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.

Add 310 tests for advanced search system modules

LearningCircuita319e50f984e
diff --git a/tests/advanced_search_system/candidate_exploration/test_constraint_guided_explorer.py b/tests/advanced_search_system/candidate_exploration/test_constraint_guided_explorer.py
new file mode 100644
index 0000000000..c88c14e6a5
--- /dev/null
+++ b/tests/advanced_search_system/candidate_exploration/test_constraint_guided_explorer.py
@@ -0,0 +1,858 @@
+"""
+Tests for the ConstraintGuidedExplorer class.
+
+Tests cover:
+- Initialization and configuration
+- Constraint prioritization
+- Constraint-specific query generation
+- Cross-constraint exploration
+- Early validation of candidates
+- Name pattern queries
+"""
+
+from dataclasses import dataclass, field
+from enum import Enum
+from typing import Any, Dict
+from unittest.mock import Mock
+
+
+class MockConstraintType(Enum):
+ """Mock constraint type for testing."""
+
+ PROPERTY = "property"
+ NAME_PATTERN = "name_pattern"
+ EVENT = "event"
+ LOCATION = "location"
+ TEMPORAL = "temporal"
+ STATISTIC = "statistic"
+ COMPARISON = "comparison"
+ EXISTENCE = "existence"
+
+
+@dataclass
+class MockConstraint:
+ """Mock constraint for testing."""
+
+ id: str = "c1"
+ value: str = "test constraint"
+ weight: float = 1.0
+ type: MockConstraintType = MockConstraintType.PROPERTY
+ description: str = ""
+
+
+@dataclass
+class MockCandidate:
+ """Mock candidate for testing."""
+
+ name: str
+ metadata: Dict[str, Any] = field(default_factory=dict)
+
+
+class TestConstraintGuidedExplorerInit:
+ """Tests for ConstraintGuidedExplorer initialization."""
+
+ def test_init_with_defaults(self):
+ """Initialize with default values."""
+ from src.local_deep_research.advanced_search_system.candidate_exploration.constraint_guided_explorer import (
+ ConstraintGuidedExplorer,
+ )
+
+ mock_model = Mock()
+ mock_engine = Mock()
+
+ explorer = ConstraintGuidedExplorer(mock_model, mock_engine)
+
+ assert explorer.constraint_weight_threshold == 0.7
+ assert explorer.early_validation is True
+
+ def test_init_with_custom_weight_threshold(self):
+ """Initialize with custom constraint weight threshold."""
+ from src.local_deep_research.advanced_search_system.candidate_exploration.constraint_guided_explorer import (
+ ConstraintGuidedExplorer,
+ )
+
+ mock_model = Mock()
+ mock_engine = Mock()
+
+ explorer = ConstraintGuidedExplorer(
+ mock_model, mock_engine, constraint_weight_threshold=0.5
+ )
+
+ assert explorer.constraint_weight_threshold == 0.5
+
+ def test_init_with_early_validation_disabled(self):
+ """Initialize with early validation disabled."""
+ from src.local_deep_research.advanced_search_system.candidate_exploration.constraint_guided_explorer import (
+ ConstraintGuidedExplorer,
+ )
+
+ mock_model = Mock()
+ mock_engine = Mock()
+
+ explorer = ConstraintGuidedExplorer(
+ mock_model, mock_engine, early_validation=False
+ )
+
+ assert explorer.early_validation is False
+
+ def test_init_stores_model_and_engine(self):
+ """Stores model and search engine references."""
+ from src.local_deep_research.advanced_search_system.candidate_exploration.constraint_guided_explorer import (
+ ConstraintGuidedExplorer,
+ )
+
+ mock_model = Mock()
+ mock_engine = Mock()
+
+ explorer = ConstraintGuidedExplorer(mock_model, mock_engine)
+
+ assert explorer.model is mock_model
+ assert explorer.search_engine is mock_engine
+
+
+class TestPrioritizeConstraints:
+ """Tests for _prioritize_constraints method."""
+
+ def test_sorts_by_weight_descending(self):
+ """Sorts constraints by weight in descending order."""
+ from src.local_deep_research.advanced_search_system.candidate_exploration.constraint_guided_explorer import (
+ ConstraintGuidedExplorer,
+ )
+ from src.local_deep_research.advanced_search_system.constraints.base_constraint import (
+ Constraint,
+ ConstraintType,
+ )
+
+ mock_model = Mock()
+ mock_engine = Mock()
+ explorer = ConstraintGuidedExplorer(mock_model, mock_engine)
+
+ constraints = [
+ Constraint(
+ id="c1",
+ type=ConstraintType.PROPERTY,
+ description="",
+ value="low",
+ weight=0.3,
+ ),
+ Constraint(
+ id="c2",
+ type=ConstraintType.PROPERTY,
+ description="",
+ value="high",
+ weight=0.9,
+ ),
+ Constraint(
+ id="c3",
+ type=ConstraintType.PROPERTY,
+ description="",
+ value="medium",
+ weight=0.6,
+ ),
+ ]
+
+ result = explorer._prioritize_constraints(constraints)
+
+ assert result[0].value == "high"
+ assert result[1].value == "medium"
+ assert result[2].value == "low"
+
+ def test_sorts_by_type_priority_when_weights_equal(self):
+ """Sorts by type priority as secondary key when weights are equal."""
+ from src.local_deep_research.advanced_search_system.candidate_exploration.constraint_guided_explorer import (
+ ConstraintGuidedExplorer,
+ )
+ from src.local_deep_research.advanced_search_system.constraints.base_constraint import (
+ Constraint,
+ ConstraintType,
+ )
+
+ mock_model = Mock()
+ mock_engine = Mock()
+ explorer = ConstraintGuidedExplorer(mock_model, mock_engine)
+
+ # Same weight, different types
+ constraints = [
+ Constraint(
+ id="c1",
+ type=ConstraintType.PROPERTY,
+ description="",
+ value="prop",
+ weight=1.0,
+ ),
+ Constraint(
+ id="c2",
+ type=ConstraintType.NAME_PATTERN,
+ description="",
+ value="name",
+ weight=1.0,
+ ),
+ ]
+
+ result = explorer._prioritize_constraints(constraints)
+
+ # With reverse=True sort and type_priority (NAME=1, PROPERTY=2),
+ # PROPERTY (2) comes before NAME_PATTERN (1) when sorted descending
+ assert result[0].type == ConstraintType.PROPERTY
+ assert result[1].type == ConstraintType.NAME_PATTERN
+
+ def test_handles_empty_constraints(self):
+ """Handles empty constraints list."""
+ from src.local_deep_research.advanced_search_system.candidate_exploration.constraint_guided_explorer import (
+ ConstraintGuidedExplorer,
+ )
+
+ mock_model = Mock()
+ mock_engine = Mock()
+ explorer = ConstraintGuidedExplorer(mock_model, mock_engine)
+
+ result = explorer._prioritize_constraints([])
+
+ assert result == []
+
+
+class TestGenerateConstraintQueries:
+ """Tests for _generate_constraint_queries method."""
+
+ def test_generates_base_constraint_query(self):
+ """Generates basic query combining base and constraint."""
+ from src.local_deep_research.advanced_search_system.candidate_exploration.constraint_guided_explorer import (
+ ConstraintGuidedExplorer,
+ )
+ from src.local_deep_research.advanced_search_system.constraints.base_constraint import (
+ Constraint,
+ ConstraintType,
+ )
+
+ mock_model = Mock()
+ mock_engine = Mock()
+ explorer = ConstraintGuidedExplorer(mock_model, mock_engine)
+
+ constraint = Constraint(
+ id="c1",
+ type=ConstraintType.PROPERTY,
+ description="test",
+ value="formed during ice age",
+ )
+
+ queries = explorer._generate_constraint_queries(
+ constraint, "Colorado mountain trail"
+ )
+
+ # Should have base query with constraint value
+ assert any("formed during ice age" in q for q in queries)
+
+ def test_uses_entity_type_when_provided(self):
+ """Uses entity type in query when provided."""
+ from src.local_deep_research.advanced_search_system.candidate_exploration.constraint_guided_explorer import (
+ ConstraintGuidedExplorer,
+ )
+ from src.local_deep_research.advanced_search_system.constraints.base_constraint import (
+ Constraint,
+ ConstraintType,
+ )
+
+ mock_model = Mock()
+ mock_engine = Mock()
+ explorer = ConstraintGuidedExplorer(mock_model, mock_engine)
+
+ constraint = Constraint(
+ id="c1",
+ type=ConstraintType.PROPERTY,
+ description="test",
+ value="test property",
+ )
+
+ queries = explorer._generate_constraint_queries(
+ constraint, "base query", entity_type="mountain trail"
+ )
+
+ assert any("mountain trail" in q for q in queries)
+
+
+class TestNamePatternQueries:
+ """Tests for _name_pattern_queries method."""
+
+ def test_generates_body_part_queries(self):
+ """Generates queries for body part name patterns."""
+ from src.local_deep_research.advanced_search_system.candidate_exploration.constraint_guided_explorer import (
+ ConstraintGuidedExplorer,
+ )
+ from src.local_deep_research.advanced_search_system.constraints.base_constraint import (
+ Constraint,
+ ConstraintType,
+ )
+
+ mock_model = Mock()
+ mock_engine = Mock()
+ explorer = ConstraintGuidedExplorer(mock_model, mock_engine)
+
+ constraint = Constraint(
+ id="c1",
+ type=ConstraintType.NAME_PATTERN,
+ description="body part",
+ value="name contains body part",
+ )
+
+ queries = explorer._name_pattern_queries(
+ constraint, "trail", entity_type=None
+ )
+
+ # Should generate queries with body part words
+ assert len(queries) > 0
+ body_parts = ["arm", "leg", "foot", "hand", "eye", "ear", "head"]
+ assert any(
+ any(part in q.lower() for part in body_parts) for q in queries
+ )
+
+ def test_uses_entity_type_for_body_parts(self):
+ """Uses entity type when generating body part queries."""
+ from src.local_deep_research.advanced_search_system.candidate_exploration.constraint_guided_explorer import (
+ ConstraintGuidedExplorer,
+ )
+ from src.local_deep_research.advanced_search_system.constraints.base_constraint import (
+ Constraint,
+ ConstraintType,
+ )
+
+ mock_model = Mock()
+ mock_engine = Mock()
+ explorer = ConstraintGuidedExplorer(mock_model, mock_engine)
+
+ constraint = Constraint(
+ id="c1",
+ type=ConstraintType.NAME_PATTERN,
+ description="body part",
+ value="body part in name",
+ )
+
+ queries = explorer._name_pattern_queries(
+ constraint, "base", entity_type="mountain trail"
+ )
+
+ assert any("mountain trail" in q for q in queries)
+
+
+class TestPropertyQueries:
+ """Tests for _property_queries method."""
+
+ def test_generates_property_query_variations(self):
+ """Generates multiple property query variations."""
+ from src.local_deep_research.advanced_search_system.candidate_exploration.constraint_guided_explorer import (
+ ConstraintGuidedExplorer,
+ )
+ from src.local_deep_research.advanced_search_system.constraints.base_constraint import (
+ Constraint,
+ ConstraintType,
+ )
+
+ mock_model = Mock()
+ mock_engine = Mock()
+ explorer = ConstraintGuidedExplorer(mock_model, mock_engine)
+
+ constraint = Constraint(
+ id="c1",
+ type=ConstraintType.PROPERTY,
+ description="test",
+ value="ice age formation",
+ )
+
+ queries = explorer._property_queries(
+ constraint, "trails", entity_type=None
+ )
+
+ assert len(queries) >= 2
+ assert any("with" in q for q in queries)
+ assert any("that" in q for q in queries)
+
+
+class TestEventQueries:
+ """Tests for _event_queries method."""
+
+ def test_generates_event_queries_with_incident_keyword(self):
+ """Generates event queries with incident/accident keywords."""
+ from src.local_deep_research.advanced_search_system.candidate_exploration.constraint_guided_explorer import (
+ ConstraintGuidedExplorer,
+ )
+ from src.local_deep_research.advanced_search_system.constraints.base_constraint import (
+ Constraint,
+ ConstraintType,
+ )
+
+ mock_model = Mock()
+ mock_engine = Mock()
+ explorer = ConstraintGuidedExplorer(mock_model, mock_engine)
+
+ constraint = Constraint(
+ id="c1",
+ type=ConstraintType.EVENT,
+ description="fall event",
+ value="deadly fall 2000-2021",
+ )
+
+ queries = explorer._event_queries(constraint, "trail", entity_type=None)
+
+ assert any("incident" in q.lower() for q in queries)
+ assert any("accident" in q.lower() for q in queries)
+
+
+class TestLocationQueries:
+ """Tests for _location_queries method."""
+
+ def test_generates_location_queries(self):
+ """Generates location-specific queries."""
+ from src.local_deep_research.advanced_search_system.candidate_exploration.constraint_guided_explorer import (
+ ConstraintGuidedExplorer,
+ )
+ from src.local_deep_research.advanced_search_system.constraints.base_constraint import (
+ Constraint,
+ ConstraintType,
+ )
+
+ mock_model = Mock()
+ mock_engine = Mock()
+ explorer = ConstraintGuidedExplorer(mock_model, mock_engine)
+
+ constraint = Constraint(
+ id="c1",
+ type=ConstraintType.LOCATION,
+ description="location",
+ value="Colorado",
+ )
+
+ queries = explorer._location_queries(
+ constraint, "mountain trail", entity_type=None
+ )
+
+ assert any("Colorado" in q for q in queries)
+ assert any("in Colorado" in q or "Colorado" in q for q in queries)
+
+
+class TestCombineConstraintsQuery:
+ """Tests for _combine_constraints_query method."""
+
+ def test_combines_two_constraints(self):
+ """Combines two constraints into one query."""
+ from src.local_deep_research.advanced_search_system.candidate_exploration.constraint_guided_explorer import (
+ ConstraintGuidedExplorer,
+ )
+ from src.local_deep_research.advanced_search_system.constraints.base_constraint import (
+ Constraint,
+ ConstraintType,
+ )
+
+ mock_model = Mock()
+ mock_engine = Mock()
+ explorer = ConstraintGuidedExplorer(mock_model, mock_engine)
+
+ constraints = [
+ Constraint(
+ id="c1",
+ type=ConstraintType.PROPERTY,
+ description="",
+ value="ice age",
+ ),
+ Constraint(
+ id="c2",
+ type=ConstraintType.LOCATION,
+ description="",
+ value="Colorado",
+ ),
+ ]
+
+ query = explorer._combine_constraints_query("trail", constraints)
+
+ assert query is not None
+ assert "ice age" in query
+ assert "Colorado" in query
+ assert "AND" in query
+
+ def test_returns_none_for_single_constraint(self):
+ """Returns None when only one constraint provided."""
+ from src.local_deep_research.advanced_search_system.candidate_exploration.constraint_guided_explorer import (
+ ConstraintGuidedExplorer,
+ )
+ from src.local_deep_research.advanced_search_system.constraints.base_constraint import (
+ Constraint,
+ ConstraintType,
+ )
+
+ mock_model = Mock()
+ mock_engine = Mock()
+ explorer = ConstraintGuidedExplorer(mock_model, mock_engine)
+
+ constraints = [
+ Constraint(
+ id="c1",
+ type=ConstraintType.PROPERTY,
+ description="",
+ value="ice age",
+ ),
+ ]
+
+ query = explorer._combine_constraints_query("trail", constraints)
+
+ assert query is None
+
+ def test_returns_none_for_empty_constraints(self):
+ """Returns None for empty constraints list."""
+ from src.local_deep_research.advanced_search_system.candidate_exploration.constraint_guided_explorer import (
+ ConstraintGuidedExplorer,
+ )
+
+ mock_model = Mock()
+ mock_engine = Mock()
+ explorer = ConstraintGuidedExplorer(mock_model, mock_engine)
+
+ query = explorer._combine_constraints_query("trail", [])
+
+ assert query is None
+
+
+class TestQuickNameValidation:
+ """Tests for _quick_name_validation method."""
+
+ def test_validates_body_part_in_name(self):
+ """Validates names containing body parts."""
+ from src.local_deep_research.advanced_search_system.candidate_exploration.constraint_guided_explorer import (
+ ConstraintGuidedExplorer,
+ )
+ from src.local_deep_research.advanced_search_system.constraints.base_constraint import (
+ Constraint,
+ ConstraintType,
+ )
+
+ mock_model = Mock()
+ mock_engine = Mock()
+ explorer = ConstraintGuidedExplorer(mock_model, mock_engine)
+
+ constraint = Constraint(
+ id="c1",
+ type=ConstraintType.NAME_PATTERN,
+ description="body part",
+ value="contains body part",
+ )
+
+ assert (
+ explorer._quick_name_validation("Heart Mountain", constraint)
+ is True
+ )
+ assert (
+ explorer._quick_name_validation("Arm Creek Trail", constraint)
+ is True
+ )
+ assert explorer._quick_name_validation("Foot Lake", constraint) is True
+
+ def test_rejects_names_without_body_part(self):
+ """Rejects names without body parts."""
+ from src.local_deep_research.advanced_search_system.candidate_exploration.constraint_guided_explorer import (
+ ConstraintGuidedExplorer,
+ )
+ from src.local_deep_research.advanced_search_system.constraints.base_constraint import (
+ Constraint,
+ ConstraintType,
+ )
+
+ mock_model = Mock()
+ mock_engine = Mock()
+ explorer = ConstraintGuidedExplorer(mock_model, mock_engine)
+
+ constraint = Constraint(
+ id="c1",
+ type=ConstraintType.NAME_PATTERN,
+ description="body part",
+ value="body part in name",
+ )
+
+ assert (
+ explorer._quick_name_validation("Pine Mountain", constraint)
+ is False
+ )
+ assert (
+ explorer._quick_name_validation("Blue Lake Trail", constraint)
+ is False
+ )
+
+ def test_accepts_non_body_part_constraints(self):
+ """Accepts candidates for non-body-part constraints."""
+ from src.local_deep_research.advanced_search_system.candidate_exploration.constraint_guided_explorer import (
+ ConstraintGuidedExplorer,
+ )
+ from src.local_deep_research.advanced_search_system.constraints.base_constraint import (
+ Constraint,
+ ConstraintType,
+ )
+
+ mock_model = Mock()
+ mock_engine = Mock()
+ explorer = ConstraintGuidedExplorer(mock_model, mock_engine)
+
+ # Non-body-part name pattern
+ constraint = Constraint(
+ id="c1",
+ type=ConstraintType.NAME_PATTERN,
+ description="other pattern",
+ value="starts with letter",
+ )
+
+ # Should accept by default
+ assert explorer._quick_name_validation("Any Name", constraint) is True
+
+
+class TestEarlyValidateCandidates:
+ """Tests for _early_validate_candidates method."""
+
+ def test_validates_name_pattern_candidates(self):
+ """Validates candidates for NAME_PATTERN constraints."""
+ from src.local_deep_research.advanced_search_system.candidate_exploration.constraint_guided_explorer import (
+ ConstraintGuidedExplorer,
+ )
+ from src.local_deep_research.advanced_search_system.constraints.base_constraint import (
+ Constraint,
+ ConstraintType,
+ )
+ from src.local_deep_research.advanced_search_system.candidates.base_candidate import (
+ Candidate,
+ )
+
+ mock_model = Mock()
+ mock_engine = Mock()
+ explorer = ConstraintGuidedExplorer(mock_model, mock_engine)
+
+ constraint = Constraint(
+ id="c1",
+ type=ConstraintType.NAME_PATTERN,
+ description="body part",
+ value="body part in name",
+ )
+
+ candidates = [
+ Candidate(name="Heart Mountain"),
+ Candidate(name="Pine Trail"),
+ Candidate(name="Arm Lake"),
+ ]
+
+ validated = explorer._early_validate_candidates(candidates, constraint)
+
+ assert len(validated) == 2
+ names = [c.name for c in validated]
+ assert "Heart Mountain" in names
+ assert "Arm Lake" in names
+ assert "Pine Trail" not in names
+
+ def test_skips_validation_for_non_name_pattern(self):
+ """Skips validation for non-NAME_PATTERN constraints."""
+ from src.local_deep_research.advanced_search_system.candidate_exploration.constraint_guided_explorer import (
+ ConstraintGuidedExplorer,
+ )
+ from src.local_deep_research.advanced_search_system.constraints.base_constraint import (
+ Constraint,
+ ConstraintType,
+ )
+ from src.local_deep_research.advanced_search_system.candidates.base_candidate import (
+ Candidate,
+ )
+
+ mock_model = Mock()
+ mock_engine = Mock()
+ explorer = ConstraintGuidedExplorer(mock_model, mock_engine)
+
+ constraint = Constraint(
+ id="c1",
+ type=ConstraintType.PROPERTY,
+ description="property",
+ value="ice age formation",
+ )
+
+ candidates = [
+ Candidate(name="Pine Trail"),
+ Candidate(name="Oak Mountain"),
+ ]
+
+ validated = explorer._early_validate_candidates(candidates, constraint)
+
+ # All candidates should pass through
+ assert len(validated) == 2
+
+
+class TestCrossConstraintExploration:
+ """Tests for _cross_constraint_exploration method."""
+
+ def test_requires_at_least_two_constraints(self):
+ """Requires at least two constraints for cross-exploration."""
+ from src.local_deep_research.advanced_search_system.candidate_exploration.constraint_guided_explorer import (
+ ConstraintGuidedExplorer,
+ )
+ from src.local_deep_research.advanced_search_system.constraints.base_constraint import (
+ Constraint,
+ ConstraintType,
+ )
+
+ mock_model = Mock()
+ mock_engine = Mock()
+ explorer = ConstraintGuidedExplorer(mock_model, mock_engine)
+
+ constraints = [
+ Constraint(
+ id="c1",
+ type=ConstraintType.PROPERTY,
+ description="",
+ value="test",
+ ),
+ ]
+
+ result = explorer._cross_constraint_exploration(
+ constraints, "query", None
+ )
+
+ assert result == []
+
+
+class TestExplore:
+ """Tests for explore method."""
+
+ def test_explore_returns_exploration_result(self):
+ """Explore returns ExplorationResult."""
+ from src.local_deep_research.advanced_search_system.candidate_exploration.constraint_guided_explorer import (
+ ConstraintGuidedExplorer,
+ )
+ from src.local_deep_research.advanced_search_system.candidate_exploration.base_explorer import (
+ ExplorationResult,
+ )
+
+ mock_model = Mock()
+ mock_engine = Mock()
+ mock_engine.run.return_value = []
+ explorer = ConstraintGuidedExplorer(mock_model, mock_engine)
+
+ result = explorer.explore("test query")
+
+ assert isinstance(result, ExplorationResult)
+
+ def test_explore_without_constraints_uses_basic(self):
+ """Explore without constraints falls back to basic search."""
+ from src.local_deep_research.advanced_search_system.candidate_exploration.constraint_guided_explorer import (
+ ConstraintGuidedExplorer,
+ )
+ from src.local_deep_research.advanced_search_system.candidate_exploration.base_explorer import (
+ ExplorationStrategy,
+ )
+
+ mock_model = Mock()
+ mock_engine = Mock()
+ mock_engine.run.return_value = []
+ explorer = ConstraintGuidedExplorer(mock_model, mock_engine)
+
+ result = explorer.explore("test query", constraints=None)
+
+ # Falls back to basic strategy
+ assert result.strategy_used == ExplorationStrategy.BREADTH_FIRST
+
+ def test_explore_with_constraints_uses_constraint_guided(self):
+ """Explore with constraints uses constraint-guided strategy."""
+ from src.local_deep_research.advanced_search_system.candidate_exploration.constraint_guided_explorer import (
+ ConstraintGuidedExplorer,
+ )
+ from src.local_deep_research.advanced_search_system.candidate_exploration.base_explorer import (
+ ExplorationStrategy,
+ )
+ from src.local_deep_research.advanced_search_system.constraints.base_constraint import (
+ Constraint,
+ ConstraintType,
+ )
+
+ mock_model = Mock()
+ mock_engine = Mock()
+ mock_engine.run.return_value = []
+ explorer = ConstraintGuidedExplorer(mock_model, mock_engine)
+
+ constraints = [
+ Constraint(
+ id="c1",
+ type=ConstraintType.PROPERTY,
+ description="",
+ value="test",
+ ),
+ ]
+
+ result = explorer.explore("test query", constraints=constraints)
+
+ assert result.strategy_used == ExplorationStrategy.CONSTRAINT_GUIDED
+
+ def test_explore_records_metadata(self):
+ """Explore records metadata about the exploration."""
+ from src.local_deep_research.advanced_search_system.candidate_exploration.constraint_guided_explorer import (
+ ConstraintGuidedExplorer,
+ )
+ from src.local_deep_research.advanced_search_system.constraints.base_constraint import (
+ Constraint,
+ ConstraintType,
+ )
+
+ mock_model = Mock()
+ mock_engine = Mock()
+ mock_engine.run.return_value = []
+ explorer = ConstraintGuidedExplorer(mock_model, mock_engine)
+
+ constraints = [
+ Constraint(
+ id="c1",
+ type=ConstraintType.PROPERTY,
+ description="",
+ value="test",
+ ),
+ ]
+
+ result = explorer.explore("test query", constraints=constraints)
+
+ assert "strategy" in result.metadata
+ assert result.metadata["strategy"] == "constraint_guided"
+ assert "early_validation" in result.metadata
+
+
+class TestGenerateExplorationQueries:
+ """Tests for generate_exploration_queries method."""
+
+ def test_returns_base_query_without_constraints(self):
+ """Returns base query when no constraints provided."""
+ from src.local_deep_research.advanced_search_system.candidate_exploration.constraint_guided_explorer import (
+ ConstraintGuidedExplorer,
+ )
+
+ mock_model = Mock()
+ mock_engine = Mock()
+ explorer = ConstraintGuidedExplorer(mock_model, mock_engine)
+
+ queries = explorer.generate_exploration_queries("base query", [])
+
+ assert queries == ["base query"]
+
+ def test_generates_queries_from_constraints(self):
+ """Generates queries from constraints."""
+ from src.local_deep_research.advanced_search_system.candidate_exploration.constraint_guided_explorer import (
+ ConstraintGuidedExplorer,
+ )
+ from src.local_deep_research.advanced_search_system.constraints.base_constraint import (
+ Constraint,
+ ConstraintType,
+ )
+
+ mock_model = Mock()
+ mock_engine = Mock()
+ explorer = ConstraintGuidedExplorer(mock_model, mock_engine)
+
+ constraints = [
+ Constraint(
+ id="c1",
+ type=ConstraintType.PROPERTY,
+ description="",
+ value="ice age",
+ ),
+ ]
+
+ queries = explorer.generate_exploration_queries(
+ "trail", [], constraints=constraints
+ )
+
+ assert len(queries) > 0
+ assert any("ice age" in q for q in queries)
diff --git a/tests/advanced_search_system/candidate_exploration/test_parallel_explorer.py b/tests/advanced_search_system/candidate_exploration/test_parallel_explorer.py
new file mode 100644
index 0000000000..f455fb543a
--- /dev/null
+++ b/tests/advanced_search_system/candidate_exploration/test_parallel_explorer.py
@@ -0,0 +1,536 @@
+"""
+Tests for the ParallelExplorer class.
+
+Tests cover:
+- Initialization with worker settings
+- Query variation generation
+- Candidate-based query generation
+- Constraint-based query generation
+- Query generation methods
+"""
+
+from dataclasses import dataclass, field
+from enum import Enum
+from typing import Any, Dict
+from unittest.mock import Mock
+
+
+class MockConstraintType(Enum):
+ """Mock constraint type for testing."""
+
+ PROPERTY = "property"
+ NAME_PATTERN = "name_pattern"
+
+
+@dataclass
+class MockConstraint:
+ """Mock constraint for testing."""
+
+ id: str = "c1"
+ value: str = "test constraint"
+ weight: float = 1.0
+ type: MockConstraintType = MockConstraintType.PROPERTY
+ description: str = ""
+
+
+@dataclass
+class MockCandidate:
+ """Mock candidate for testing."""
+
+ name: str
+ metadata: Dict[str, Any] = field(default_factory=dict)
+
+
+class TestParallelExplorerInit:
+ """Tests for ParallelExplorer initialization."""
+
+ def test_init_with_defaults(self):
+ """Initialize with default values."""
+ from src.local_deep_research.advanced_search_system.candidate_exploration.parallel_explorer import (
+ ParallelExplorer,
+ )
+
+ mock_model = Mock()
+ mock_engine = Mock()
+
+ explorer = ParallelExplorer(mock_model, mock_engine)
+
+ assert explorer.max_workers == 5
+ assert explorer.queries_per_round == 8
+ assert explorer.max_rounds == 3
+
+ def test_init_with_custom_max_workers(self):
+ """Initialize with custom max workers."""
+ from src.local_deep_research.advanced_search_system.candidate_exploration.parallel_explorer import (
+ ParallelExplorer,
+ )
+
+ mock_model = Mock()
+ mock_engine = Mock()
+
+ explorer = ParallelExplorer(mock_model, mock_engine, max_workers=10)
+
+ assert explorer.max_workers == 10
+
+ def test_init_with_custom_queries_per_round(self):
+ """Initialize with custom queries per round."""
+ from src.local_deep_research.advanced_search_system.candidate_exploration.parallel_explorer import (
+ ParallelExplorer,
+ )
+
+ mock_model = Mock()
+ mock_engine = Mock()
+
+ explorer = ParallelExplorer(
+ mock_model, mock_engine, queries_per_round=15
+ )
+
+ assert explorer.queries_per_round == 15
+
+ def test_init_with_custom_max_rounds(self):
+ """Initialize with custom max rounds."""
+ from src.local_deep_research.advanced_search_system.candidate_exploration.parallel_explorer import (
+ ParallelExplorer,
+ )
+
+ mock_model = Mock()
+ mock_engine = Mock()
+
+ explorer = ParallelExplorer(mock_model, mock_engine, max_rounds=5)
+
+ assert explorer.max_rounds == 5
+
+ def test_init_stores_model_and_engine(self):
+ """Stores model and search engine references."""
+ from src.local_deep_research.advanced_search_system.candidate_exploration.parallel_explorer import (
+ ParallelExplorer,
+ )
+
+ mock_model = Mock()
+ mock_engine = Mock()
+
+ explorer = ParallelExplorer(mock_model, mock_engine)
+
+ assert explorer.model is mock_model
+ assert explorer.search_engine is mock_engine
+
+
+class TestGenerateQueryVariations:
+ """Tests for _generate_query_variations method."""
+
+ def test_generates_variations_from_llm(self):
+ """Generates query variations using LLM."""
+ from src.local_deep_research.advanced_search_system.candidate_exploration.parallel_explorer import (
+ ParallelExplorer,
+ )
+
+ mock_model = Mock()
+ mock_model.invoke.return_value.content = """
+ 1. Colorado mountain trails
+ 2. hiking trails in Colorado
+ 3. Colorado hiking paths
+ 4. mountain trails Colorado state
+ """
+ mock_engine = Mock()
+
+ explorer = ParallelExplorer(mock_model, mock_engine)
+
+ variations = explorer._generate_query_variations("Colorado trails")
+
+ assert len(variations) == 4
+ assert "Colorado mountain trails" in variations
+
+ def test_handles_llm_exception(self):
+ """Returns empty list on LLM exception."""
+ from src.local_deep_research.advanced_search_system.candidate_exploration.parallel_explorer import (
+ ParallelExplorer,
+ )
+
+ mock_model = Mock()
+ mock_model.invoke.side_effect = Exception("LLM error")
+ mock_engine = Mock()
+
+ explorer = ParallelExplorer(mock_model, mock_engine)
+
+ variations = explorer._generate_query_variations("test query")
+
+ assert variations == []
+
+ def test_limits_to_four_variations(self):
+ """Limits variations to 4 max."""
+ from src.local_deep_research.advanced_search_system.candidate_exploration.parallel_explorer import (
+ ParallelExplorer,
+ )
+
+ mock_model = Mock()
+ mock_model.invoke.return_value.content = """
+ 1. var1
+ 2. var2
+ 3. var3
+ 4. var4
+ 5. var5
+ 6. var6
+ """
+ mock_engine = Mock()
+
+ explorer = ParallelExplorer(mock_model, mock_engine)
+
+ variations = explorer._generate_query_variations("test")
+
+ assert len(variations) <= 4
+
+ def test_parses_numbered_list(self):
+ """Parses numbered list format."""
+ from src.local_deep_research.advanced_search_system.candidate_exploration.parallel_explorer import (
+ ParallelExplorer,
+ )
+
+ mock_model = Mock()
+ mock_model.invoke.return_value.content = (
+ "1. first query\n2. second query\n3. third"
+ )
+ mock_engine = Mock()
+
+ explorer = ParallelExplorer(mock_model, mock_engine)
+
+ variations = explorer._generate_query_variations("test")
+
+ assert "first query" in variations
+ assert "second query" in variations
+ assert "third" in variations
+
+ def test_handles_empty_response(self):
+ """Handles empty LLM response."""
+ from src.local_deep_research.advanced_search_system.candidate_exploration.parallel_explorer import (
+ ParallelExplorer,
+ )
+
+ mock_model = Mock()
+ mock_model.invoke.return_value.content = ""
+ mock_engine = Mock()
+
+ explorer = ParallelExplorer(mock_model, mock_engine)
+
+ variations = explorer._generate_query_variations("test")
+
+ assert variations == []
+
+
+class TestGenerateCandidateBasedQueries:
+ """Tests for _generate_candidate_based_queries method."""
+
+ def test_generates_queries_from_candidates(self):
+ """Generates queries based on found candidates."""
+ from src.local_deep_research.advanced_search_system.candidate_exploration.parallel_explorer import (
+ ParallelExplorer,
+ )
+ from src.local_deep_research.advanced_search_system.candidates.base_candidate import (
+ Candidate,
+ )
+
+ mock_model = Mock()
+ mock_engine = Mock()
+
+ explorer = ParallelExplorer(mock_model, mock_engine)
+
+ candidates = [
+ Candidate(name="Heart Mountain Trail"),
+ Candidate(name="Arm Creek Path"),
+ ]
+
+ queries = explorer._generate_candidate_based_queries(
+ candidates, "trails"
+ )
+
+ assert len(queries) > 0
+ assert any("Heart Mountain Trail" in q for q in queries)
+
+ def test_limits_to_sample_candidates(self):
+ """Only samples first 3 candidates."""
+ from src.local_deep_research.advanced_search_system.candidate_exploration.parallel_explorer import (
+ ParallelExplorer,
+ )
+ from src.local_deep_research.advanced_search_system.candidates.base_candidate import (
+ Candidate,
+ )
+
+ mock_model = Mock()
+ mock_engine = Mock()
+
+ explorer = ParallelExplorer(mock_model, mock_engine)
+
+ candidates = [Candidate(name=f"Candidate {i}") for i in range(10)]
+
+ queries = explorer._generate_candidate_based_queries(candidates, "base")
+
+ # 2 queries per candidate, 3 candidates = 6 queries max
+ assert len(queries) <= 6
+
+ def test_generates_similar_and_like_queries(self):
+ """Generates 'similar to' and 'like' queries."""
+ from src.local_deep_research.advanced_search_system.candidate_exploration.parallel_explorer import (
+ ParallelExplorer,
+ )
+ from src.local_deep_research.advanced_search_system.candidates.base_candidate import (
+ Candidate,
+ )
+
+ mock_model = Mock()
+ mock_engine = Mock()
+
+ explorer = ParallelExplorer(mock_model, mock_engine)
+
+ candidates = [Candidate(name="Test Name")]
+
+ queries = explorer._generate_candidate_based_queries(candidates, "base")
+
+ assert any("similar to" in q.lower() for q in queries)
+ assert any("like" in q.lower() for q in queries)
+
+
+class TestGenerateConstraintQueries:
+ """Tests for _generate_constraint_queries method."""
+
+ def test_generates_queries_from_constraints(self):
+ """Generates queries from constraints."""
+ from src.local_deep_research.advanced_search_system.candidate_exploration.parallel_explorer import (
+ ParallelExplorer,
+ )
+ from src.local_deep_research.advanced_search_system.constraints.base_constraint import (
+ Constraint,
+ ConstraintType,
+ )
+
+ mock_model = Mock()
+ mock_engine = Mock()
+
+ explorer = ParallelExplorer(mock_model, mock_engine)
+
+ constraints = [
+ Constraint(
+ id="c1",
+ type=ConstraintType.PROPERTY,
+ description="",
+ value="ice age formation",
+ ),
+ ]
+
+ queries = explorer._generate_constraint_queries(constraints, "trail")
+
+ assert len(queries) > 0
+ assert any("ice age formation" in q for q in queries)
+
+ def test_limits_to_two_constraints(self):
+ """Only uses first 2 constraints."""
+ from src.local_deep_research.advanced_search_system.candidate_exploration.parallel_explorer import (
+ ParallelExplorer,
+ )
+ from src.local_deep_research.advanced_search_system.constraints.base_constraint import (
+ Constraint,
+ ConstraintType,
+ )
+
+ mock_model = Mock()
+ mock_engine = Mock()
+
+ explorer = ParallelExplorer(mock_model, mock_engine)
+
+ constraints = [
+ Constraint(
+ id=f"c{i}",
+ type=ConstraintType.PROPERTY,
+ description="",
+ value=f"value{i}",
+ )
+ for i in range(5)
+ ]
+
+ queries = explorer._generate_constraint_queries(constraints, "base")
+
+ # 2 queries per constraint, 2 constraints = 4 queries max
+ assert len(queries) <= 4
+
+ def test_generates_examples_query(self):
+ """Generates 'examples' query for constraints."""
+ from src.local_deep_research.advanced_search_system.candidate_exploration.parallel_explorer import (
+ ParallelExplorer,
+ )
+ from src.local_deep_research.advanced_search_system.constraints.base_constraint import (
+ Constraint,
+ ConstraintType,
+ )
+
+ mock_model = Mock()
+ mock_engine = Mock()
+
+ explorer = ParallelExplorer(mock_model, mock_engine)
+
+ constraints = [
+ Constraint(
+ id="c1",
+ type=ConstraintType.PROPERTY,
+ description="",
+ value="test value",
+ ),
+ ]
+
+ queries = explorer._generate_constraint_queries(constraints, "base")
+
+ assert any("examples" in q for q in queries)
+
+
+class TestGenerateExplorationQueries:
+ """Tests for generate_exploration_queries method."""
+
+ def test_combines_all_query_sources(self):
+ """Combines queries from all sources."""
+ from src.local_deep_research.advanced_search_system.candidate_exploration.parallel_explorer import (
+ ParallelExplorer,
+ )
+ from src.local_deep_research.advanced_search_system.candidates.base_candidate import (
+ Candidate,
+ )
+ from src.local_deep_research.advanced_search_system.constraints.base_constraint import (
+ Constraint,
+ ConstraintType,
+ )
+
+ mock_model = Mock()
+ mock_model.invoke.return_value.content = "1. variation1\n2. variation2"
+ mock_engine = Mock()
+
+ explorer = ParallelExplorer(mock_model, mock_engine)
+
+ candidates = [Candidate(name="Test Candidate")]
+ constraints = [
+ Constraint(
+ id="c1",
+ type=ConstraintType.PROPERTY,
+ description="",
+ value="test",
+ ),
+ ]
+
+ queries = explorer.generate_exploration_queries(
+ "base query", candidates, constraints
+ )
+
+ assert len(queries) > 0
+
+ def test_excludes_already_explored_queries(self):
+ """Excludes queries that have already been explored."""
+ from src.local_deep_research.advanced_search_system.candidate_exploration.parallel_explorer import (
+ ParallelExplorer,
+ )
+
+ mock_model = Mock()
+ mock_model.invoke.return_value.content = (
+ "1. already explored\n2. new query"
+ )
+ mock_engine = Mock()
+
+ explorer = ParallelExplorer(mock_model, mock_engine)
+ explorer.explored_queries.add("already explored")
+
+ queries = explorer.generate_exploration_queries("base", [])
+
+ assert "already explored" not in [q.lower() for q in queries]
+
+ def test_limits_to_queries_per_round(self):
+ """Limits output to queries_per_round."""
+ from src.local_deep_research.advanced_search_system.candidate_exploration.parallel_explorer import (
+ ParallelExplorer,
+ )
+ from src.local_deep_research.advanced_search_system.candidates.base_candidate import (
+ Candidate,
+ )
+ from src.local_deep_research.advanced_search_system.constraints.base_constraint import (
+ Constraint,
+ ConstraintType,
+ )
+
+ mock_model = Mock()
+ mock_model.invoke.return_value.content = "\n".join(
+ [f"{i}. query{i}" for i in range(1, 20)]
+ )
+ mock_engine = Mock()
+
+ explorer = ParallelExplorer(
+ mock_model, mock_engine, queries_per_round=3
+ )
+
+ candidates = [Candidate(name=f"c{i}") for i in range(10)]
+ constraints = [
+ Constraint(
+ id=f"c{i}",
+ type=ConstraintType.PROPERTY,
+ description="",
+ value=f"v{i}",
+ )
+ for i in range(5)
+ ]
+
+ queries = explorer.generate_exploration_queries(
+ "base", candidates, constraints
+ )
+
+ assert len(queries) <= 3
+
+ def test_returns_empty_when_no_new_queries(self):
+ """Returns empty list when all queries already explored."""
+ from src.local_deep_research.advanced_search_system.candidate_exploration.parallel_explorer import (
+ ParallelExplorer,
+ )
+
+ mock_model = Mock()
+ mock_model.invoke.return_value.content = "1. explored1\n2. explored2"
+ mock_engine = Mock()
+
+ explorer = ParallelExplorer(mock_model, mock_engine)
+ explorer.explored_queries.add("explored1")
+ explorer.explored_queries.add("explored2")
+
+ queries = explorer.generate_exploration_queries("base", [])
+
+ # May still have base query or be empty
+ for q in queries:
+ assert q.lower() not in ["explored1", "explored2"]
+
+
+class TestExplorationResult:
+ """Tests for exploration result structure."""
+
+ def test_result_has_required_attributes(self):
+ """ExplorationResult has required attributes."""
+ from src.local_deep_research.advanced_search_system.candidate_exploration.base_explorer import (
+ ExplorationResult,
+ ExplorationStrategy,
+ )
+
+ result = ExplorationResult(
+ candidates=[],
+ total_searched=5,
+ unique_candidates=3,
+ exploration_paths=["path1", "path2"],
+ metadata={"key": "value"},
+ elapsed_time=1.5,
+ strategy_used=ExplorationStrategy.BREADTH_FIRST,
+ )
+
+ assert result.candidates == []
+ assert result.total_searched == 5
+ assert result.unique_candidates == 3
+ assert len(result.exploration_paths) == 2
+ assert result.metadata["key"] == "value"
+ assert result.elapsed_time == 1.5
+ assert result.strategy_used == ExplorationStrategy.BREADTH_FIRST
+
+ def test_result_strategy_enum(self):
+ """ExplorationStrategy enum has expected values."""
+ from src.local_deep_research.advanced_search_system.candidate_exploration.base_explorer import (
+ ExplorationStrategy,
+ )
+
+ assert hasattr(ExplorationStrategy, "BREADTH_FIRST")
+ assert hasattr(ExplorationStrategy, "DEPTH_FIRST")
+ assert hasattr(ExplorationStrategy, "CONSTRAINT_GUIDED")
diff --git a/tests/advanced_search_system/constraint_checking/test_dual_confidence_checker.py b/tests/advanced_search_system/constraint_checking/test_dual_confidence_checker.py
new file mode 100644
index 0000000000..9eb1dfe6d2
--- /dev/null
+++ b/tests/advanced_search_system/constraint_checking/test_dual_confidence_checker.py
@@ -0,0 +1,768 @@
+"""
+Tests for the DualConfidenceChecker class.
+
+Tests cover:
+- Initialization with thresholds
+- Dual confidence scoring
+- Re-evaluation logic for uncertain results
+- LLM pre-screening
+- Rejection decisions based on positive/negative evidence
+- Weighted score calculation
+"""
+
+from dataclasses import dataclass
+from enum import Enum
+from unittest.mock import Mock
+
+
+class MockConstraintType(Enum):
+ """Mock constraint type for testing."""
+
+ PROPERTY = "property"
+ NAME_PATTERN = "name_pattern"
+
+
+@dataclass
+class MockCandidate:
+ """Mock candidate for testing."""
+
+ name: str
+ value: str = ""
+
+
+@dataclass
+class MockConstraint:
+ """Mock constraint for testing."""
+
+ value: str
+ weight: float = 1.0
+ type: MockConstraintType = MockConstraintType.PROPERTY
+
+
+@dataclass
+class MockConstraintEvidence:
+ """Mock constraint evidence for testing."""
+
+ positive_confidence: float
+ negative_confidence: float
+ uncertainty: float
+ evidence_text: str = ""
+ source: str = "test"
+
+
+class TestDualConfidenceCheckerInit:
+ """Tests for DualConfidenceChecker initialization."""
+
+ def test_init_with_defaults(self):
+ """Initialize with default thresholds."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.dual_confidence_checker import (
+ DualConfidenceChecker,
+ )
+
+ mock_model = Mock()
+ checker = DualConfidenceChecker(mock_model)
+
+ assert checker.negative_threshold == 0.25
+ assert checker.positive_threshold == 0.4
+ assert checker.uncertainty_penalty == 0.2
+ assert checker.negative_weight == 0.5
+ assert checker.uncertainty_threshold == 0.6
+ assert checker.max_reevaluations == 2
+
+ def test_init_with_custom_negative_threshold(self):
+ """Initialize with custom negative threshold."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.dual_confidence_checker import (
+ DualConfidenceChecker,
+ )
+
+ mock_model = Mock()
+ checker = DualConfidenceChecker(mock_model, negative_threshold=0.3)
+
+ assert checker.negative_threshold == 0.3
+
+ def test_init_with_custom_positive_threshold(self):
+ """Initialize with custom positive threshold."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.dual_confidence_checker import (
+ DualConfidenceChecker,
+ )
+
+ mock_model = Mock()
+ checker = DualConfidenceChecker(mock_model, positive_threshold=0.5)
+
+ assert checker.positive_threshold == 0.5
+
+ def test_init_with_custom_uncertainty_penalty(self):
+ """Initialize with custom uncertainty penalty."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.dual_confidence_checker import (
+ DualConfidenceChecker,
+ )
+
+ mock_model = Mock()
+ checker = DualConfidenceChecker(mock_model, uncertainty_penalty=0.3)
+
+ assert checker.uncertainty_penalty == 0.3
+
+ def test_init_with_custom_max_reevaluations(self):
+ """Initialize with custom max reevaluations."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.dual_confidence_checker import (
+ DualConfidenceChecker,
+ )
+
+ mock_model = Mock()
+ checker = DualConfidenceChecker(mock_model, max_reevaluations=5)
+
+ assert checker.max_reevaluations == 5
+
+ def test_init_creates_evidence_analyzer(self):
+ """Initializes evidence analyzer."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.dual_confidence_checker import (
+ DualConfidenceChecker,
+ )
+
+ mock_model = Mock()
+ checker = DualConfidenceChecker(mock_model)
+
+ assert checker.evidence_analyzer is not None
+
+ def test_init_stores_model(self):
+ """Stores model reference."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.dual_confidence_checker import (
+ DualConfidenceChecker,
+ )
+
+ mock_model = Mock()
+ checker = DualConfidenceChecker(mock_model)
+
+ assert checker.model is mock_model
+
+
+class TestShouldEarlyReject:
+ """Tests for _should_early_reject method."""
+
+ def test_rejects_high_negative(self):
+ """Rejects when negative evidence exceeds threshold."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.dual_confidence_checker import (
+ DualConfidenceChecker,
+ )
+
+ mock_model = Mock()
+ checker = DualConfidenceChecker(mock_model, negative_threshold=0.25)
+
+ result = checker._should_early_reject(0.5, 0.3) # negative > 0.25
+
+ assert result is True
+
+ def test_rejects_low_positive(self):
+ """Rejects when positive evidence below threshold."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.dual_confidence_checker import (
+ DualConfidenceChecker,
+ )
+
+ mock_model = Mock()
+ checker = DualConfidenceChecker(mock_model, positive_threshold=0.4)
+
+ result = checker._should_early_reject(0.3, 0.1) # positive < 0.4
+
+ assert result is True
+
+ def test_accepts_good_scores(self):
+ """Accepts when scores meet thresholds."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.dual_confidence_checker import (
+ DualConfidenceChecker,
+ )
+
+ mock_model = Mock()
+ checker = DualConfidenceChecker(
+ mock_model, negative_threshold=0.25, positive_threshold=0.4
+ )
+
+ result = checker._should_early_reject(0.6, 0.1) # Good scores
+
+ assert result is False
+
+
+class TestShouldRejectCandidateFromAverages:
+ """Tests for should_reject_candidate_from_averages method."""
+
+ def test_rejects_high_negative_evidence(self):
+ """Rejects when average negative evidence high."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.dual_confidence_checker import (
+ DualConfidenceChecker,
+ )
+
+ mock_model = Mock()
+ checker = DualConfidenceChecker(mock_model, negative_threshold=0.25)
+
+ candidate = MockCandidate(name="Test")
+ constraint = MockConstraint(value="test constraint")
+
+ should_reject, reason = checker.should_reject_candidate_from_averages(
+ candidate,
+ constraint,
+ 0.5,
+ 0.3, # negative > 0.25
+ )
+
+ assert should_reject is True
+ assert "negative evidence" in reason.lower()
+
+ def test_rejects_low_positive_evidence(self):
+ """Rejects when average positive evidence low."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.dual_confidence_checker import (
+ DualConfidenceChecker,
+ )
+
+ mock_model = Mock()
+ checker = DualConfidenceChecker(mock_model, positive_threshold=0.4)
+
+ candidate = MockCandidate(name="Test")
+ constraint = MockConstraint(value="test constraint")
+
+ should_reject, reason = checker.should_reject_candidate_from_averages(
+ candidate,
+ constraint,
+ 0.2,
+ 0.1, # positive < 0.4
+ )
+
+ assert should_reject is True
+ assert "positive evidence" in reason.lower()
+
+ def test_accepts_good_averages(self):
+ """Accepts when averages meet thresholds."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.dual_confidence_checker import (
+ DualConfidenceChecker,
+ )
+
+ mock_model = Mock()
+ checker = DualConfidenceChecker(mock_model)
+
+ candidate = MockCandidate(name="Test")
+ constraint = MockConstraint(value="test constraint")
+
+ should_reject, reason = checker.should_reject_candidate_from_averages(
+ candidate,
+ constraint,
+ 0.7,
+ 0.1, # Good averages
+ )
+
+ assert should_reject is False
+ assert reason == ""
+
+
+class TestShouldRejectCandidate:
+ """Tests for should_reject_candidate method."""
+
+ def test_returns_false_for_empty_evidence(self):
+ """Returns false when no evidence provided."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.dual_confidence_checker import (
+ DualConfidenceChecker,
+ )
+
+ mock_model = Mock()
+ checker = DualConfidenceChecker(mock_model)
+
+ candidate = MockCandidate(name="Test")
+ constraint = MockConstraint(value="constraint")
+
+ should_reject, reason = checker.should_reject_candidate(
+ candidate, constraint, []
+ )
+
+ assert should_reject is False
+ assert reason == ""
+
+ def test_calculates_averages_from_evidence(self):
+ """Calculates averages from dual evidence."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.dual_confidence_checker import (
+ DualConfidenceChecker,
+ )
+
+ mock_model = Mock()
+ checker = DualConfidenceChecker(
+ mock_model, negative_threshold=0.25, positive_threshold=0.4
+ )
+
+ candidate = MockCandidate(name="Test")
+ constraint = MockConstraint(value="constraint")
+
+ evidence = [
+ MockConstraintEvidence(0.8, 0.1, 0.1),
+ MockConstraintEvidence(0.6, 0.2, 0.2),
+ ]
+
+ should_reject, _ = checker.should_reject_candidate(
+ candidate, constraint, evidence
+ )
+
+ # Avg positive = 0.7, avg negative = 0.15 - should pass
+ assert should_reject is False
+
+
+class TestLLMPrescreenCandidate:
+ """Tests for _llm_prescreen_candidate method."""
+
+ def test_returns_not_rejected_without_query(self):
+ """Returns not rejected when no original query."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.dual_confidence_checker import (
+ DualConfidenceChecker,
+ )
+
+ mock_model = Mock()
+ checker = DualConfidenceChecker(mock_model)
+
+ candidate = MockCandidate(name="Test")
+ constraints = [MockConstraint(value="c1")]
+
+ result = checker._llm_prescreen_candidate(candidate, constraints, None)
+
+ assert result["should_reject"] is False
+
+ def test_accepts_high_quality_answer(self):
+ """Accepts answer with high quality score."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.dual_confidence_checker import (
+ DualConfidenceChecker,
+ )
+
+ mock_model = Mock()
+ mock_model.generate.return_value = "85"
+ checker = DualConfidenceChecker(mock_model)
+
+ candidate = MockCandidate(name="Good Answer")
+ constraints = [MockConstraint(value="c1")]
+
+ result = checker._llm_prescreen_candidate(
+ candidate, constraints, "What is the answer?"
+ )
+
+ assert result["should_reject"] is False
+
+ def test_rejects_low_quality_answer(self):
+ """Rejects answer with low quality score."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.dual_confidence_checker import (
+ DualConfidenceChecker,
+ )
+
+ mock_model = Mock()
+ mock_model.generate.return_value = "25"
+ checker = DualConfidenceChecker(mock_model)
+
+ candidate = MockCandidate(name="Bad Answer")
+ constraints = [MockConstraint(value="c1")]
+
+ result = checker._llm_prescreen_candidate(
+ candidate, constraints, "What is the answer?"
+ )
+
+ assert result["should_reject"] is True
+ assert "Poor answer quality" in result["reason"]
+
+ def test_accepts_on_parse_failure(self):
+ """Accepts by default when score parsing fails."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.dual_confidence_checker import (
+ DualConfidenceChecker,
+ )
+
+ mock_model = Mock()
+ mock_model.generate.return_value = "no score here"
+ checker = DualConfidenceChecker(mock_model)
+
+ candidate = MockCandidate(name="Answer")
+ constraints = [MockConstraint(value="c1")]
+
+ result = checker._llm_prescreen_candidate(
+ candidate, constraints, "question"
+ )
+
+ assert result["should_reject"] is False
+
+ def test_accepts_on_exception(self):
+ """Accepts by default when exception occurs."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.dual_confidence_checker import (
+ DualConfidenceChecker,
+ )
+
+ mock_model = Mock()
+ mock_model.generate.side_effect = Exception("LLM error")
+ checker = DualConfidenceChecker(mock_model)
+
+ candidate = MockCandidate(name="Answer")
+ constraints = [MockConstraint(value="c1")]
+
+ result = checker._llm_prescreen_candidate(
+ candidate, constraints, "question"
+ )
+
+ assert result["should_reject"] is False
+
+
+class TestEvaluateConstraintWithReevaluation:
+ """Tests for _evaluate_constraint_with_reevaluation method."""
+
+ def test_returns_high_uncertainty_when_no_evidence(self):
+ """Returns high uncertainty when no evidence found."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.dual_confidence_checker import (
+ DualConfidenceChecker,
+ )
+
+ mock_model = Mock()
+ mock_gatherer = Mock(return_value=[]) # No evidence
+ checker = DualConfidenceChecker(
+ mock_model, evidence_gatherer=mock_gatherer
+ )
+
+ candidate = MockCandidate(name="Test")
+ constraint = MockConstraint(value="constraint")
+
+ result = checker._evaluate_constraint_with_reevaluation(
+ candidate, constraint
+ )
+
+ assert result["uncertainty"] == 1.0
+ assert result["positive"] == 0.0
+ assert result["negative"] == 0.0
+
+ def test_does_not_reevaluate_when_certain(self):
+ """Does not re-evaluate when uncertainty is low."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.dual_confidence_checker import (
+ DualConfidenceChecker,
+ )
+
+ mock_model = Mock()
+ mock_model.invoke.return_value.content = (
+ "POSITIVE: 0.8\nNEGATIVE: 0.1\nUNCERTAINTY: 0.1"
+ )
+ mock_gatherer = Mock(return_value=[{"text": "evidence"}])
+ checker = DualConfidenceChecker(
+ mock_model,
+ evidence_gatherer=mock_gatherer,
+ uncertainty_threshold=0.6,
+ )
+
+ candidate = MockCandidate(name="Test")
+ constraint = MockConstraint(value="constraint")
+
+ result = checker._evaluate_constraint_with_reevaluation(
+ candidate, constraint
+ )
+
+ assert result["reevaluation_count"] == 0
+
+ def test_tracks_reevaluation_count(self):
+ """Tracks number of re-evaluations."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.dual_confidence_checker import (
+ DualConfidenceChecker,
+ )
+
+ mock_model = Mock()
+ # First call: high uncertainty, second call: low uncertainty
+ mock_model.invoke.return_value.content = (
+ "POSITIVE: 0.7\nNEGATIVE: 0.1\nUNCERTAINTY: 0.2"
+ )
+ mock_gatherer = Mock(return_value=[{"text": "evidence"}])
+ checker = DualConfidenceChecker(
+ mock_model,
+ evidence_gatherer=mock_gatherer,
+ uncertainty_threshold=0.6,
+ max_reevaluations=2,
+ )
+
+ candidate = MockCandidate(name="Test")
+ constraint = MockConstraint(value="constraint")
+
+ result = checker._evaluate_constraint_with_reevaluation(
+ candidate, constraint
+ )
+
+ assert "reevaluation_count" in result
+
+
+class TestCheckCandidate:
+ """Tests for check_candidate method."""
+
+ def test_returns_constraint_check_result(self):
+ """Returns ConstraintCheckResult with all fields."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.dual_confidence_checker import (
+ DualConfidenceChecker,
+ )
+
+ mock_model = Mock()
+ mock_model.invoke.return_value.content = (
+ "POSITIVE: 0.8\nNEGATIVE: 0.1\nUNCERTAINTY: 0.1"
+ )
+ mock_model.generate.return_value = "75" # Pre-screen passes
+ mock_gatherer = Mock(return_value=[{"text": "evidence"}])
+ checker = DualConfidenceChecker(
+ mock_model, evidence_gatherer=mock_gatherer
+ )
+
+ candidate = MockCandidate(name="Test")
+ constraints = [MockConstraint(value="c1")]
+
+ result = checker.check_candidate(
+ candidate, constraints, original_query="test query"
+ )
+
+ assert hasattr(result, "total_score")
+ assert hasattr(result, "should_reject")
+ assert hasattr(result, "constraint_scores")
+ assert hasattr(result, "detailed_results")
+
+ def test_prescreen_rejects_low_quality_answer(self):
+ """Pre-screen rejects low quality answers via _llm_prescreen_candidate."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.dual_confidence_checker import (
+ DualConfidenceChecker,
+ )
+
+ mock_model = Mock()
+ mock_model.generate.return_value = "20" # Low quality score
+ checker = DualConfidenceChecker(mock_model)
+
+ candidate = MockCandidate(name="Bad Answer")
+ constraints = [MockConstraint(value="c1")]
+
+ # Test the pre-screen method directly
+ result = checker._llm_prescreen_candidate(
+ candidate, constraints, "test query"
+ )
+
+ assert result["should_reject"] is True
+ assert "Poor answer quality" in result["reason"]
+
+ def test_stores_positive_negative_uncertainty(self):
+ """Stores positive/negative/uncertainty in constraint scores."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.dual_confidence_checker import (
+ DualConfidenceChecker,
+ )
+
+ mock_model = Mock()
+ mock_model.invoke.return_value.content = (
+ "POSITIVE: 0.7\nNEGATIVE: 0.1\nUNCERTAINTY: 0.2"
+ )
+ mock_model.generate.return_value = "80"
+ mock_gatherer = Mock(return_value=[{"text": "evidence"}])
+ checker = DualConfidenceChecker(
+ mock_model, evidence_gatherer=mock_gatherer
+ )
+
+ candidate = MockCandidate(name="Test")
+ constraints = [MockConstraint(value="c1")]
+
+ result = checker.check_candidate(
+ candidate, constraints, original_query="test"
+ )
+
+ scores = result.constraint_scores["c1"]
+ assert "positive" in scores
+ assert "negative" in scores
+ assert "uncertainty" in scores
+
+ def test_calculates_weighted_total_score(self):
+ """Calculates weighted total score from constraints."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.dual_confidence_checker import (
+ DualConfidenceChecker,
+ )
+
+ mock_model = Mock()
+ mock_model.invoke.return_value.content = (
+ "POSITIVE: 0.8\nNEGATIVE: 0.1\nUNCERTAINTY: 0.1"
+ )
+ mock_model.generate.return_value = "80"
+ mock_gatherer = Mock(return_value=[{"text": "evidence"}])
+ checker = DualConfidenceChecker(
+ mock_model, evidence_gatherer=mock_gatherer
+ )
+
+ candidate = MockCandidate(name="Test")
+ constraints = [
+ MockConstraint(value="c1", weight=2.0),
+ MockConstraint(value="c2", weight=1.0),
+ ]
+
+ result = checker.check_candidate(
+ candidate, constraints, original_query="test"
+ )
+
+ # Should have a weighted score
+ assert result.total_score >= 0.0
+ assert result.total_score <= 1.0
+
+ def test_sets_score_zero_when_rejected(self):
+ """Sets total score to 0 when candidate rejected."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.dual_confidence_checker import (
+ DualConfidenceChecker,
+ )
+
+ mock_model = Mock()
+ # High negative evidence
+ mock_model.invoke.return_value.content = (
+ "POSITIVE: 0.1\nNEGATIVE: 0.8\nUNCERTAINTY: 0.1"
+ )
+ mock_model.generate.return_value = "80"
+ mock_gatherer = Mock(return_value=[{"text": "evidence"}])
+ checker = DualConfidenceChecker(
+ mock_model, evidence_gatherer=mock_gatherer
+ )
+
+ candidate = MockCandidate(name="Test")
+ constraints = [MockConstraint(value="c1")]
+
+ result = checker.check_candidate(
+ candidate, constraints, original_query="test"
+ )
+
+ assert result.should_reject is True
+ assert result.total_score == 0.0
+
+ def test_handles_empty_constraints(self):
+ """Handles empty constraints list."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.dual_confidence_checker import (
+ DualConfidenceChecker,
+ )
+
+ mock_model = Mock()
+ mock_model.generate.return_value = "80"
+ checker = DualConfidenceChecker(mock_model)
+
+ candidate = MockCandidate(name="Test")
+ constraints = []
+
+ result = checker.check_candidate(
+ candidate, constraints, original_query="test"
+ )
+
+ assert result.total_score == 0.0
+ assert result.detailed_results == []
+
+ def test_records_reevaluation_count_in_results(self):
+ """Records reevaluation count in detailed results."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.dual_confidence_checker import (
+ DualConfidenceChecker,
+ )
+
+ mock_model = Mock()
+ mock_model.invoke.return_value.content = (
+ "POSITIVE: 0.7\nNEGATIVE: 0.1\nUNCERTAINTY: 0.2"
+ )
+ mock_model.generate.return_value = "80"
+ mock_gatherer = Mock(return_value=[{"text": "evidence"}])
+ checker = DualConfidenceChecker(
+ mock_model, evidence_gatherer=mock_gatherer
+ )
+
+ candidate = MockCandidate(name="Test")
+ constraints = [MockConstraint(value="c1")]
+
+ result = checker.check_candidate(
+ candidate, constraints, original_query="test"
+ )
+
+ assert "reevaluation_count" in result.detailed_results[0]
+ assert "reevaluation_count" in result.constraint_scores["c1"]
+
+
+class TestLogConstraintResultDetailed:
+ """Tests for _log_constraint_result_detailed method."""
+
+ def test_logs_high_score_with_checkmark(self):
+ """Logs high scores with checkmark symbol."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.dual_confidence_checker import (
+ DualConfidenceChecker,
+ )
+
+ mock_model = Mock()
+ checker = DualConfidenceChecker(mock_model)
+
+ candidate = MockCandidate(name="Test")
+ constraint = MockConstraint(value="constraint")
+
+ # Should not raise
+ checker._log_constraint_result_detailed(
+ candidate, constraint, 0.9, 0.8, 0.1, 0.1, 0
+ )
+
+ def test_logs_medium_score_with_circle(self):
+ """Logs medium scores with circle symbol."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.dual_confidence_checker import (
+ DualConfidenceChecker,
+ )
+
+ mock_model = Mock()
+ checker = DualConfidenceChecker(mock_model)
+
+ candidate = MockCandidate(name="Test")
+ constraint = MockConstraint(value="constraint")
+
+ # Should not raise
+ checker._log_constraint_result_detailed(
+ candidate, constraint, 0.6, 0.5, 0.2, 0.3, 1
+ )
+
+ def test_logs_low_score_with_x(self):
+ """Logs low scores with X symbol."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.dual_confidence_checker import (
+ DualConfidenceChecker,
+ )
+
+ mock_model = Mock()
+ checker = DualConfidenceChecker(mock_model)
+
+ candidate = MockCandidate(name="Test")
+ constraint = MockConstraint(value="constraint")
+
+ # Should not raise
+ checker._log_constraint_result_detailed(
+ candidate, constraint, 0.3, 0.2, 0.5, 0.3, 2
+ )
+
+
+class TestCalculateWeightedScore:
+ """Tests for _calculate_weighted_score method."""
+
+ def test_calculates_weighted_average(self):
+ """Calculates weighted average correctly."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.dual_confidence_checker import (
+ DualConfidenceChecker,
+ )
+
+ mock_model = Mock()
+ checker = DualConfidenceChecker(mock_model)
+
+ scores = [0.8, 0.4]
+ weights = [2.0, 1.0]
+
+ result = checker._calculate_weighted_score(scores, weights)
+
+ # (0.8 * 2.0 + 0.4 * 1.0) / 3.0 = 2.0 / 3.0 = 0.667
+ assert abs(result - 0.667) < 0.01
+
+ def test_handles_empty_scores(self):
+ """Handles empty score list."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.dual_confidence_checker import (
+ DualConfidenceChecker,
+ )
+
+ mock_model = Mock()
+ checker = DualConfidenceChecker(mock_model)
+
+ result = checker._calculate_weighted_score([], [])
+
+ assert result == 0.0
+
+ def test_handles_equal_weights(self):
+ """Calculates simple average for equal weights."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.dual_confidence_checker import (
+ DualConfidenceChecker,
+ )
+
+ mock_model = Mock()
+ checker = DualConfidenceChecker(mock_model)
+
+ scores = [0.9, 0.5, 0.1]
+ weights = [1.0, 1.0, 1.0]
+
+ result = checker._calculate_weighted_score(scores, weights)
+
+ # Simple average: 0.5
+ assert abs(result - 0.5) < 0.01
diff --git a/tests/advanced_search_system/constraint_checking/test_strict_checker.py b/tests/advanced_search_system/constraint_checking/test_strict_checker.py
new file mode 100644
index 0000000000..3b1f80571d
--- /dev/null
+++ b/tests/advanced_search_system/constraint_checking/test_strict_checker.py
@@ -0,0 +1,649 @@
+"""
+Tests for the StrictChecker class.
+
+Tests cover:
+- Initialization with strict thresholds
+- NAME_PATTERN constraint handling
+- Body part name pattern checking
+- Strict evaluation criteria
+- LLM prompt generation
+- Rejection decisions
+"""
+
+from dataclasses import dataclass
+from enum import Enum
+from unittest.mock import Mock
+
+
+class MockConstraintType(Enum):
+ """Mock constraint type for testing."""
+
+ PROPERTY = "property"
+ NAME_PATTERN = "name_pattern"
+ EVENT = "event"
+
+
+@dataclass
+class MockCandidate:
+ """Mock candidate for testing."""
+
+ name: str
+ value: str = ""
+
+
+@dataclass
+class MockConstraint:
+ """Mock constraint for testing."""
+
+ value: str
+ weight: float = 1.0
+ type: MockConstraintType = MockConstraintType.PROPERTY
+
+
+class TestStrictCheckerInit:
+ """Tests for StrictChecker initialization."""
+
+ def test_init_with_defaults(self):
+ """Initialize with default strict thresholds."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.strict_checker import (
+ StrictChecker,
+ )
+
+ mock_model = Mock()
+ checker = StrictChecker(mock_model)
+
+ assert checker.strict_threshold == 0.9
+ assert checker.name_pattern_required is True
+
+ def test_init_with_custom_strict_threshold(self):
+ """Initialize with custom strict threshold."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.strict_checker import (
+ StrictChecker,
+ )
+
+ mock_model = Mock()
+ checker = StrictChecker(mock_model, strict_threshold=0.95)
+
+ assert checker.strict_threshold == 0.95
+
+ def test_init_with_name_pattern_not_required(self):
+ """Initialize with name_pattern_required False."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.strict_checker import (
+ StrictChecker,
+ )
+
+ mock_model = Mock()
+ checker = StrictChecker(mock_model, name_pattern_required=False)
+
+ assert checker.name_pattern_required is False
+
+ def test_init_stores_model(self):
+ """Initialization stores model reference."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.strict_checker import (
+ StrictChecker,
+ )
+
+ mock_model = Mock()
+ checker = StrictChecker(mock_model)
+
+ assert checker.model is mock_model
+
+ def test_init_stores_evidence_gatherer(self):
+ """Initialization stores evidence gatherer."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.strict_checker import (
+ StrictChecker,
+ )
+
+ mock_model = Mock()
+ mock_gatherer = Mock()
+ checker = StrictChecker(mock_model, evidence_gatherer=mock_gatherer)
+
+ assert checker.evidence_gatherer is mock_gatherer
+
+
+class TestCheckNamePatternStrictly:
+ """Tests for _check_name_pattern_strictly method."""
+
+ def test_finds_body_part_arm(self):
+ """Finds 'arm' body part in name."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.strict_checker import (
+ StrictChecker,
+ )
+
+ mock_model = Mock()
+ checker = StrictChecker(mock_model)
+
+ score = checker._check_name_pattern_strictly(
+ "Strong Arm Mountain", "contains body part"
+ )
+
+ assert score == 1.0
+
+ def test_finds_body_part_foot(self):
+ """Finds 'foot' body part in name."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.strict_checker import (
+ StrictChecker,
+ )
+
+ mock_model = Mock()
+ checker = StrictChecker(mock_model)
+
+ score = checker._check_name_pattern_strictly(
+ "Bigfoot Trail", "body part in name"
+ )
+
+ assert score == 1.0
+
+ def test_finds_body_part_heart(self):
+ """Finds 'heart' body part in name."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.strict_checker import (
+ StrictChecker,
+ )
+
+ mock_model = Mock()
+ checker = StrictChecker(mock_model)
+
+ score = checker._check_name_pattern_strictly(
+ "Heart Lake", "must contain body part"
+ )
+
+ assert score == 1.0
+
+ def test_finds_body_part_knee(self):
+ """Finds 'knee' body part in name."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.strict_checker import (
+ StrictChecker,
+ )
+
+ mock_model = Mock()
+ checker = StrictChecker(mock_model)
+
+ score = checker._check_name_pattern_strictly(
+ "Wounded Knee Creek", "body part"
+ )
+
+ assert score == 1.0
+
+ def test_no_body_part_returns_zero(self):
+ """Returns 0.0 when no body part found."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.strict_checker import (
+ StrictChecker,
+ )
+
+ mock_model = Mock()
+ checker = StrictChecker(mock_model)
+
+ score = checker._check_name_pattern_strictly(
+ "Pine Mountain Trail", "contains body part"
+ )
+
+ assert score == 0.0
+
+ def test_body_part_case_insensitive(self):
+ """Body part check is case insensitive."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.strict_checker import (
+ StrictChecker,
+ )
+
+ mock_model = Mock()
+ checker = StrictChecker(mock_model)
+
+ score = checker._check_name_pattern_strictly(
+ "HAND CREEK TRAIL", "body part"
+ )
+
+ assert score == 1.0
+
+ def test_uses_llm_for_non_body_part_patterns(self):
+ """Uses LLM for non-body-part patterns."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.strict_checker import (
+ StrictChecker,
+ )
+
+ mock_model = Mock()
+ mock_model.invoke.return_value.content = "Score: 0.95"
+ checker = StrictChecker(mock_model)
+
+ score = checker._check_name_pattern_strictly(
+ "Crystal Lake", "name must start with C"
+ )
+
+ assert score == 0.95
+ mock_model.invoke.assert_called_once()
+
+ def test_llm_pattern_returns_zero_on_exception(self):
+ """Returns 0.0 when LLM fails for pattern check."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.strict_checker import (
+ StrictChecker,
+ )
+
+ mock_model = Mock()
+ mock_model.invoke.side_effect = Exception("LLM error")
+ checker = StrictChecker(mock_model)
+
+ score = checker._check_name_pattern_strictly(
+ "Test Name", "starts with T"
+ )
+
+ assert score == 0.0
+
+
+class TestEvaluateConstraintStrictly:
+ """Tests for _evaluate_constraint_strictly method."""
+
+ def test_returns_zero_for_empty_evidence(self):
+ """Returns 0.0 when no evidence provided."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.strict_checker import (
+ StrictChecker,
+ )
+
+ mock_model = Mock()
+ checker = StrictChecker(mock_model)
+
+ candidate = MockCandidate(name="Test")
+ constraint = MockConstraint(value="must be valid")
+
+ score = checker._evaluate_constraint_strictly(candidate, constraint, [])
+
+ assert score == 0.0
+
+ def test_uses_name_pattern_check_for_name_pattern_type(self):
+ """Uses name pattern check for NAME_PATTERN constraints."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.strict_checker import (
+ StrictChecker,
+ )
+ from src.local_deep_research.advanced_search_system.constraints.base_constraint import (
+ ConstraintType,
+ Constraint,
+ )
+
+ mock_model = Mock()
+ checker = StrictChecker(mock_model)
+
+ candidate = MockCandidate(name="Heart Mountain")
+ constraint = Constraint(
+ id="c1",
+ type=ConstraintType.NAME_PATTERN,
+ description="Contains body part",
+ value="body part in name",
+ )
+ evidence = [{"text": "some evidence"}]
+
+ score = checker._evaluate_constraint_strictly(
+ candidate, constraint, evidence
+ )
+
+ assert score == 1.0 # Heart is a body part
+
+ def test_uses_llm_for_property_constraints(self):
+ """Uses LLM evaluation for PROPERTY constraints."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.strict_checker import (
+ StrictChecker,
+ )
+ from src.local_deep_research.advanced_search_system.constraints.base_constraint import (
+ ConstraintType,
+ Constraint,
+ )
+
+ mock_model = Mock()
+ mock_model.invoke.return_value.content = "0.92"
+ checker = StrictChecker(mock_model)
+
+ candidate = MockCandidate(name="Test Candidate")
+ constraint = Constraint(
+ id="c1",
+ type=ConstraintType.PROPERTY,
+ description="Must be old",
+ value="formed during ice age",
+ )
+ evidence = [{"text": "Formed during the ice age"}]
+
+ score = checker._evaluate_constraint_strictly(
+ candidate, constraint, evidence
+ )
+
+ assert score == 0.92
+
+ def test_strict_prompt_mentions_strict(self):
+ """LLM prompt emphasizes strict evaluation."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.strict_checker import (
+ StrictChecker,
+ )
+ from src.local_deep_research.advanced_search_system.constraints.base_constraint import (
+ ConstraintType,
+ Constraint,
+ )
+
+ mock_model = Mock()
+ mock_model.invoke.return_value.content = "0.8"
+ checker = StrictChecker(mock_model)
+
+ candidate = MockCandidate(name="Test")
+ constraint = Constraint(
+ id="c1",
+ type=ConstraintType.PROPERTY,
+ description="test",
+ value="test",
+ )
+ evidence = [{"text": "evidence"}]
+
+ checker._evaluate_constraint_strictly(candidate, constraint, evidence)
+
+ call_args = mock_model.invoke.call_args[0][0]
+ assert "STRICT" in call_args or "strict" in call_args
+
+ def test_truncates_evidence_text(self):
+ """Truncates long evidence text in prompt."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.strict_checker import (
+ StrictChecker,
+ )
+ from src.local_deep_research.advanced_search_system.constraints.base_constraint import (
+ ConstraintType,
+ Constraint,
+ )
+
+ mock_model = Mock()
+ mock_model.invoke.return_value.content = "0.9"
+ checker = StrictChecker(mock_model)
+
+ candidate = MockCandidate(name="Test")
+ constraint = Constraint(
+ id="c1",
+ type=ConstraintType.PROPERTY,
+ description="test",
+ value="test",
+ )
+ evidence = [{"text": "A" * 1000}] # Very long text
+
+ checker._evaluate_constraint_strictly(candidate, constraint, evidence)
+
+ # Verify evidence is truncated (uses first 300 chars per evidence, 2 evidences max)
+ call_args = mock_model.invoke.call_args[0][0]
+ # The code truncates to 300 chars, but may include up to 2 evidence items
+ assert call_args.count("A") <= 600 # Max 2 evidence * 300 chars each
+
+
+class TestShouldRejectCandidate:
+ """Tests for should_reject_candidate method."""
+
+ def test_rejects_when_no_evidence(self):
+ """Rejects candidate when no evidence available."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.strict_checker import (
+ StrictChecker,
+ )
+
+ mock_model = Mock()
+ checker = StrictChecker(mock_model)
+
+ candidate = MockCandidate(name="Test")
+ constraint = MockConstraint(value="constraint")
+
+ should_reject, reason = checker.should_reject_candidate(
+ candidate, constraint, []
+ )
+
+ assert should_reject is True
+ assert "No evidence" in reason
+
+ def test_rejects_name_pattern_below_095(self):
+ """Rejects NAME_PATTERN constraints below 0.95."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.strict_checker import (
+ StrictChecker,
+ )
+ from src.local_deep_research.advanced_search_system.constraints.base_constraint import (
+ ConstraintType,
+ Constraint,
+ )
+
+ mock_model = Mock()
+ mock_model.invoke.return_value.content = "0.9"
+ checker = StrictChecker(mock_model)
+
+ candidate = MockCandidate(name="Pine Trail")
+ constraint = Constraint(
+ id="c1",
+ type=ConstraintType.NAME_PATTERN,
+ description="body part",
+ value="contains body part",
+ )
+ evidence = [{"text": "evidence"}]
+
+ should_reject, reason = checker.should_reject_candidate(
+ candidate, constraint, evidence
+ )
+
+ assert should_reject is True
+ assert "NAME_PATTERN" in reason
+
+ def test_accepts_name_pattern_at_095_or_above(self):
+ """Accepts NAME_PATTERN constraints at 0.95 or above."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.strict_checker import (
+ StrictChecker,
+ )
+ from src.local_deep_research.advanced_search_system.constraints.base_constraint import (
+ ConstraintType,
+ Constraint,
+ )
+
+ mock_model = Mock()
+ checker = StrictChecker(mock_model)
+
+ candidate = MockCandidate(name="Heart Mountain")
+ constraint = Constraint(
+ id="c1",
+ type=ConstraintType.NAME_PATTERN,
+ description="body part",
+ value="body part",
+ )
+ evidence = [{"text": "evidence"}]
+
+ should_reject, _ = checker.should_reject_candidate(
+ candidate, constraint, evidence
+ )
+
+ assert should_reject is False
+
+ def test_rejects_below_strict_threshold(self):
+ """Rejects when score below strict threshold."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.strict_checker import (
+ StrictChecker,
+ )
+ from src.local_deep_research.advanced_search_system.constraints.base_constraint import (
+ ConstraintType,
+ Constraint,
+ )
+
+ mock_model = Mock()
+ mock_model.invoke.return_value.content = "0.85" # Below 0.9
+ checker = StrictChecker(mock_model)
+
+ candidate = MockCandidate(name="Test")
+ constraint = Constraint(
+ id="c1",
+ type=ConstraintType.PROPERTY,
+ description="test",
+ value="test",
+ )
+ evidence = [{"text": "evidence"}]
+
+ should_reject, reason = checker.should_reject_candidate(
+ candidate, constraint, evidence
+ )
+
+ assert should_reject is True
+ assert "strict threshold" in reason.lower()
+
+ def test_name_pattern_not_required_uses_standard_threshold(self):
+ """When name_pattern_required=False, uses standard 0.9 threshold instead of 0.95."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.strict_checker import (
+ StrictChecker,
+ )
+ from src.local_deep_research.advanced_search_system.constraints.base_constraint import (
+ ConstraintType,
+ Constraint,
+ )
+
+ mock_model = Mock()
+ # For NAME_PATTERN with body part, it uses _check_name_pattern_strictly
+ # which returns 1.0 for "Heart Trail" (has body part)
+ checker = StrictChecker(mock_model, name_pattern_required=False)
+
+ # Use a name that has a body part so the pattern check passes
+ candidate = MockCandidate(name="Heart Trail")
+ constraint = Constraint(
+ id="c1",
+ type=ConstraintType.NAME_PATTERN,
+ description="body part",
+ value="body part",
+ )
+ evidence = [{"text": "evidence"}]
+
+ should_reject, _ = checker.should_reject_candidate(
+ candidate, constraint, evidence
+ )
+
+ # Should pass - body part "heart" found, returns 1.0 which is >= 0.9
+ assert should_reject is False
+
+
+class TestCheckCandidate:
+ """Tests for check_candidate method."""
+
+ def test_returns_constraint_check_result(self):
+ """Returns ConstraintCheckResult with all fields."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.strict_checker import (
+ StrictChecker,
+ )
+
+ mock_model = Mock()
+ mock_model.invoke.return_value.content = "0.95"
+ mock_gatherer = Mock(return_value=[{"text": "evidence"}])
+ checker = StrictChecker(mock_model, evidence_gatherer=mock_gatherer)
+
+ candidate = MockCandidate(name="Test")
+ constraints = [MockConstraint(value="c1")]
+
+ result = checker.check_candidate(candidate, constraints)
+
+ assert hasattr(result, "total_score")
+ assert hasattr(result, "should_reject")
+ assert hasattr(result, "constraint_scores")
+
+ def test_total_score_1_when_all_pass_strict(self):
+ """Total score is 1.0 when all constraints pass strict threshold."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.strict_checker import (
+ StrictChecker,
+ )
+
+ mock_model = Mock()
+ mock_model.invoke.return_value.content = "0.95"
+ mock_gatherer = Mock(return_value=[{"text": "evidence"}])
+ checker = StrictChecker(mock_model, evidence_gatherer=mock_gatherer)
+
+ candidate = MockCandidate(name="Test")
+ constraints = [MockConstraint(value="c1"), MockConstraint(value="c2")]
+
+ result = checker.check_candidate(candidate, constraints)
+
+ assert result.should_reject is False
+ assert result.total_score == 1.0
+
+ def test_total_score_0_when_any_fail_strict(self):
+ """Total score is 0.0 when any constraint fails strict threshold."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.strict_checker import (
+ StrictChecker,
+ )
+
+ mock_model = Mock()
+ mock_model.invoke.return_value.content = "0.85" # Below 0.9
+ mock_gatherer = Mock(return_value=[{"text": "evidence"}])
+ checker = StrictChecker(mock_model, evidence_gatherer=mock_gatherer)
+
+ candidate = MockCandidate(name="Test")
+ constraints = [MockConstraint(value="c1")]
+
+ result = checker.check_candidate(candidate, constraints)
+
+ assert result.should_reject is True
+ assert result.total_score == 0.0
+
+ def test_stores_strict_pass_in_constraint_scores(self):
+ """Stores strict_pass boolean in constraint scores."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.strict_checker import (
+ StrictChecker,
+ )
+
+ mock_model = Mock()
+ mock_model.invoke.return_value.content = "0.92"
+ mock_gatherer = Mock(return_value=[{"text": "evidence"}])
+ checker = StrictChecker(mock_model, evidence_gatherer=mock_gatherer)
+
+ candidate = MockCandidate(name="Test")
+ constraints = [MockConstraint(value="c1")]
+
+ result = checker.check_candidate(candidate, constraints)
+
+ assert "strict_pass" in result.constraint_scores["c1"]
+ assert (
+ result.constraint_scores["c1"]["strict_pass"] is True
+ ) # 0.92 >= 0.9
+
+ def test_detailed_results_contain_strict_pass(self):
+ """Detailed results contain strict_pass field."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.strict_checker import (
+ StrictChecker,
+ )
+
+ mock_model = Mock()
+ mock_model.invoke.return_value.content = "0.88"
+ mock_gatherer = Mock(return_value=[{"text": "evidence"}])
+ checker = StrictChecker(mock_model, evidence_gatherer=mock_gatherer)
+
+ candidate = MockCandidate(name="Test")
+ constraints = [MockConstraint(value="c1")]
+
+ result = checker.check_candidate(candidate, constraints)
+
+ assert result.detailed_results[0]["strict_pass"] is False # 0.88 < 0.9
+
+ def test_records_first_rejection_reason(self):
+ """Records first rejection reason when multiple constraints fail."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.strict_checker import (
+ StrictChecker,
+ )
+
+ mock_model = Mock()
+ mock_model.invoke.return_value.content = "0.5" # Below threshold
+ mock_gatherer = Mock(return_value=[{"text": "evidence"}])
+ checker = StrictChecker(mock_model, evidence_gatherer=mock_gatherer)
+
+ candidate = MockCandidate(name="Test")
+ constraints = [MockConstraint(value="c1"), MockConstraint(value="c2")]
+
+ result = checker.check_candidate(candidate, constraints)
+
+ assert result.should_reject is True
+ assert result.rejection_reason is not None
+ assert "c1" in result.rejection_reason # First constraint
+
+ def test_uses_custom_strict_threshold(self):
+ """Uses custom strict threshold for evaluation."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.strict_checker import (
+ StrictChecker,
+ )
+
+ mock_model = Mock()
+ mock_model.invoke.return_value.content = "0.8"
+ mock_gatherer = Mock(return_value=[{"text": "evidence"}])
+ checker = StrictChecker(
+ mock_model, evidence_gatherer=mock_gatherer, strict_threshold=0.75
+ )
+
+ candidate = MockCandidate(name="Test")
+ constraints = [MockConstraint(value="c1")]
+
+ result = checker.check_candidate(candidate, constraints)
+
+ # 0.8 >= 0.75, so should pass
+ assert result.should_reject is False
+ assert result.constraint_scores["c1"]["strict_pass"] is True
diff --git a/tests/advanced_search_system/constraint_checking/test_threshold_checker.py b/tests/advanced_search_system/constraint_checking/test_threshold_checker.py
new file mode 100644
index 0000000000..f3cb969283
--- /dev/null
+++ b/tests/advanced_search_system/constraint_checking/test_threshold_checker.py
@@ -0,0 +1,600 @@
+"""
+Tests for the ThresholdChecker class.
+
+Tests cover:
+- Initialization with custom thresholds
+- Constraint satisfaction checking
+- Candidate rejection decisions
+- Evidence handling
+- Score calculation
+- LLM response parsing
+"""
+
+from dataclasses import dataclass
+from enum import Enum
+from unittest.mock import Mock
+
+
+class MockConstraintType(Enum):
+ """Mock constraint type for testing."""
+
+ PROPERTY = "property"
+ NAME_PATTERN = "name_pattern"
+
+
+@dataclass
+class MockCandidate:
+ """Mock candidate for testing."""
+
+ name: str
+ value: str = ""
+
+
+@dataclass
+class MockConstraint:
+ """Mock constraint for testing."""
+
+ value: str
+ weight: float = 1.0
+ type: MockConstraintType = MockConstraintType.PROPERTY
+
+
+class TestThresholdCheckerInit:
+ """Tests for ThresholdChecker initialization."""
+
+ def test_init_with_defaults(self):
+ """Initialize with default thresholds."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.threshold_checker import (
+ ThresholdChecker,
+ )
+
+ mock_model = Mock()
+ checker = ThresholdChecker(mock_model)
+
+ assert checker.satisfaction_threshold == 0.7
+ assert checker.required_satisfaction_rate == 0.8
+
+ def test_init_with_custom_satisfaction_threshold(self):
+ """Initialize with custom satisfaction threshold."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.threshold_checker import (
+ ThresholdChecker,
+ )
+
+ mock_model = Mock()
+ checker = ThresholdChecker(mock_model, satisfaction_threshold=0.5)
+
+ assert checker.satisfaction_threshold == 0.5
+
+ def test_init_with_custom_required_satisfaction_rate(self):
+ """Initialize with custom required satisfaction rate."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.threshold_checker import (
+ ThresholdChecker,
+ )
+
+ mock_model = Mock()
+ checker = ThresholdChecker(mock_model, required_satisfaction_rate=0.6)
+
+ assert checker.required_satisfaction_rate == 0.6
+
+ def test_init_stores_model(self):
+ """Initialization stores model reference."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.threshold_checker import (
+ ThresholdChecker,
+ )
+
+ mock_model = Mock()
+ checker = ThresholdChecker(mock_model)
+
+ assert checker.model is mock_model
+
+ def test_init_stores_evidence_gatherer(self):
+ """Initialization stores evidence gatherer."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.threshold_checker import (
+ ThresholdChecker,
+ )
+
+ mock_model = Mock()
+ mock_gatherer = Mock()
+ checker = ThresholdChecker(mock_model, evidence_gatherer=mock_gatherer)
+
+ assert checker.evidence_gatherer is mock_gatherer
+
+
+class TestCheckConstraintSatisfaction:
+ """Tests for _check_constraint_satisfaction method."""
+
+ def test_extracts_score_from_llm_response(self):
+ """Extracts score from LLM response."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.threshold_checker import (
+ ThresholdChecker,
+ )
+
+ mock_model = Mock()
+ mock_model.invoke.return_value.content = "Score: 0.85"
+ checker = ThresholdChecker(mock_model)
+
+ candidate = MockCandidate(name="Test Candidate")
+ constraint = MockConstraint(value="must be valid")
+ evidence = [{"text": "Evidence text"}]
+
+ score = checker._check_constraint_satisfaction(
+ candidate, constraint, evidence
+ )
+
+ assert score == 0.85
+
+ def test_extracts_integer_score(self):
+ """Extracts integer score from LLM response."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.threshold_checker import (
+ ThresholdChecker,
+ )
+
+ mock_model = Mock()
+ mock_model.invoke.return_value.content = "1"
+ checker = ThresholdChecker(mock_model)
+
+ candidate = MockCandidate(name="Test")
+ constraint = MockConstraint(value="constraint")
+ evidence = [{"text": "text"}]
+
+ score = checker._check_constraint_satisfaction(
+ candidate, constraint, evidence
+ )
+
+ assert score == 1.0
+
+ def test_clamps_score_to_max_1(self):
+ """Clamps score to maximum 1.0."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.threshold_checker import (
+ ThresholdChecker,
+ )
+
+ mock_model = Mock()
+ mock_model.invoke.return_value.content = "Score: 1.5"
+ checker = ThresholdChecker(mock_model)
+
+ candidate = MockCandidate(name="Test")
+ constraint = MockConstraint(value="constraint")
+ evidence = [{"text": "text"}]
+
+ score = checker._check_constraint_satisfaction(
+ candidate, constraint, evidence
+ )
+
+ assert score == 1.0
+
+ def test_negative_score_returns_default(self):
+ """Negative scores in LLM response are not matched, returns default 0.5."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.threshold_checker import (
+ ThresholdChecker,
+ )
+
+ mock_model = Mock()
+ # Regex only matches positive numbers, so "-0.5" doesn't match
+ mock_model.invoke.return_value.content = "Score: -0.5"
+ checker = ThresholdChecker(mock_model)
+
+ candidate = MockCandidate(name="Test")
+ constraint = MockConstraint(value="constraint")
+ evidence = [{"text": "text"}]
+
+ score = checker._check_constraint_satisfaction(
+ candidate, constraint, evidence
+ )
+
+ # Returns default 0.5 since regex doesn't match negative numbers
+ assert score == 0.5
+
+ def test_returns_default_on_parse_failure(self):
+ """Returns 0.5 default when parsing fails."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.threshold_checker import (
+ ThresholdChecker,
+ )
+
+ mock_model = Mock()
+ mock_model.invoke.return_value.content = "no score here"
+ checker = ThresholdChecker(mock_model)
+
+ candidate = MockCandidate(name="Test")
+ constraint = MockConstraint(value="constraint")
+ evidence = [{"text": "text"}]
+
+ score = checker._check_constraint_satisfaction(
+ candidate, constraint, evidence
+ )
+
+ assert score == 0.5
+
+ def test_returns_default_on_exception(self):
+ """Returns 0.5 default on exception."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.threshold_checker import (
+ ThresholdChecker,
+ )
+
+ mock_model = Mock()
+ mock_model.invoke.side_effect = Exception("LLM error")
+ checker = ThresholdChecker(mock_model)
+
+ candidate = MockCandidate(name="Test")
+ constraint = MockConstraint(value="constraint")
+ evidence = [{"text": "text"}]
+
+ score = checker._check_constraint_satisfaction(
+ candidate, constraint, evidence
+ )
+
+ assert score == 0.5
+
+ def test_combines_evidence_texts(self):
+ """Combines multiple evidence texts in prompt."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.threshold_checker import (
+ ThresholdChecker,
+ )
+
+ mock_model = Mock()
+ mock_model.invoke.return_value.content = "0.9"
+ checker = ThresholdChecker(mock_model)
+
+ candidate = MockCandidate(name="Test")
+ constraint = MockConstraint(value="constraint")
+ evidence = [
+ {"text": "Evidence 1"},
+ {"text": "Evidence 2"},
+ {"text": "Evidence 3"},
+ ]
+
+ checker._check_constraint_satisfaction(candidate, constraint, evidence)
+
+ # Verify prompt contains evidence
+ call_args = mock_model.invoke.call_args[0][0]
+ assert "Evidence 1" in call_args
+ assert "Evidence 2" in call_args
+ assert "Evidence 3" in call_args
+
+ def test_truncates_evidence_text(self):
+ """Truncates long evidence texts."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.threshold_checker import (
+ ThresholdChecker,
+ )
+
+ mock_model = Mock()
+ mock_model.invoke.return_value.content = "0.7"
+ checker = ThresholdChecker(mock_model)
+
+ candidate = MockCandidate(name="Test")
+ constraint = MockConstraint(value="constraint")
+ evidence = [{"text": "A" * 500}] # Long text
+
+ checker._check_constraint_satisfaction(candidate, constraint, evidence)
+
+ call_args = mock_model.invoke.call_args[0][0]
+ # Evidence should be truncated to 200 chars
+ assert len(call_args) < 500 + 200 # Some buffer for prompt
+
+
+class TestShouldRejectCandidate:
+ """Tests for should_reject_candidate method."""
+
+ def test_rejects_when_no_evidence(self):
+ """Rejects candidate when no evidence available."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.threshold_checker import (
+ ThresholdChecker,
+ )
+
+ mock_model = Mock()
+ checker = ThresholdChecker(mock_model)
+
+ candidate = MockCandidate(name="Test")
+ constraint = MockConstraint(value="constraint")
+
+ should_reject, reason = checker.should_reject_candidate(
+ candidate, constraint, []
+ )
+
+ assert should_reject is True
+ assert "No evidence" in reason
+
+ def test_rejects_when_score_below_threshold(self):
+ """Rejects when satisfaction score below threshold."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.threshold_checker import (
+ ThresholdChecker,
+ )
+
+ mock_model = Mock()
+ mock_model.invoke.return_value.content = "0.3" # Below 0.7 default
+ checker = ThresholdChecker(mock_model)
+
+ candidate = MockCandidate(name="Test")
+ constraint = MockConstraint(value="constraint")
+ evidence = [{"text": "some evidence"}]
+
+ should_reject, reason = checker.should_reject_candidate(
+ candidate, constraint, evidence
+ )
+
+ assert should_reject is True
+ assert "not satisfied" in reason
+
+ def test_accepts_when_score_above_threshold(self):
+ """Accepts when satisfaction score above threshold."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.threshold_checker import (
+ ThresholdChecker,
+ )
+
+ mock_model = Mock()
+ mock_model.invoke.return_value.content = "0.85"
+ checker = ThresholdChecker(mock_model)
+
+ candidate = MockCandidate(name="Test")
+ constraint = MockConstraint(value="constraint")
+ evidence = [{"text": "good evidence"}]
+
+ should_reject, reason = checker.should_reject_candidate(
+ candidate, constraint, evidence
+ )
+
+ assert should_reject is False
+ assert reason == ""
+
+ def test_uses_custom_threshold(self):
+ """Uses custom satisfaction threshold."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.threshold_checker import (
+ ThresholdChecker,
+ )
+
+ mock_model = Mock()
+ mock_model.invoke.return_value.content = "0.5"
+ checker = ThresholdChecker(mock_model, satisfaction_threshold=0.4)
+
+ candidate = MockCandidate(name="Test")
+ constraint = MockConstraint(value="constraint")
+ evidence = [{"text": "evidence"}]
+
+ should_reject, _ = checker.should_reject_candidate(
+ candidate, constraint, evidence
+ )
+
+ assert should_reject is False # 0.5 >= 0.4
+
+
+class TestCheckCandidate:
+ """Tests for check_candidate method."""
+
+ def test_returns_constraint_check_result(self):
+ """Returns ConstraintCheckResult with all fields."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.threshold_checker import (
+ ThresholdChecker,
+ )
+
+ mock_model = Mock()
+ mock_model.invoke.return_value.content = "0.9"
+ mock_gatherer = Mock(return_value=[{"text": "evidence"}])
+ checker = ThresholdChecker(mock_model, evidence_gatherer=mock_gatherer)
+
+ candidate = MockCandidate(name="Test")
+ constraints = [MockConstraint(value="c1")]
+
+ result = checker.check_candidate(candidate, constraints)
+
+ assert hasattr(result, "total_score")
+ assert hasattr(result, "should_reject")
+ assert hasattr(result, "constraint_scores")
+ assert hasattr(result, "detailed_results")
+
+ def test_checks_all_constraints(self):
+ """Checks all provided constraints."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.threshold_checker import (
+ ThresholdChecker,
+ )
+
+ mock_model = Mock()
+ mock_model.invoke.return_value.content = "0.8"
+ mock_gatherer = Mock(return_value=[{"text": "evidence"}])
+ checker = ThresholdChecker(mock_model, evidence_gatherer=mock_gatherer)
+
+ candidate = MockCandidate(name="Test")
+ constraints = [
+ MockConstraint(value="c1"),
+ MockConstraint(value="c2"),
+ MockConstraint(value="c3"),
+ ]
+
+ result = checker.check_candidate(candidate, constraints)
+
+ assert len(result.detailed_results) == 3
+ assert "c1" in result.constraint_scores
+ assert "c2" in result.constraint_scores
+ assert "c3" in result.constraint_scores
+
+ def test_rejects_when_satisfaction_rate_too_low(self):
+ """Rejects when satisfaction rate below threshold."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.threshold_checker import (
+ ThresholdChecker,
+ )
+
+ mock_model = Mock()
+ # First constraint passes (0.9), others fail (0.3)
+ mock_model.invoke.return_value.content = "0.3"
+ mock_gatherer = Mock(return_value=[{"text": "evidence"}])
+ checker = ThresholdChecker(
+ mock_model,
+ evidence_gatherer=mock_gatherer,
+ satisfaction_threshold=0.7,
+ required_satisfaction_rate=0.8,
+ )
+
+ candidate = MockCandidate(name="Test")
+ constraints = [
+ MockConstraint(value="c1"),
+ MockConstraint(value="c2"),
+ MockConstraint(value="c3"),
+ ]
+
+ result = checker.check_candidate(candidate, constraints)
+
+ # 0/3 constraints satisfied = 0% < 80%
+ assert result.should_reject is True
+ assert "0/3" in result.rejection_reason
+
+ def test_accepts_when_satisfaction_rate_sufficient(self):
+ """Accepts when satisfaction rate meets threshold."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.threshold_checker import (
+ ThresholdChecker,
+ )
+
+ mock_model = Mock()
+ mock_model.invoke.return_value.content = "0.85"
+ mock_gatherer = Mock(return_value=[{"text": "evidence"}])
+ checker = ThresholdChecker(mock_model, evidence_gatherer=mock_gatherer)
+
+ candidate = MockCandidate(name="Test")
+ constraints = [MockConstraint(value="c1")]
+
+ result = checker.check_candidate(candidate, constraints)
+
+ assert result.should_reject is False
+ assert result.rejection_reason is None
+
+ def test_handles_no_evidence_for_constraint(self):
+ """Handles missing evidence for constraint."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.threshold_checker import (
+ ThresholdChecker,
+ )
+
+ mock_model = Mock()
+ mock_gatherer = Mock(return_value=[]) # No evidence
+ checker = ThresholdChecker(mock_model, evidence_gatherer=mock_gatherer)
+
+ candidate = MockCandidate(name="Test")
+ constraints = [MockConstraint(value="c1")]
+
+ result = checker.check_candidate(candidate, constraints)
+
+ assert result.constraint_scores["c1"]["total"] == 0.0
+ assert result.constraint_scores["c1"]["satisfied"] is False
+
+ def test_calculates_total_score_as_satisfaction_rate(self):
+ """Total score equals satisfaction rate when not rejected."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.threshold_checker import (
+ ThresholdChecker,
+ )
+
+ mock_model = Mock()
+ mock_model.invoke.return_value.content = "0.9"
+ mock_gatherer = Mock(return_value=[{"text": "evidence"}])
+ checker = ThresholdChecker(
+ mock_model,
+ evidence_gatherer=mock_gatherer,
+ required_satisfaction_rate=0.5,
+ )
+
+ candidate = MockCandidate(name="Test")
+ constraints = [
+ MockConstraint(value="c1"),
+ MockConstraint(value="c2"),
+ ]
+
+ result = checker.check_candidate(candidate, constraints)
+
+ # Both satisfied, so 100% satisfaction rate
+ assert result.total_score == 1.0
+
+ def test_sets_total_score_zero_when_rejected(self):
+ """Total score is zero when rejected."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.threshold_checker import (
+ ThresholdChecker,
+ )
+
+ mock_model = Mock()
+ mock_model.invoke.return_value.content = "0.3" # Below threshold
+ mock_gatherer = Mock(return_value=[{"text": "evidence"}])
+ checker = ThresholdChecker(mock_model, evidence_gatherer=mock_gatherer)
+
+ candidate = MockCandidate(name="Test")
+ constraints = [MockConstraint(value="c1")]
+
+ result = checker.check_candidate(candidate, constraints)
+
+ assert result.should_reject is True
+ assert result.total_score == 0.0
+
+ def test_stores_weight_in_constraint_scores(self):
+ """Stores constraint weight in scores."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.threshold_checker import (
+ ThresholdChecker,
+ )
+
+ mock_model = Mock()
+ mock_model.invoke.return_value.content = "0.9"
+ mock_gatherer = Mock(return_value=[{"text": "evidence"}])
+ checker = ThresholdChecker(mock_model, evidence_gatherer=mock_gatherer)
+
+ candidate = MockCandidate(name="Test")
+ constraints = [MockConstraint(value="c1", weight=2.5)]
+
+ result = checker.check_candidate(candidate, constraints)
+
+ assert result.constraint_scores["c1"]["weight"] == 2.5
+
+ def test_handles_empty_constraints_list(self):
+ """Handles empty constraints list."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.threshold_checker import (
+ ThresholdChecker,
+ )
+
+ mock_model = Mock()
+ checker = ThresholdChecker(mock_model)
+
+ candidate = MockCandidate(name="Test")
+ constraints = []
+
+ result = checker.check_candidate(candidate, constraints)
+
+ assert result.total_score == 0 # 0/0 division handled
+ assert result.should_reject is True # 0 < 0.8
+
+
+class TestDetailedResults:
+ """Tests for detailed_results structure."""
+
+ def test_detailed_results_contains_constraint_info(self):
+ """Detailed results contain constraint information."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.threshold_checker import (
+ ThresholdChecker,
+ )
+
+ mock_model = Mock()
+ mock_model.invoke.return_value.content = "0.75"
+ mock_gatherer = Mock(return_value=[{"text": "evidence"}])
+ checker = ThresholdChecker(mock_model, evidence_gatherer=mock_gatherer)
+
+ candidate = MockCandidate(name="Test")
+ constraints = [MockConstraint(value="test constraint", weight=1.5)]
+
+ result = checker.check_candidate(candidate, constraints)
+
+ detail = result.detailed_results[0]
+ assert detail["constraint"] == "test constraint"
+ assert detail["weight"] == 1.5
+ assert detail["type"] == "property"
+ assert "score" in detail
+ assert "satisfied" in detail
+
+ def test_detailed_results_score_matches_satisfaction_check(self):
+ """Score in detailed results matches satisfaction check."""
+ from src.local_deep_research.advanced_search_system.constraint_checking.threshold_checker import (
+ ThresholdChecker,
+ )
+
+ mock_model = Mock()
+ mock_model.invoke.return_value.content = "0.82"
+ mock_gatherer = Mock(return_value=[{"text": "evidence"}])
+ checker = ThresholdChecker(mock_model, evidence_gatherer=mock_gatherer)
+
+ candidate = MockCandidate(name="Test")
+ constraints = [MockConstraint(value="c1")]
+
+ result = checker.check_candidate(candidate, constraints)
+
+ assert result.detailed_results[0]["score"] == 0.82
+ assert result.detailed_results[0]["satisfied"] is True # 0.82 >= 0.7
diff --git a/tests/advanced_search_system/knowledge/test_followup_context_manager.py b/tests/advanced_search_system/knowledge/test_followup_context_manager.py
new file mode 100644
index 0000000000..7380936dc0
--- /dev/null
+++ b/tests/advanced_search_system/knowledge/test_followup_context_manager.py
@@ -0,0 +1,681 @@
+"""
+Tests for FollowUpContextHandler.
+
+Tests cover:
+- Initialization with model and settings
+- Context building from research data
+- Findings extraction from various data formats
+- Source extraction and deduplication
+- Entity extraction via LLM
+- Summary generation for context and prompts
+- Gap identification
+- Settings snapshot formatting
+- LLM context formatting
+"""
+
+from unittest.mock import Mock
+
+import pytest
+
+from src.local_deep_research.advanced_search_system.knowledge.followup_context_manager import (
+ FollowUpContextHandler,
+)
+
+
+class TestFollowUpContextHandlerInit:
+ """Tests for FollowUpContextHandler initialization."""
+
+ def test_init_stores_model(self):
+ """Handler stores the model reference."""
+ mock_model = Mock()
+ handler = FollowUpContextHandler(mock_model)
+ assert handler.model is mock_model
+
+ def test_init_with_settings_snapshot(self):
+ """Handler stores settings snapshot."""
+ mock_model = Mock()
+ settings = {"key": "value"}
+ handler = FollowUpContextHandler(mock_model, settings_snapshot=settings)
+ assert handler.settings_snapshot == settings
+
+ def test_init_without_settings_snapshot(self):
+ """Handler initializes empty settings snapshot when None."""
+ mock_model = Mock()
+ handler = FollowUpContextHandler(mock_model, settings_snapshot=None)
+ assert handler.settings_snapshot == {}
+
+ def test_init_creates_empty_cache(self):
+ """Handler initializes empty research cache."""
+ mock_model = Mock()
+ handler = FollowUpContextHandler(mock_model)
+ assert handler.past_research_cache == {}
+
+
+class TestBuildContext:
+ """Tests for build_context method."""
+
+ @pytest.fixture
+ def mock_model(self):
+ """Create mock model."""
+ mock = Mock()
+ mock.invoke.return_value = Mock(
+ content="Entity1\nEntity2\nSummary text"
+ )
+ return mock
+
+ @pytest.fixture
+ def handler(self, mock_model):
+ """Create handler instance."""
+ return FollowUpContextHandler(mock_model)
+
+ @pytest.fixture
+ def sample_research_data(self):
+ """Create sample research data."""
+ return {
+ "research_id": "research_123",
+ "query": "What is machine learning?",
+ "formatted_findings": "ML is a field of AI...",
+ "report_content": "Detailed report about ML...",
+ "resources": [
+ {"url": "https://example.com/1", "title": "Source 1"}
+ ],
+ "all_links_of_system": [
+ {"url": "https://example.com/2", "title": "Source 2"}
+ ],
+ "strategy": "detailed",
+ "mode": "research",
+ "created_at": "2024-01-14",
+ "research_meta": {"duration": 120},
+ }
+
+ def test_build_context_returns_dict(self, handler, sample_research_data):
+ """build_context returns a dictionary."""
+ result = handler.build_context(
+ sample_research_data, "What are ML applications?"
+ )
+ assert isinstance(result, dict)
+
+ def test_build_context_includes_parent_research_id(
+ self, handler, sample_research_data
+ ):
+ """Context includes parent_research_id."""
+ result = handler.build_context(
+ sample_research_data, "Follow-up question?"
+ )
+ assert result["parent_research_id"] == "research_123"
+
+ def test_build_context_includes_original_query(
+ self, handler, sample_research_data
+ ):
+ """Context includes original_query."""
+ result = handler.build_context(
+ sample_research_data, "Follow-up question?"
+ )
+ assert result["original_query"] == "What is machine learning?"
+
+ def test_build_context_includes_follow_up_query(
+ self, handler, sample_research_data
+ ):
+ """Context includes follow_up_query."""
+ result = handler.build_context(
+ sample_research_data, "What are ML applications?"
+ )
+ assert result["follow_up_query"] == "What are ML applications?"
+
+ def test_build_context_includes_all_keys(
+ self, handler, sample_research_data
+ ):
+ """Context includes all expected keys."""
+ result = handler.build_context(sample_research_data, "Follow-up?")
+ expected_keys = [
+ "parent_research_id",
+ "original_query",
+ "follow_up_query",
+ "past_findings",
+ "past_sources",
+ "key_entities",
+ "summary",
+ "report_content",
+ "formatted_findings",
+ "all_links_of_system",
+ "metadata",
+ ]
+ for key in expected_keys:
+ assert key in result
+
+
+class TestExtractFindings:
+ """Tests for _extract_findings method."""
+
+ @pytest.fixture
+ def handler(self):
+ """Create handler without model."""
+ return FollowUpContextHandler(None)
+
+ def test_extract_from_formatted_findings(self, handler):
+ """Extract from formatted_findings field."""
+ data = {"formatted_findings": "Formatted findings text"}
+ result = handler._extract_findings(data)
+ assert "Formatted findings text" in result
+
+ def test_extract_from_report_content_when_no_formatted(self, handler):
+ """Extract from report_content when no formatted_findings."""
+ data = {"report_content": "Report content text here"}
+ result = handler._extract_findings(data)
+ assert "Report content text" in result
+
+ def test_report_content_truncated_to_2000(self, handler):
+ """Report content is truncated to 2000 characters."""
+ long_content = "A" * 5000
+ data = {"report_content": long_content}
+ result = handler._extract_findings(data)
+ assert len(result) == 2000
+
+ def test_returns_default_when_no_findings(self, handler):
+ """Returns default message when no findings available."""
+ data = {}
+ result = handler._extract_findings(data)
+ assert result == "No previous findings available"
+
+ def test_prefers_formatted_over_report(self, handler):
+ """Prefers formatted_findings over report_content."""
+ data = {
+ "formatted_findings": "Formatted text",
+ "report_content": "Report text",
+ }
+ result = handler._extract_findings(data)
+ assert "Formatted text" in result
+
+
+class TestExtractSources:
+ """Tests for _extract_sources method."""
+
+ @pytest.fixture
+ def handler(self):
+ """Create handler without model."""
+ return FollowUpContextHandler(None)
+
+ def test_extract_from_resources(self, handler):
+ """Extract sources from resources field."""
+ data = {"resources": [{"url": "https://a.com", "title": "A"}]}
+ result = handler._extract_sources(data)
+ assert len(result) == 1
+ assert result[0]["url"] == "https://a.com"
+
+ def test_extract_from_all_links_of_system(self, handler):
+ """Extract sources from all_links_of_system field."""
+ data = {"all_links_of_system": [{"url": "https://b.com", "title": "B"}]}
+ result = handler._extract_sources(data)
+ assert len(result) == 1
+
+ def test_extract_from_past_links(self, handler):
+ """Extract sources from past_links field."""
+ data = {"past_links": [{"url": "https://c.com", "title": "C"}]}
+ result = handler._extract_sources(data)
+ assert len(result) == 1
+
+ def test_deduplicates_by_url(self, handler):
+ """Deduplicates sources by URL."""
+ data = {
+ "resources": [{"url": "https://a.com", "title": "A1"}],
+ "all_links_of_system": [{"url": "https://a.com", "title": "A2"}],
+ }
+ result = handler._extract_sources(data)
+ assert len(result) == 1
+
+ def test_includes_sources_without_url(self, handler):
+ """Includes sources that have no URL."""
+ data = {"resources": [{"title": "No URL source"}]}
+ result = handler._extract_sources(data)
+ assert len(result) == 1
+
+ def test_combines_all_source_fields(self, handler):
+ """Combines sources from all fields."""
+ data = {
+ "resources": [{"url": "https://a.com", "title": "A"}],
+ "all_links_of_system": [{"url": "https://b.com", "title": "B"}],
+ "past_links": [{"url": "https://c.com", "title": "C"}],
+ }
+ result = handler._extract_sources(data)
+ assert len(result) == 3
+
+ def test_returns_empty_list_when_no_sources(self, handler):
+ """Returns empty list when no sources available."""
+ data = {}
+ result = handler._extract_sources(data)
+ assert result == []
+
+
+class TestExtractEntities:
+ """Tests for _extract_entities method."""
+
+ @pytest.fixture
+ def mock_model(self):
+ """Create mock model."""
+ mock = Mock()
+ mock.invoke.return_value = Mock(content="Entity1\nEntity2\nEntity3")
+ return mock
+
+ @pytest.fixture
+ def handler(self, mock_model):
+ """Create handler with mock model."""
+ return FollowUpContextHandler(mock_model)
+
+ def test_extracts_entities_from_findings(self, handler):
+ """Extracts entities using LLM."""
+ data = {"formatted_findings": "Research findings about Python and ML"}
+ result = handler._extract_entities(data)
+ assert len(result) == 3
+ assert "Entity1" in result
+
+ def test_limits_to_10_entities(self, handler, mock_model):
+ """Limits entities to 10."""
+ mock_model.invoke.return_value = Mock(
+ content="\n".join([f"Entity{i}" for i in range(15)])
+ )
+ data = {"formatted_findings": "Some findings"}
+ result = handler._extract_entities(data)
+ assert len(result) <= 10
+
+ def test_returns_empty_when_no_findings_and_no_model(self):
+ """Returns empty list when no findings and no model."""
+ handler = FollowUpContextHandler(None)
+ data = {}
+ result = handler._extract_entities(data)
+ assert result == []
+
+ def test_returns_empty_when_no_model(self):
+ """Returns empty list when no model available."""
+ handler = FollowUpContextHandler(None)
+ data = {"formatted_findings": "Some findings"}
+ result = handler._extract_entities(data)
+ assert result == []
+
+ def test_handles_llm_exception(self, handler, mock_model):
+ """Handles LLM exception gracefully."""
+ mock_model.invoke.side_effect = RuntimeError("Connection failed")
+ data = {"formatted_findings": "Some findings"}
+ result = handler._extract_entities(data)
+ assert result == []
+
+
+class TestCreateSummary:
+ """Tests for _create_summary method."""
+
+ @pytest.fixture
+ def mock_model(self):
+ """Create mock model."""
+ mock = Mock()
+ mock.invoke.return_value = Mock(content="Summary of findings")
+ return mock
+
+ @pytest.fixture
+ def handler(self, mock_model):
+ """Create handler with mock model."""
+ return FollowUpContextHandler(mock_model)
+
+ def test_creates_summary_with_llm(self, handler):
+ """Creates summary using LLM."""
+ data = {
+ "formatted_findings": "Research findings",
+ "query": "Original question?",
+ }
+ handler._create_summary(data, "Follow-up question?")
+ assert handler.model.invoke.called
+
+ def test_includes_original_query_in_prompt(self, handler):
+ """Includes original query in prompt."""
+ data = {
+ "formatted_findings": "Research findings",
+ "query": "Original question?",
+ }
+ handler._create_summary(data, "Follow-up?")
+ call_args = handler.model.invoke.call_args[0][0]
+ assert "Original question?" in call_args
+
+
+class TestSummarizeForFollowup:
+ """Tests for summarize_for_followup method."""
+
+ @pytest.fixture
+ def mock_model(self):
+ """Create mock model."""
+ mock = Mock()
+ mock.invoke.return_value = Mock(content="Concise summary")
+ return mock
+
+ @pytest.fixture
+ def handler(self, mock_model):
+ """Create handler with mock model."""
+ return FollowUpContextHandler(mock_model)
+
+ def test_summarize_returns_string(self, handler):
+ """summarize_for_followup returns a string."""
+ result = handler.summarize_for_followup(
+ "Long findings text...", "Follow-up question?"
+ )
+ assert isinstance(result, str)
+
+ def test_summarize_respects_max_length(self, handler, mock_model):
+ """Result respects max_length constraint."""
+ mock_model.invoke.return_value = Mock(content="A" * 2000)
+ result = handler.summarize_for_followup(
+ "Findings", "Question?", max_length=500
+ )
+ assert len(result) <= 503 # 500 + "..."
+
+ def test_short_findings_returned_as_is(self, handler):
+ """Short findings are returned as-is without LLM call."""
+ result = handler.summarize_for_followup(
+ "Short text", "Question?", max_length=1000
+ )
+ # Model should not be called for short text
+ assert result == "Short text"
+
+
+class TestGenerateSummary:
+ """Tests for _generate_summary method."""
+
+ @pytest.fixture
+ def mock_model(self):
+ """Create mock model."""
+ mock = Mock()
+ mock.invoke.return_value = Mock(content="Generated summary")
+ return mock
+
+ @pytest.fixture
+ def handler(self, mock_model):
+ """Create handler with mock model."""
+ return FollowUpContextHandler(mock_model)
+
+ def test_returns_empty_for_empty_findings(self, handler):
+ """Returns empty string for empty findings."""
+ result = handler._generate_summary("", "Query")
+ assert result == ""
+
+ def test_returns_findings_when_short_enough(self, handler):
+ """Returns findings as-is when within max_length."""
+ result = handler._generate_summary(
+ "Short findings", "Query", max_length=1000
+ )
+ assert result == "Short findings"
+
+ def test_context_purpose_includes_original_query(self, handler):
+ """Context purpose prompt includes original query."""
+ handler._generate_summary(
+ "Long " * 500, # Force LLM call
+ "Follow-up?",
+ original_query="Original?",
+ purpose="context",
+ )
+ call_args = handler.model.invoke.call_args[0][0]
+ assert "Original?" in call_args
+
+ def test_prompt_purpose_omits_original_query(self, handler):
+ """Prompt purpose omits original query reference."""
+ handler._generate_summary(
+ "Long " * 500,
+ "Follow-up?",
+ original_query="Original?",
+ purpose="prompt",
+ )
+ call_args = handler.model.invoke.call_args[0][0]
+ # Prompt purpose uses simpler format
+ assert "Follow-up?" in call_args
+
+ def test_fallback_without_model(self):
+ """Fallback truncation when no model available."""
+ handler = FollowUpContextHandler(None)
+ result = handler._generate_summary("A" * 1000, "Query", max_length=100)
+ assert len(result) <= 103 # 100 + "..."
+
+ def test_handles_llm_exception(self, handler, mock_model):
+ """Handles LLM exception with truncation fallback."""
+ mock_model.invoke.side_effect = RuntimeError("Error")
+ result = handler._generate_summary("A" * 1000, "Query", max_length=100)
+ assert len(result) <= 103
+
+
+class TestIdentifyGaps:
+ """Tests for identify_gaps method."""
+
+ @pytest.fixture
+ def mock_model(self):
+ """Create mock model."""
+ mock = Mock()
+ mock.invoke.return_value = Mock(content="Gap 1\nGap 2\nGap 3")
+ return mock
+
+ @pytest.fixture
+ def handler(self, mock_model):
+ """Create handler with mock model."""
+ return FollowUpContextHandler(mock_model)
+
+ def test_identifies_gaps(self, handler):
+ """Identifies gaps using LLM."""
+ data = {"formatted_findings": "Some research findings"}
+ result = handler.identify_gaps(data, "Follow-up question?")
+ assert len(result) == 3
+ assert "Gap 1" in result
+
+ def test_limits_to_5_gaps(self, handler, mock_model):
+ """Limits gaps to 5."""
+ mock_model.invoke.return_value = Mock(
+ content="\n".join([f"Gap {i}" for i in range(10)])
+ )
+ data = {"formatted_findings": "Findings"}
+ result = handler.identify_gaps(data, "Question?")
+ assert len(result) <= 5
+
+ def test_returns_empty_when_no_findings_and_no_model(self):
+ """Returns empty list when no findings and no model."""
+ handler = FollowUpContextHandler(None)
+ data = {}
+ result = handler.identify_gaps(data, "Question?")
+ assert result == []
+
+ def test_returns_empty_when_no_model(self):
+ """Returns empty list when no model."""
+ handler = FollowUpContextHandler(None)
+ data = {"formatted_findings": "Findings"}
+ result = handler.identify_gaps(data, "Question?")
+ assert result == []
+
+ def test_handles_llm_exception(self, handler, mock_model):
+ """Handles LLM exception gracefully."""
+ mock_model.invoke.side_effect = RuntimeError("Error")
+ data = {"formatted_findings": "Findings"}
+ result = handler.identify_gaps(data, "Question?")
+ assert result == []
+
+
+class TestFormatForSettingsSnapshot:
+ """Tests for format_for_settings_snapshot method."""
+
+ @pytest.fixture
+ def handler(self):
+ """Create handler without model."""
+ return FollowUpContextHandler(None)
+
+ def test_returns_minimal_metadata(self, handler):
+ """Returns minimal metadata dictionary."""
+ context = {
+ "parent_research_id": "research_123",
+ "past_findings": "Some findings",
+ "extra_data": "Should not be included",
+ }
+ result = handler.format_for_settings_snapshot(context)
+ assert "followup_metadata" in result
+ assert (
+ result["followup_metadata"]["parent_research_id"] == "research_123"
+ )
+ assert result["followup_metadata"]["is_followup"] is True
+
+ def test_has_context_true_when_findings_present(self, handler):
+ """has_context is True when past_findings present."""
+ context = {"past_findings": "Some findings"}
+ result = handler.format_for_settings_snapshot(context)
+ assert result["followup_metadata"]["has_context"] is True
+
+ def test_has_context_false_when_no_findings(self, handler):
+ """has_context is False when no past_findings."""
+ context = {}
+ result = handler.format_for_settings_snapshot(context)
+ assert result["followup_metadata"]["has_context"] is False
+
+
+class TestGetRelevantContextForLLM:
+ """Tests for get_relevant_context_for_llm method."""
+
+ @pytest.fixture
+ def handler(self):
+ """Create handler without model."""
+ return FollowUpContextHandler(None)
+
+ def test_includes_original_query(self, handler):
+ """Includes original query in output."""
+ context = {"original_query": "Original question?"}
+ result = handler.get_relevant_context_for_llm(context)
+ assert "Original question?" in result
+
+ def test_includes_follow_up_query(self, handler):
+ """Includes follow-up query in output."""
+ context = {"follow_up_query": "Follow-up question?"}
+ result = handler.get_relevant_context_for_llm(context)
+ assert "Follow-up question?" in result
+
+ def test_includes_summary(self, handler):
+ """Includes summary in output."""
+ context = {"summary": "Summary of findings"}
+ result = handler.get_relevant_context_for_llm(context)
+ assert "Summary of findings" in result
+
+ def test_includes_key_entities(self, handler):
+ """Includes key entities in output."""
+ context = {"key_entities": ["Entity1", "Entity2", "Entity3"]}
+ result = handler.get_relevant_context_for_llm(context)
+ assert "Entity1" in result
+
+ def test_limits_entities_to_5(self, handler):
+ """Limits entities to first 5."""
+ context = {"key_entities": [f"Entity{i}" for i in range(10)]}
+ result = handler.get_relevant_context_for_llm(context)
+ assert "Entity4" in result
+ assert "Entity5" not in result or result.count("Entity") <= 5
+
+ def test_includes_source_count(self, handler):
+ """Includes source count in output."""
+ context = {"past_sources": [{"url": "a"}, {"url": "b"}, {"url": "c"}]}
+ result = handler.get_relevant_context_for_llm(context)
+ assert "3" in result
+
+ def test_truncates_to_max_tokens(self, handler):
+ """Truncates output to approximate max_tokens."""
+ context = {
+ "original_query": "A" * 1000,
+ "follow_up_query": "B" * 1000,
+ "summary": "C" * 10000,
+ }
+ result = handler.get_relevant_context_for_llm(context, max_tokens=500)
+ # max_tokens * 4 = 2000 chars
+ assert len(result) <= 2003 # 2000 + "..."
+
+
+class TestExtractMetadata:
+ """Tests for _extract_metadata method."""
+
+ @pytest.fixture
+ def handler(self):
+ """Create handler without model."""
+ return FollowUpContextHandler(None)
+
+ def test_extracts_strategy(self, handler):
+ """Extracts strategy from research data."""
+ data = {"strategy": "detailed"}
+ result = handler._extract_metadata(data)
+ assert result["strategy"] == "detailed"
+
+ def test_extracts_mode(self, handler):
+ """Extracts mode from research data."""
+ data = {"mode": "research"}
+ result = handler._extract_metadata(data)
+ assert result["mode"] == "research"
+
+ def test_extracts_created_at(self, handler):
+ """Extracts created_at from research data."""
+ data = {"created_at": "2024-01-14"}
+ result = handler._extract_metadata(data)
+ assert result["created_at"] == "2024-01-14"
+
+ def test_extracts_research_meta(self, handler):
+ """Extracts research_meta from research data."""
+ data = {"research_meta": {"duration": 120}}
+ result = handler._extract_metadata(data)
+ assert result["research_meta"]["duration"] == 120
+
+ def test_returns_empty_strings_for_missing_fields(self, handler):
+ """Returns empty strings for missing fields."""
+ data = {}
+ result = handler._extract_metadata(data)
+ assert result["strategy"] == ""
+ assert result["mode"] == ""
+ assert result["created_at"] == ""
+ assert result["research_meta"] == {}
+
+
+class TestIntegration:
+ """Integration tests for complete workflows."""
+
+ @pytest.fixture
+ def mock_model(self):
+ """Create mock model with realistic responses."""
+ mock = Mock()
+
+ def invoke_side_effect(prompt):
+ if "entities" in prompt.lower():
+ return Mock(content="Python\nMachine Learning\nAI")
+ elif "summary" in prompt.lower() or "summarize" in prompt.lower():
+ return Mock(content="A concise summary of the research.")
+ elif "gaps" in prompt.lower():
+ return Mock(content="Gap 1\nGap 2")
+ return Mock(content="Default response")
+
+ mock.invoke.side_effect = invoke_side_effect
+ return mock
+
+ @pytest.fixture
+ def handler(self, mock_model):
+ """Create handler with mock model."""
+ return FollowUpContextHandler(mock_model)
+
+ def test_full_workflow(self, handler):
+ """Test complete workflow from research data to context."""
+ research_data = {
+ "research_id": "research_123",
+ "query": "What is machine learning?",
+ "formatted_findings": "Machine learning is a branch of AI that enables computers to learn from data.",
+ "resources": [{"url": "https://example.com", "title": "ML Guide"}],
+ "strategy": "detailed",
+ "mode": "research",
+ }
+
+ context = handler.build_context(
+ research_data, "How is ML used in healthcare?"
+ )
+
+ # Verify context structure
+ assert context["parent_research_id"] == "research_123"
+ assert context["original_query"] == "What is machine learning?"
+ assert context["follow_up_query"] == "How is ML used in healthcare?"
+ assert len(context["past_sources"]) == 1
+ assert len(context["key_entities"]) > 0
+
+ def test_full_workflow_with_gaps(self, handler):
+ """Test gap identification in complete workflow."""
+ research_data = {
+ "formatted_findings": "Some research findings about ML."
+ }
+
+ gaps = handler.identify_gaps(research_data, "What about deep learning?")
+ assert isinstance(gaps, list)
+ assert len(gaps) <= 5
diff --git a/tests/advanced_search_system/questions/test_decomposition_question.py b/tests/advanced_search_system/questions/test_decomposition_question.py
new file mode 100644
index 0000000000..0738ff7b00
--- /dev/null
+++ b/tests/advanced_search_system/questions/test_decomposition_question.py
@@ -0,0 +1,513 @@
+"""
+Tests for DecompositionQuestionGenerator.
+
+Tests cover:
+- Initialization with default and custom parameters
+- Subject extraction from various question formats
+- Compound question splitting on conjunctions
+- Article removal from subjects
+- LLM response parsing (numbered, bulleted, plain text)
+- Error handling (LLM errors, exceptions)
+- Default question generation for various topic types
+"""
+
+from unittest.mock import Mock
+
+import pytest
+
+from src.local_deep_research.advanced_search_system.questions.decomposition_question import (
+ DecompositionQuestionGenerator,
+)
+
+
+class TestDecompositionQuestionGeneratorInit:
+ """Tests for DecompositionQuestionGenerator initialization."""
+
+ def test_init_with_default_max_subqueries(self):
+ """Default max_subqueries is 5."""
+ mock_model = Mock()
+ generator = DecompositionQuestionGenerator(mock_model)
+ assert generator.max_subqueries == 5
+
+ def test_init_with_custom_max_subqueries(self):
+ """Custom max_subqueries is stored correctly."""
+ mock_model = Mock()
+ generator = DecompositionQuestionGenerator(mock_model, max_subqueries=3)
+ assert generator.max_subqueries == 3
+
+ def test_init_stores_model(self):
+ """Generator stores the model reference."""
+ mock_model = Mock()
+ generator = DecompositionQuestionGenerator(mock_model)
+ assert generator.model is mock_model
+
+
+class TestSubjectExtraction:
+ """Tests for subject extraction from question formats."""
+
+ @pytest.fixture
+ def mock_model(self):
+ """Create mock model that returns valid questions."""
+ mock = Mock()
+ mock.invoke.return_value = Mock(
+ content="What is the definition?\nHow does it work?\nWhat are examples?"
+ )
+ return mock
+
+ @pytest.fixture
+ def generator(self, mock_model):
+ """Create generator instance."""
+ return DecompositionQuestionGenerator(mock_model)
+
+ def test_extract_subject_from_what_is_question(self, generator):
+ """Extract subject from 'what is' question."""
+ generator.generate_questions("What is machine learning?", "")
+ # Model was invoked with correct subject
+ call_args = generator.model.invoke.call_args[0][0]
+ assert "machine learning" in call_args
+
+ def test_extract_subject_from_how_does_question(self, generator):
+ """Extract subject from 'how does' question."""
+ generator.generate_questions("How does deep learning work?", "")
+ call_args = generator.model.invoke.call_args[0][0]
+ assert "deep learning work" in call_args
+
+ def test_extract_subject_from_why_is_question(self, generator):
+ """Extract subject from 'why is' question."""
+ generator.generate_questions("Why is encryption important?", "")
+ call_args = generator.model.invoke.call_args[0][0]
+ assert "encryption important" in call_args
+
+ def test_extract_subject_from_who_is_question(self, generator):
+ """Extract subject from 'who is' question."""
+ generator.generate_questions("Who is Alan Turing?", "")
+ call_args = generator.model.invoke.call_args[0][0]
+ assert "Alan Turing" in call_args
+
+ def test_non_question_uses_full_query(self, generator):
+ """Non-question query uses the full query as subject."""
+ generator.generate_questions("machine learning algorithms", "")
+ call_args = generator.model.invoke.call_args[0][0]
+ assert "machine learning algorithms" in call_args
+
+
+class TestCompoundQuestionSplitting:
+ """Tests for splitting compound questions on conjunctions."""
+
+ @pytest.fixture
+ def mock_model(self):
+ """Create mock model."""
+ mock = Mock()
+ mock.invoke.return_value = Mock(
+ content="Q1: What is it?\nQ2: How does it work?\nQ3: Examples?"
+ )
+ return mock
+
+ @pytest.fixture
+ def generator(self, mock_model):
+ """Create generator instance."""
+ return DecompositionQuestionGenerator(mock_model)
+
+ def test_split_on_and_conjunction(self, generator):
+ """Split compound question at ' and '."""
+ generator.generate_questions("What is Python and how is it used?", "")
+ call_args = generator.model.invoke.call_args[0][0]
+ # Should extract "Python" before " and "
+ assert "Python" in call_args
+
+ def test_split_on_or_conjunction(self, generator):
+ """Split compound question at ' or '."""
+ generator.generate_questions(
+ "What is Java or C++ better for games?", ""
+ )
+ call_args = generator.model.invoke.call_args[0][0]
+ assert "Java" in call_args
+
+ def test_split_on_but_conjunction(self, generator):
+ """Split compound question at ' but '."""
+ generator.generate_questions("What is fast but easy to learn?", "")
+ call_args = generator.model.invoke.call_args[0][0]
+ assert "fast" in call_args
+
+ def test_split_on_when_conjunction(self, generator):
+ """Split compound question at ' when '."""
+ generator.generate_questions(
+ "What is Python when used for web development?", ""
+ )
+ call_args = generator.model.invoke.call_args[0][0]
+ assert "Python" in call_args
+
+
+class TestArticleRemoval:
+ """Tests for removing articles from subjects."""
+
+ @pytest.fixture
+ def mock_model(self):
+ """Create mock model."""
+ mock = Mock()
+ mock.invoke.return_value = Mock(content="Q1\nQ2\nQ3")
+ return mock
+
+ @pytest.fixture
+ def generator(self, mock_model):
+ """Create generator instance."""
+ return DecompositionQuestionGenerator(mock_model)
+
+ def test_remove_article_a(self, generator):
+ """Remove 'a' article from subject."""
+ generator.generate_questions("What is a neural network?", "")
+ call_args = generator.model.invoke.call_args[0][0]
+ # Should not contain "a neural network", just "neural network"
+ assert "neural network" in call_args
+
+ def test_remove_article_an(self, generator):
+ """Remove 'an' article from subject."""
+ generator.generate_questions("What is an algorithm?", "")
+ call_args = generator.model.invoke.call_args[0][0]
+ assert "algorithm" in call_args
+
+ def test_remove_article_the(self, generator):
+ """Remove 'the' article from subject."""
+ generator.generate_questions("What is the internet?", "")
+ call_args = generator.model.invoke.call_args[0][0]
+ assert "internet" in call_args
+
+
+class TestLLMResponseParsing:
+ """Tests for parsing different LLM response formats."""
+
+ @pytest.fixture
+ def generator(self):
+ """Create generator with mock model."""
+ mock_model = Mock()
+ return DecompositionQuestionGenerator(mock_model)
+
+ def test_parse_numbered_response(self, generator):
+ """Parse numbered list format (1. 2. 3.)."""
+ generator.model.invoke.return_value = Mock(
+ content="1. What is the definition?\n2. How does it work?\n3. What are examples?"
+ )
+ result = generator.generate_questions("test topic", "")
+ # Lines starting with "1. " etc. are skipped in first pass, but content is extracted
+ assert len(result) >= 0 # May use fallback depending on parsing
+
+ def test_parse_bulleted_response(self, generator):
+ """Parse bulleted list format (-, *, •)."""
+ generator.model.invoke.return_value = Mock(
+ content="- What is the definition of topic?\n* How does topic work?\n• What are topic examples?"
+ )
+ result = generator.generate_questions("test topic", "")
+ assert len(result) >= 0
+
+ def test_parse_plain_text_response(self, generator):
+ """Parse plain text questions (one per line, no bullets)."""
+ generator.model.invoke.return_value = Mock(
+ content="What is the definition of topic?\nHow does topic work?\nWhat are topic examples?"
+ )
+ result = generator.generate_questions("test topic", "")
+ assert len(result) == 3
+ assert "What is the definition of topic?" in result
+
+ def test_handle_response_with_content_attribute(self, generator):
+ """Handle response object with .content attribute."""
+ mock_response = Mock()
+ mock_response.content = (
+ "Question one here?\nQuestion two here?\nQuestion three here?"
+ )
+ generator.model.invoke.return_value = mock_response
+ result = generator.generate_questions("test", "")
+ assert len(result) == 3
+
+ def test_handle_string_response(self, generator):
+ """Handle plain string response (no .content attribute)."""
+ generator.model.invoke.return_value = (
+ "Question one here?\nQuestion two here?\nQuestion three here?"
+ )
+ result = generator.generate_questions("test", "")
+ assert len(result) == 3
+
+ def test_filter_short_lines(self, generator):
+ """Filter out lines shorter than 10 characters."""
+ generator.model.invoke.return_value = Mock(
+ content="Short\nThis is a valid question longer than ten chars?\nOK"
+ )
+ result = generator.generate_questions("test", "")
+ assert len(result) == 1
+ assert "This is a valid question" in result[0]
+
+ def test_skip_empty_lines(self, generator):
+ """Skip empty lines in response."""
+ generator.model.invoke.return_value = Mock(
+ content="First valid question here?\n\n\nSecond valid question here?"
+ )
+ result = generator.generate_questions("test", "")
+ assert len(result) == 2
+
+ def test_respect_max_subqueries_limit(self, generator):
+ """Respect max_subqueries limit."""
+ generator.max_subqueries = 2
+ generator.model.invoke.return_value = Mock(
+ content="Question one here?\nQuestion two here?\nQuestion three here?\nQuestion four here?"
+ )
+ result = generator.generate_questions("test", "")
+ assert len(result) <= 2
+
+
+class TestLLMErrorHandling:
+ """Tests for handling LLM errors and fallbacks."""
+
+ @pytest.fixture
+ def generator(self):
+ """Create generator with mock model."""
+ mock_model = Mock()
+ return DecompositionQuestionGenerator(mock_model)
+
+ def test_handle_no_language_models_error(self, generator):
+ """Fall back to defaults when 'No language models are available'."""
+ generator.model.invoke.return_value = Mock(
+ content="No language models are available. Please install Ollama."
+ )
+ result = generator.generate_questions("What is Python?", "")
+ # Should return default questions
+ assert len(result) > 0
+ assert any("Python" in q for q in result)
+
+ def test_handle_please_install_ollama_error(self, generator):
+ """Fall back to defaults when 'Please install Ollama'."""
+ generator.model.invoke.return_value = Mock(
+ content="Please install Ollama to use local models."
+ )
+ result = generator.generate_questions("What is Python?", "")
+ assert len(result) > 0
+
+ def test_handle_llm_exception(self, generator):
+ """Fall back to defaults when LLM raises exception."""
+ generator.model.invoke.side_effect = RuntimeError("Connection failed")
+ result = generator.generate_questions("What is Python?", "")
+ # Should catch exception and return default questions
+ assert len(result) > 0
+ assert any("Python" in q for q in result)
+
+ def test_simplified_prompt_fallback(self, generator):
+ """Use simplified prompt when first attempt yields no results."""
+ # First call returns unparseable content, second returns valid
+ generator.model.invoke.side_effect = [
+ Mock(
+ content="*\n-\n•"
+ ), # Only formatting chars, no valid questions
+ Mock(
+ content="1. Valid question here?\n2. Another valid one?\n3. Third question?"
+ ),
+ ]
+ generator.generate_questions("test topic", "")
+ # Should have called invoke twice
+ assert generator.model.invoke.call_count == 2
+
+ def test_fallback_to_defaults_after_both_prompts_fail(self, generator):
+ """Fall back to defaults when both prompts fail."""
+ generator.model.invoke.side_effect = [
+ Mock(content=""), # Empty first response
+ Mock(content=""), # Empty second response
+ ]
+ result = generator.generate_questions("What is AI?", "")
+ # Should return default questions
+ assert len(result) > 0
+
+
+class TestDefaultQuestionGeneration:
+ """Tests for _generate_default_questions method."""
+
+ @pytest.fixture
+ def generator(self):
+ """Create generator with mock model."""
+ mock_model = Mock()
+ return DecompositionQuestionGenerator(mock_model)
+
+ def test_csrf_special_case(self, generator):
+ """Generate CSRF-specific questions for CSRF queries."""
+ result = generator._generate_default_questions("What is CSRF?")
+ assert any("CSRF" in q for q in result)
+ assert any("Cross-Site Request Forgery" in q for q in result)
+
+ def test_csrf_full_name(self, generator):
+ """Generate CSRF-specific questions for full name."""
+ result = generator._generate_default_questions(
+ "What is cross-site request forgery?"
+ )
+ assert any("CSRF" in q for q in result)
+
+ def test_security_topic_questions(self, generator):
+ """Generate security-focused questions for security topics."""
+ result = generator._generate_default_questions(
+ "What is SQL injection vulnerability?"
+ )
+ assert any(
+ "vulnerability" in q.lower() or "attack" in q.lower()
+ for q in result
+ )
+
+ def test_programming_topic_questions(self, generator):
+ """Generate programming-focused questions for programming topics."""
+ result = generator._generate_default_questions(
+ "Python programming language"
+ )
+ assert any(
+ "features" in q.lower() or "advantages" in q.lower() for q in result
+ )
+
+ def test_short_subject_questions(self, generator):
+ """Generate appropriate questions for short subjects (1-2 words)."""
+ result = generator._generate_default_questions("AI")
+ assert result[0] == "What is AI?"
+ assert any("characteristics" in q for q in result)
+
+ def test_generic_topic_questions(self, generator):
+ """Generate generic questions for unrecognized topics."""
+ result = generator._generate_default_questions(
+ "quantum entanglement in physics research"
+ )
+ assert any("definition" in q.lower() for q in result)
+ assert any(
+ "components" in q.lower() or "features" in q.lower() for q in result
+ )
+
+ def test_empty_query_questions(self, generator):
+ """Generate generic questions for empty query."""
+ result = generator._generate_default_questions("")
+ assert len(result) > 0
+ assert any("definition" in q.lower() for q in result)
+
+ def test_default_respects_max_subqueries(self, generator):
+ """Default questions respect max_subqueries limit."""
+ generator.max_subqueries = 2
+ result = generator._generate_default_questions("What is Python?")
+ assert len(result) <= 2
+
+
+class TestContextHandling:
+ """Tests for context parameter handling."""
+
+ @pytest.fixture
+ def generator(self):
+ """Create generator with mock model."""
+ mock_model = Mock()
+ mock_model.invoke.return_value = Mock(
+ content="Q1: First question?\nQ2: Second question?\nQ3: Third?"
+ )
+ return DecompositionQuestionGenerator(mock_model)
+
+ def test_context_included_in_prompt(self, generator):
+ """Context is included in the LLM prompt."""
+ context = "This is relevant context information."
+ generator.generate_questions("test query", context)
+ call_args = generator.model.invoke.call_args[0][0]
+ assert "This is relevant context information" in call_args
+
+ def test_long_context_truncated(self, generator):
+ """Long context is truncated to 2000 characters."""
+ long_context = "A" * 5000
+ generator.generate_questions("test query", long_context)
+ call_args = generator.model.invoke.call_args[0][0]
+ # Context should be truncated - the prompt won't contain 5000 A's
+ assert call_args.count("A") <= 2000
+
+ def test_empty_context_handled(self, generator):
+ """Empty context is handled gracefully."""
+ result = generator.generate_questions("test query", "")
+ assert result is not None
+
+
+class TestIntegration:
+ """Integration tests for complete workflows."""
+
+ @pytest.fixture
+ def mock_model(self):
+ """Create mock model with realistic responses."""
+ mock = Mock()
+ mock.invoke.return_value = Mock(
+ content="""What is the definition of machine learning?
+How does machine learning differ from traditional programming?
+What are common applications of machine learning?
+What are the main types of machine learning algorithms?"""
+ )
+ return mock
+
+ @pytest.fixture
+ def generator(self, mock_model):
+ """Create generator instance."""
+ return DecompositionQuestionGenerator(mock_model)
+
+ def test_full_workflow_simple_query(self, generator):
+ """Test complete workflow with simple query."""
+ result = generator.generate_questions("machine learning", "")
+ assert isinstance(result, list)
+ assert len(result) > 0
+ assert all(isinstance(q, str) for q in result)
+
+ def test_full_workflow_question_query(self, generator):
+ """Test complete workflow with question-format query."""
+ result = generator.generate_questions(
+ "What is machine learning and how does it work?", ""
+ )
+ assert isinstance(result, list)
+ assert len(result) > 0
+
+ def test_full_workflow_with_context(self, generator):
+ """Test complete workflow with context provided."""
+ context = "Machine learning is a subset of artificial intelligence."
+ result = generator.generate_questions("machine learning", context)
+ assert isinstance(result, list)
+ assert len(result) > 0
+
+
+class TestEdgeCases:
+ """Tests for edge cases and boundary conditions."""
+
+ @pytest.fixture
+ def generator(self):
+ """Create generator with mock model."""
+ mock_model = Mock()
+ mock_model.invoke.return_value = Mock(content="Valid question here?")
+ return DecompositionQuestionGenerator(mock_model)
+
+ def test_whitespace_only_query(self, generator):
+ """Handle whitespace-only query."""
+ result = generator.generate_questions(" ", "")
+ assert isinstance(result, list)
+
+ def test_special_characters_in_query(self, generator):
+ """Handle special characters in query."""
+ result = generator.generate_questions("What is C++ & C#?", "")
+ assert isinstance(result, list)
+
+ def test_unicode_in_query(self, generator):
+ """Handle unicode characters in query."""
+ result = generator.generate_questions("What is 日本語?", "")
+ assert isinstance(result, list)
+
+ def test_very_long_query(self, generator):
+ """Handle very long query."""
+ long_query = "What is " + "very " * 100 + "long query?"
+ result = generator.generate_questions(long_query, "")
+ assert isinstance(result, list)
+
+ def test_query_with_newlines(self, generator):
+ """Handle query with newline characters."""
+ result = generator.generate_questions("What is\nmachine\nlearning?", "")
+ assert isinstance(result, list)
+
+ def test_max_subqueries_zero(self, generator):
+ """Handle max_subqueries set to zero."""
+ generator.max_subqueries = 0
+ generator.model.invoke.return_value = Mock(content="Q1?\nQ2?\nQ3?")
+ result = generator.generate_questions("test", "")
+ assert len(result) == 0
+
+ def test_max_subqueries_one(self, generator):
+ """Handle max_subqueries set to one."""
+ generator.max_subqueries = 1
+ generator.model.invoke.return_value = Mock(
+ content="First question?\nSecond question?\nThird question?"
+ )
+ result = generator.generate_questions("test", "")
+ assert len(result) == 1
diff --git a/tests/advanced_search_system/questions/test_entity_aware_question.py b/tests/advanced_search_system/questions/test_entity_aware_question.py
new file mode 100644
index 0000000000..587eb9bad5
--- /dev/null
+++ b/tests/advanced_search_system/questions/test_entity_aware_question.py
@@ -0,0 +1,463 @@
+"""
+Tests for EntityAwareQuestionGenerator.
+
+Tests cover:
+- Entity detection with various keywords
+- Entity-focused prompt generation with/without past questions
+- Response parsing for Q: prefixed lines
+- Non-entity query fallback to parent class
+- Sub-question generation for entity queries
+- Error handling for exceptions
+"""
+
+from datetime import datetime, UTC
+from unittest.mock import Mock, patch
+
+import pytest
+
+from src.local_deep_research.advanced_search_system.questions.entity_aware_question import (
+ EntityAwareQuestionGenerator,
+)
+
+
+class TestEntityAwareQuestionGeneratorInit:
+ """Tests for EntityAwareQuestionGenerator initialization."""
+
+ def test_init_stores_model(self):
+ """Generator stores the model reference."""
+ mock_model = Mock()
+ generator = EntityAwareQuestionGenerator(mock_model)
+ assert generator.model is mock_model
+
+
+class TestEntityDetection:
+ """Tests for entity keyword detection."""
+
+ @pytest.fixture
+ def mock_model(self):
+ """Create mock model."""
+ mock = Mock()
+ mock.invoke.return_value = Mock(content="Q: query1\nQ: query2")
+ return mock
+
+ @pytest.fixture
+ def generator(self, mock_model):
+ """Create generator instance."""
+ return EntityAwareQuestionGenerator(mock_model)
+
+ def test_detect_who_keyword(self, generator):
+ """Detect 'who' as entity keyword."""
+ generator.generate_questions("", "Who is the president?", 2)
+ # Entity query uses entity-focused prompt, check model was called
+ assert generator.model.invoke.called
+ call_args = generator.model.invoke.call_args[0][0]
+ assert "entity" in call_args.lower() or "identify" in call_args.lower()
+
+ def test_detect_what_keyword(self, generator):
+ """Detect 'what' as entity keyword."""
+ generator.generate_questions("", "What character is this?", 2)
+ assert generator.model.invoke.called
+
+ def test_detect_which_keyword(self, generator):
+ """Detect 'which' as entity keyword."""
+ generator.generate_questions("", "Which movie won the award?", 2)
+ assert generator.model.invoke.called
+
+ def test_detect_identify_keyword(self, generator):
+ """Detect 'identify' as entity keyword."""
+ generator.generate_questions("", "Identify the person", 2)
+ assert generator.model.invoke.called
+
+ def test_detect_name_keyword(self, generator):
+ """Detect 'name' as entity keyword."""
+ generator.generate_questions("", "Name the scientist", 2)
+ assert generator.model.invoke.called
+
+ def test_detect_character_keyword(self, generator):
+ """Detect 'character' as entity keyword."""
+ generator.generate_questions("", "The character from TV", 2)
+ assert generator.model.invoke.called
+
+ def test_detect_person_keyword(self, generator):
+ """Detect 'person' as entity keyword."""
+ generator.generate_questions("", "The person responsible", 2)
+ assert generator.model.invoke.called
+
+ def test_detect_company_keyword(self, generator):
+ """Detect 'company' as entity keyword."""
+ generator.generate_questions("", "The company that made it", 2)
+ assert generator.model.invoke.called
+
+ def test_detect_author_keyword(self, generator):
+ """Detect 'author' as entity keyword."""
+ generator.generate_questions("", "The author of the book", 2)
+ assert generator.model.invoke.called
+
+ def test_case_insensitive_detection(self, generator):
+ """Entity detection is case-insensitive."""
+ generator.generate_questions("", "WHO is the president?", 2)
+ assert generator.model.invoke.called
+
+
+class TestNonEntityQueryFallback:
+ """Tests for non-entity query fallback to parent class."""
+
+ @pytest.fixture
+ def mock_model(self):
+ """Create mock model."""
+ mock = Mock()
+ mock.invoke.return_value = Mock(content="Q: query1\nQ: query2")
+ return mock
+
+ @pytest.fixture
+ def generator(self, mock_model):
+ """Create generator instance."""
+ return EntityAwareQuestionGenerator(mock_model)
+
+ def test_non_entity_query_uses_parent(self, generator):
+ """Non-entity query falls back to parent class."""
+ # Queries without entity keywords should call super().generate_questions()
+ # This will use the parent's implementation
+ with patch.object(
+ EntityAwareQuestionGenerator.__bases__[0],
+ "generate_questions",
+ return_value=["parent q1", "parent q2"],
+ ) as mock_parent:
+ generator.generate_questions("", "How to learn programming?", 2)
+ # Should have called parent class method
+ mock_parent.assert_called_once()
+
+ def test_technical_query_uses_parent(self, generator):
+ """Technical queries use parent class."""
+ with patch.object(
+ EntityAwareQuestionGenerator.__bases__[0],
+ "generate_questions",
+ return_value=["q1", "q2"],
+ ):
+ generator.generate_questions(
+ "", "Explain machine learning algorithms", 2
+ )
+
+
+class TestEntityFocusedPromptGeneration:
+ """Tests for entity-focused prompt generation."""
+
+ @pytest.fixture
+ def mock_model(self):
+ """Create mock model."""
+ mock = Mock()
+ mock.invoke.return_value = Mock(content="Q: query1\nQ: query2")
+ return mock
+
+ @pytest.fixture
+ def generator(self, mock_model):
+ """Create generator instance."""
+ return EntityAwareQuestionGenerator(mock_model)
+
+ def test_prompt_includes_query(self, generator):
+ """Prompt includes the original query."""
+ generator.generate_questions("", "Who is the main character?", 2)
+ call_args = generator.model.invoke.call_args[0][0]
+ assert "Who is the main character?" in call_args
+
+ def test_prompt_includes_current_date(self, generator):
+ """Prompt includes current date."""
+ generator.generate_questions("", "Who is the president?", 2)
+ call_args = generator.model.invoke.call_args[0][0]
+ # Should contain date in YYYY-MM-DD format
+ today = datetime.now(UTC).strftime("%Y-%m-%d")
+ assert today in call_args
+
+ def test_prompt_with_past_questions(self, generator):
+ """Prompt includes past questions when provided."""
+ past = {1: ["Q1", "Q2"], 2: ["Q3"]}
+ generator.generate_questions("", "Who is the character?", 2, past)
+ call_args = generator.model.invoke.call_args[0][0]
+ assert "Past questions:" in call_args
+
+ def test_prompt_without_past_questions(self, generator):
+ """Prompt format changes when no past questions."""
+ generator.generate_questions("", "Who is the inventor?", 2, None)
+ call_args = generator.model.invoke.call_args[0][0]
+ # Without past questions, uses simpler format
+ assert "Past questions:" not in call_args
+
+ def test_prompt_includes_current_knowledge(self, generator):
+ """Prompt includes current knowledge when with past questions."""
+ past = {1: ["Q1"]}
+ knowledge = "Some gathered knowledge"
+ generator.generate_questions(
+ knowledge, "Who is the scientist?", 2, past
+ )
+ call_args = generator.model.invoke.call_args[0][0]
+ assert "Some gathered knowledge" in call_args
+
+ def test_questions_per_iteration_in_prompt(self, generator):
+ """Prompt requests specific number of questions."""
+ generator.generate_questions("", "Who invented it?", 3)
+ call_args = generator.model.invoke.call_args[0][0]
+ assert "3" in call_args
+
+
+class TestResponseParsing:
+ """Tests for parsing LLM responses."""
+
+ @pytest.fixture
+ def generator(self):
+ """Create generator with mock model."""
+ mock_model = Mock()
+ return EntityAwareQuestionGenerator(mock_model)
+
+ def test_parse_q_prefixed_lines(self, generator):
+ """Parse lines starting with 'Q:'."""
+ generator.model.invoke.return_value = Mock(
+ content="Q: First query here\nQ: Second query here\nQ: Third query"
+ )
+ result = generator.generate_questions("", "Who is it?", 3)
+ assert len(result) == 3
+ assert "First query here" in result[0]
+ assert "Second query here" in result[1]
+ assert "Third query" in result[2]
+
+ def test_respect_questions_per_iteration(self, generator):
+ """Limit results to questions_per_iteration."""
+ generator.model.invoke.return_value = Mock(
+ content="Q: q1\nQ: q2\nQ: q3\nQ: q4\nQ: q5"
+ )
+ result = generator.generate_questions("", "Who is it?", 2)
+ assert len(result) == 2
+
+ def test_skip_non_q_lines(self, generator):
+ """Skip lines not starting with 'Q:'."""
+ generator.model.invoke.return_value = Mock(
+ content="Introduction text\nQ: First query\nMore text\nQ: Second query"
+ )
+ result = generator.generate_questions("", "Who is it?", 5)
+ assert len(result) == 2
+
+ def test_handle_content_attribute(self, generator):
+ """Handle response with .content attribute."""
+ mock_response = Mock()
+ mock_response.content = "Q: query1\nQ: query2"
+ generator.model.invoke.return_value = mock_response
+ result = generator.generate_questions("", "Who is it?", 2)
+ assert len(result) == 2
+
+ def test_handle_string_response(self, generator):
+ """Handle plain string response."""
+ generator.model.invoke.return_value = "Q: query1\nQ: query2"
+ result = generator.generate_questions("", "Who is it?", 2)
+ assert len(result) == 2
+
+ def test_strip_q_prefix(self, generator):
+ """Strip 'Q:' prefix from results."""
+ generator.model.invoke.return_value = Mock(
+ content="Q: simple query here"
+ )
+ result = generator.generate_questions("", "Who is it?", 1)
+ assert result[0] == "simple query here"
+
+ def test_strip_whitespace(self, generator):
+ """Strip whitespace from parsed queries."""
+ generator.model.invoke.return_value = Mock(
+ content="Q: query with spaces \nQ: another query "
+ )
+ result = generator.generate_questions("", "Who is it?", 2)
+ assert result[0] == "query with spaces"
+ assert result[1] == "another query"
+
+
+class TestGenerateSubQuestions:
+ """Tests for generate_sub_questions method."""
+
+ @pytest.fixture
+ def generator(self):
+ """Create generator with mock model."""
+ mock_model = Mock()
+ return EntityAwareQuestionGenerator(mock_model)
+
+ def test_entity_query_sub_questions(self, generator):
+ """Generate sub-questions for entity queries."""
+ generator.model.invoke.return_value = Mock(
+ content="1. First sub-question\n2. Second sub-question\n3. Third sub-question"
+ )
+ result = generator.generate_sub_questions("Who invented the telephone?")
+ assert len(result) == 3
+
+ def test_parse_numbered_format(self, generator):
+ """Parse numbered list format."""
+ generator.model.invoke.return_value = Mock(
+ content="1. Question one here\n2. Question two here"
+ )
+ result = generator.generate_sub_questions("Which movie is this?")
+ assert "Question one here" in result[0]
+ assert "Question two here" in result[1]
+
+ def test_parse_bulleted_format(self, generator):
+ """Parse bulleted list format."""
+ generator.model.invoke.return_value = Mock(
+ content="- First question\n- Second question"
+ )
+ result = generator.generate_sub_questions("Who wrote this book?")
+ assert len(result) == 2
+
+ def test_context_included_in_prompt(self, generator):
+ """Context is included in prompt."""
+ generator.model.invoke.return_value = Mock(content="1. Q1\n2. Q2")
+ generator.generate_sub_questions(
+ "Who is the character?",
+ context="Previous findings about the character",
+ )
+ call_args = generator.model.invoke.call_args[0][0]
+ assert "Previous findings about the character" in call_args
+
+ def test_non_entity_raises_or_returns_empty(self, generator):
+ """Non-entity query attempts parent call (may fail without implementation)."""
+ # The base class doesn't have generate_sub_questions, so this tests
+ # that the code path is attempted for non-entity queries
+ try:
+ result = generator.generate_sub_questions(
+ "How does machine learning work?"
+ )
+ # If it doesn't raise, should return empty or valid list
+ assert isinstance(result, list)
+ except AttributeError:
+ # Expected if parent class doesn't implement generate_sub_questions
+ pass
+
+ def test_handle_content_attribute(self, generator):
+ """Handle response with .content attribute."""
+ mock_response = Mock()
+ mock_response.content = "1. Sub Q1\n2. Sub Q2"
+ generator.model.invoke.return_value = mock_response
+ result = generator.generate_sub_questions("Who is the scientist?")
+ assert len(result) == 2
+
+ def test_handle_string_response(self, generator):
+ """Handle plain string response."""
+ generator.model.invoke.return_value = "1. Sub Q1\n2. Sub Q2"
+ result = generator.generate_sub_questions("Who is the author?")
+ assert len(result) == 2
+
+
+class TestErrorHandling:
+ """Tests for error handling."""
+
+ @pytest.fixture
+ def generator(self):
+ """Create generator with mock model."""
+ mock_model = Mock()
+ return EntityAwareQuestionGenerator(mock_model)
+
+ def test_sub_questions_exception_returns_empty(self, generator):
+ """Exception in generate_sub_questions returns empty list."""
+ generator.model.invoke.side_effect = RuntimeError("Connection failed")
+ result = generator.generate_sub_questions("Who is the inventor?")
+ assert result == []
+
+ def test_sub_questions_logs_exception(self, generator, caplog):
+ """Exception is logged in generate_sub_questions."""
+ generator.model.invoke.side_effect = ValueError("Invalid input")
+ result = generator.generate_sub_questions("Who is the character?")
+ # Exception should be logged
+ assert result == []
+
+
+class TestEdgeCases:
+ """Tests for edge cases."""
+
+ @pytest.fixture
+ def generator(self):
+ """Create generator with mock model."""
+ mock_model = Mock()
+ mock_model.invoke.return_value = Mock(content="Q: query")
+ return EntityAwareQuestionGenerator(mock_model)
+
+ def test_empty_response(self, generator):
+ """Handle empty LLM response."""
+ generator.model.invoke.return_value = Mock(content="")
+ result = generator.generate_questions("", "Who is it?", 2)
+ assert result == []
+
+ def test_no_valid_q_lines(self, generator):
+ """Handle response with no valid Q: lines."""
+ generator.model.invoke.return_value = Mock(
+ content="Some text\nMore text\nNo Q lines"
+ )
+ result = generator.generate_questions("", "Who is it?", 2)
+ assert result == []
+
+ def test_empty_query(self, generator):
+ """Handle empty query string."""
+ generator.generate_questions("", "", 2)
+ # Empty query has no entity keywords, should fall back to parent
+ # Just verify it doesn't crash
+
+ def test_questions_by_iteration_none(self, generator):
+ """Handle questions_by_iteration as None."""
+ result = generator.generate_questions("", "Who is it?", 2, None)
+ assert isinstance(result, list)
+
+ def test_questions_by_iteration_empty(self, generator):
+ """Handle questions_by_iteration as empty dict."""
+ result = generator.generate_questions("", "Who is it?", 2, {})
+ assert isinstance(result, list)
+ # Empty dict is falsy, so uses simpler prompt format
+
+ def test_sub_questions_empty_content(self, generator):
+ """Handle empty content in sub-questions."""
+ generator.model.invoke.return_value = Mock(content="")
+ result = generator.generate_sub_questions("Who is the inventor?")
+ assert result == []
+
+ def test_sub_questions_no_numbered_lines(self, generator):
+ """Handle response with no numbered lines."""
+ generator.model.invoke.return_value = Mock(
+ content="Some text without numbers"
+ )
+ result = generator.generate_sub_questions("Who is the character?")
+ assert result == []
+
+
+class TestIntegration:
+ """Integration tests."""
+
+ @pytest.fixture
+ def mock_model(self):
+ """Create mock model with realistic responses."""
+ mock = Mock()
+ mock.invoke.return_value = Mock(
+ content="""Q: "fictional character" "fourth wall" TV show
+Q: character name sitcom breaks fourth wall
+Q: TV character speaks to audience directly"""
+ )
+ return mock
+
+ @pytest.fixture
+ def generator(self, mock_model):
+ """Create generator instance."""
+ return EntityAwareQuestionGenerator(mock_model)
+
+ def test_full_workflow_entity_query(self, generator):
+ """Test complete workflow with entity query."""
+ result = generator.generate_questions(
+ "Some knowledge about characters",
+ "What fictional character breaks the fourth wall?",
+ 3,
+ {1: ["Previous question"]},
+ )
+ assert isinstance(result, list)
+ assert len(result) == 3
+ assert all(isinstance(q, str) for q in result)
+
+ def test_full_workflow_sub_questions(self, generator):
+ """Test complete workflow for sub-questions."""
+ generator.model.invoke.return_value = Mock(
+ content="1. Who created this character?\n2. What show features this character?\n3. When did the show air?"
+ )
+ result = generator.generate_sub_questions(
+ "Which character breaks the fourth wall?",
+ context="Looking for a TV character",
+ )
+ assert isinstance(result, list)
+ assert len(result) == 3