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.

test: add 196 pure-logic tests for advanced search strategies (#2703)

LearningCircuit40a6ec5315ba
diff --git a/tests/advanced_search_system/search_optimization/test_cross_constraint_pure_logic.py b/tests/advanced_search_system/search_optimization/test_cross_constraint_pure_logic.py
new file mode 100644
index 0000000000..cc9e70cb63
--- /dev/null
+++ b/tests/advanced_search_system/search_optimization/test_cross_constraint_pure_logic.py
@@ -0,0 +1,196 @@
+"""
+Pure-logic tests for CrossConstraintManager.
+
+Tests cluster coherence calculation, cluster deduplication, and
+search order optimization — no LLM or search calls.
+"""
+
+from unittest.mock import Mock
+
+from local_deep_research.advanced_search_system.constraints.base_constraint import (
+ Constraint,
+ ConstraintType,
+)
+from local_deep_research.advanced_search_system.search_optimization.cross_constraint_manager import (
+ ConstraintCluster,
+ ConstraintRelationship,
+ CrossConstraintManager,
+)
+
+
+def _constraint(id, ctype=ConstraintType.PROPERTY, value="v"):
+ return Constraint(id=id, type=ctype, description="", value=value)
+
+
+def _cluster(constraint_ids, coherence=0.5, cluster_type="descriptive"):
+ """Build a ConstraintCluster from a list of IDs."""
+ constraints = [_constraint(cid) for cid in constraint_ids]
+ return ConstraintCluster(
+ constraints=constraints,
+ cluster_type=cluster_type,
+ coherence_score=coherence,
+ )
+
+
+def _make_manager(relationships=None):
+ """Build a minimal Mock with the attributes used by pure-logic methods."""
+ m = Mock(spec=[])
+ m.relationships = relationships or {}
+ return m
+
+
+# ---------------------------------------------------------------------------
+# _calculate_cluster_coherence
+# ---------------------------------------------------------------------------
+
+
+class TestCalculateClusterCoherence:
+ """Verify pairwise-average coherence with size factor."""
+
+ def test_single_constraint(self):
+ """< 2 constraints -> 0.0."""
+ m = _make_manager()
+ c = [_constraint("c1")]
+ result = CrossConstraintManager._calculate_cluster_coherence(m, c)
+ assert result == 0.0
+
+ def test_no_relationships(self):
+ """Two constraints with no relationship -> default 0.5."""
+ m = _make_manager()
+ c = [_constraint("c1"), _constraint("c2")]
+ result = CrossConstraintManager._calculate_cluster_coherence(m, c)
+ assert result == 0.5
+
+ def test_single_relationship(self):
+ """Two constraints with one relationship."""
+ rel = ConstraintRelationship(
+ constraint1_id="c1",
+ constraint2_id="c2",
+ relationship_type="complementary",
+ strength=0.8,
+ )
+ m = _make_manager(relationships={("c1", "c2"): rel})
+ c = [_constraint("c1"), _constraint("c2")]
+ result = CrossConstraintManager._calculate_cluster_coherence(m, c)
+ # avg_strength = 0.8, size_factor = min(2/5, 1.0) = 0.4
+ # coherence = 0.8 * (0.7 + 0.3 * 0.4) = 0.8 * 0.82 = 0.656
+ assert abs(result - 0.656) < 1e-9
+
+ def test_size_factor_capped(self):
+ """Size factor capped at 1.0 for clusters >= 5."""
+ rels = {}
+ for i in range(5):
+ for j in range(i + 1, 5):
+ rels[(f"c{i}", f"c{j}")] = ConstraintRelationship(
+ constraint1_id=f"c{i}",
+ constraint2_id=f"c{j}",
+ relationship_type="complementary",
+ strength=1.0,
+ )
+ m = _make_manager(relationships=rels)
+ c = [_constraint(f"c{i}") for i in range(5)]
+ result = CrossConstraintManager._calculate_cluster_coherence(m, c)
+ # avg_strength = 1.0, size_factor = 1.0
+ # coherence = 1.0 * (0.7 + 0.3 * 1.0) = 1.0
+ assert abs(result - 1.0) < 1e-9
+
+ def test_partial_relationships(self):
+ """Only some pairs have relationships."""
+ rels = {
+ ("c1", "c2"): ConstraintRelationship(
+ constraint1_id="c1",
+ constraint2_id="c2",
+ relationship_type="complementary",
+ strength=0.6,
+ ),
+ }
+ m = _make_manager(relationships=rels)
+ # 3 constraints: pairs (c1,c2), (c1,c3), (c2,c3) — only 1 has relationship
+ c = [_constraint("c1"), _constraint("c2"), _constraint("c3")]
+ result = CrossConstraintManager._calculate_cluster_coherence(m, c)
+ # pair_count=1, avg_strength=0.6, size_factor=min(3/5,1)=0.6
+ # coherence = 0.6 * (0.7 + 0.3*0.6) = 0.6 * 0.88 = 0.528
+ assert abs(result - 0.528) < 1e-9
+
+
+# ---------------------------------------------------------------------------
+# _deduplicate_clusters
+# ---------------------------------------------------------------------------
+
+
+class TestDeduplicateClusters:
+ """Verify set-equality based cluster deduplication."""
+
+ def test_no_duplicates(self):
+ """Distinct clusters are all kept."""
+ clusters = [_cluster(["c1", "c2"]), _cluster(["c3", "c4"])]
+ result = CrossConstraintManager._deduplicate_clusters(Mock(), clusters)
+ assert len(result) == 2
+
+ def test_removes_exact_duplicates(self):
+ """Clusters with the same constraint IDs are deduplicated."""
+ clusters = [_cluster(["c1", "c2"]), _cluster(["c1", "c2"])]
+ result = CrossConstraintManager._deduplicate_clusters(Mock(), clusters)
+ assert len(result) == 1
+
+ def test_order_independent(self):
+ """Constraint order doesn't matter for dedup (set comparison)."""
+ clusters = [_cluster(["c1", "c2"]), _cluster(["c2", "c1"])]
+ result = CrossConstraintManager._deduplicate_clusters(Mock(), clusters)
+ assert len(result) == 1
+
+ def test_preserves_first(self):
+ """First occurrence is kept."""
+ c1 = _cluster(["c1", "c2"], coherence=0.9)
+ c2 = _cluster(["c1", "c2"], coherence=0.1)
+ result = CrossConstraintManager._deduplicate_clusters(Mock(), [c1, c2])
+ assert result[0].coherence_score == 0.9
+
+ def test_empty_input(self):
+ """Empty list returns empty."""
+ result = CrossConstraintManager._deduplicate_clusters(Mock(), [])
+ assert result == []
+
+ def test_subsets_not_duplicates(self):
+ """A subset is not a duplicate of a larger cluster."""
+ clusters = [_cluster(["c1", "c2", "c3"]), _cluster(["c1", "c2"])]
+ result = CrossConstraintManager._deduplicate_clusters(Mock(), clusters)
+ assert len(result) == 2
+
+
+# ---------------------------------------------------------------------------
+# optimize_search_order
+# ---------------------------------------------------------------------------
+
+
+class TestOptimizeSearchOrder:
+ """Verify sorting by coherence * constraint count, descending."""
+
+ def test_sorts_by_product(self):
+ """Higher coherence * size comes first."""
+ c1 = _cluster(["a", "b"], coherence=0.5) # 0.5 * 2 = 1.0
+ c2 = _cluster(["a", "b", "c"], coherence=0.8) # 0.8 * 3 = 2.4
+ c3 = _cluster(["a"], coherence=1.0) # 1.0 * 1 = 1.0
+ result = CrossConstraintManager.optimize_search_order(
+ Mock(), [c1, c2, c3]
+ )
+ assert result[0] is c2
+
+ def test_empty_input(self):
+ """Empty list returns empty."""
+ result = CrossConstraintManager.optimize_search_order(Mock(), [])
+ assert result == []
+
+ def test_single_cluster(self):
+ """Single cluster returned as-is."""
+ c = _cluster(["a", "b"], coherence=0.5)
+ result = CrossConstraintManager.optimize_search_order(Mock(), [c])
+ assert result == [c]
+
+ def test_tiebreaker(self):
+ """Equal products maintain stable order."""
+ c1 = _cluster(["a", "b"], coherence=0.5) # 1.0
+ c2 = _cluster(["a"], coherence=1.0) # 1.0
+ result = CrossConstraintManager.optimize_search_order(Mock(), [c1, c2])
+ # Both have product 1.0 — stable sort preserves input order
+ assert len(result) == 2
diff --git a/tests/advanced_search_system/strategies/test_adaptive_decomp_pure_logic.py b/tests/advanced_search_system/strategies/test_adaptive_decomp_pure_logic.py
new file mode 100644
index 0000000000..287afc160b
--- /dev/null
+++ b/tests/advanced_search_system/strategies/test_adaptive_decomp_pure_logic.py
@@ -0,0 +1,83 @@
+"""
+Pure-logic tests for AdaptiveDecompositionStrategy._calculate_confidence.
+
+Tests the confidence ratio calculation with candidate boost and cap,
+requiring no LLM or search calls.
+"""
+
+from unittest.mock import Mock
+
+from local_deep_research.advanced_search_system.strategies.adaptive_decomposition_strategy import (
+ AdaptiveDecompositionStrategy,
+)
+
+
+def _make_strategy(constraints=None, verified_facts=None, candidates=None):
+ """Build a minimal Mock with the working_knowledge dict."""
+ s = Mock(spec=[])
+ s.working_knowledge = {
+ "constraints": constraints or [],
+ "verified_facts": verified_facts or [],
+ "candidates": candidates or [],
+ }
+ return s
+
+
+class TestCalculateConfidence:
+ """Verify confidence calculation: verified/total ratio + candidate boost, capped at 0.95."""
+
+ def test_no_constraints(self):
+ """No constraints -> 0.0."""
+ s = _make_strategy(constraints=[], verified_facts=["a"])
+ result = AdaptiveDecompositionStrategy._calculate_confidence(s)
+ assert result == 0.0
+
+ def test_half_verified(self):
+ """2 verified out of 4 constraints -> 0.5."""
+ s = _make_strategy(
+ constraints=["c1", "c2", "c3", "c4"],
+ verified_facts=["f1", "f2"],
+ )
+ result = AdaptiveDecompositionStrategy._calculate_confidence(s)
+ assert result == 0.5
+
+ def test_candidate_boost(self):
+ """Having candidates adds 0.1 boost."""
+ s = _make_strategy(
+ constraints=["c1", "c2", "c3", "c4"],
+ verified_facts=["f1", "f2"],
+ candidates=["cand1"],
+ )
+ result = AdaptiveDecompositionStrategy._calculate_confidence(s)
+ assert abs(result - 0.6) < 1e-9
+
+ def test_cap_at_095(self):
+ """Confidence should never exceed 0.95."""
+ s = _make_strategy(
+ constraints=["c1"],
+ verified_facts=["f1"],
+ candidates=["cand1"],
+ )
+ # 1/1 + 0.1 = 1.1, but capped at 0.95
+ result = AdaptiveDecompositionStrategy._calculate_confidence(s)
+ assert result == 0.95
+
+ def test_all_verified_no_candidates(self):
+ """All verified, no candidates -> base ratio (capped at 0.95)."""
+ s = _make_strategy(
+ constraints=["c1", "c2"],
+ verified_facts=["f1", "f2"],
+ )
+ result = AdaptiveDecompositionStrategy._calculate_confidence(s)
+ assert result == 0.95
+
+ def test_none_verified(self):
+ """No verified facts -> 0.0 (no candidate boost since 0+0.1 stays)."""
+ s = _make_strategy(
+ constraints=["c1", "c2"],
+ verified_facts=[],
+ candidates=["cand1"],
+ )
+ # 0/2 + 0.1 = 0.1
+ result = AdaptiveDecompositionStrategy._calculate_confidence(s)
+ assert abs(result - 0.1) < 1e-9
diff --git a/tests/advanced_search_system/strategies/test_browsecomp_entity_pure_logic.py b/tests/advanced_search_system/strategies/test_browsecomp_entity_pure_logic.py
new file mode 100644
index 0000000000..751f08f369
--- /dev/null
+++ b/tests/advanced_search_system/strategies/test_browsecomp_entity_pure_logic.py
@@ -0,0 +1,453 @@
+"""
+Pure-logic tests for BrowseCompEntityStrategy and EntityKnowledgeGraph.
+
+Tests entity graph operations, entity type identification, specificity
+scoring, constraint term extraction, entity candidate extraction, entity
+search generation, and knowledge summarization — no LLM or search calls.
+"""
+
+from unittest.mock import Mock
+
+from local_deep_research.advanced_search_system.constraints.base_constraint import (
+ Constraint,
+ ConstraintType,
+)
+from local_deep_research.advanced_search_system.strategies.browsecomp_entity_strategy import (
+ BrowseCompEntityStrategy,
+ EntityCandidate,
+ EntityKnowledgeGraph,
+)
+
+
+def _entity(name, entity_type="company", **kwargs):
+ """Build an EntityCandidate with sensible defaults."""
+ return EntityCandidate(
+ name=name,
+ entity_type=entity_type,
+ aliases=kwargs.get("aliases", []),
+ properties=kwargs.get("properties", {}),
+ sources=kwargs.get("sources", []),
+ confidence=kwargs.get("confidence", 0.0),
+ constraint_matches=kwargs.get("constraint_matches", {}),
+ )
+
+
+def _constraint(id, ctype=ConstraintType.PROPERTY, value="v"):
+ return Constraint(id=id, type=ctype, description="", value=value)
+
+
+def _make_strategy():
+ """Build a minimal Mock with entity_patterns matching the real init."""
+ s = Mock(spec=[])
+ s.entity_patterns = {
+ "company": [
+ "company",
+ "corporation",
+ "group",
+ "firm",
+ "business",
+ "conglomerate",
+ ],
+ "person": ["person", "individual", "character", "figure", "people"],
+ "event": [
+ "event",
+ "incident",
+ "occurrence",
+ "game",
+ "match",
+ "competition",
+ ],
+ "location": [
+ "place",
+ "location",
+ "city",
+ "country",
+ "region",
+ "area",
+ ],
+ "product": ["product", "item", "device", "software", "app", "tool"],
+ }
+ s.knowledge_graph = EntityKnowledgeGraph()
+ return s
+
+
+# ---------------------------------------------------------------------------
+# EntityKnowledgeGraph.add_entity
+# ---------------------------------------------------------------------------
+
+
+class TestEntityKnowledgeGraphAddEntity:
+ """Verify merge-on-add and fresh-insert logic."""
+
+ def test_add_new_entity(self):
+ """New entity is stored by name."""
+ g = EntityKnowledgeGraph()
+ e = _entity("Acme Corp")
+ g.add_entity(e)
+ assert "Acme Corp" in g.entities
+
+ def test_merge_aliases(self):
+ """Repeated add merges and deduplicates aliases."""
+ g = EntityKnowledgeGraph()
+ g.add_entity(_entity("X", aliases=["a", "b"]))
+ g.add_entity(_entity("X", aliases=["b", "c"]))
+ assert set(g.entities["X"].aliases) == {"a", "b", "c"}
+
+ def test_merge_properties(self):
+ """Properties dict is updated on merge."""
+ g = EntityKnowledgeGraph()
+ g.add_entity(_entity("X", properties={"k1": "v1"}))
+ g.add_entity(_entity("X", properties={"k2": "v2"}))
+ assert g.entities["X"].properties == {"k1": "v1", "k2": "v2"}
+
+ def test_merge_sources(self):
+ """Sources are merged and deduplicated."""
+ g = EntityKnowledgeGraph()
+ g.add_entity(_entity("X", sources=["s1", "s2"]))
+ g.add_entity(_entity("X", sources=["s2", "s3"]))
+ assert set(g.entities["X"].sources) == {"s1", "s2", "s3"}
+
+ def test_merge_constraint_matches(self):
+ """Constraint matches are updated on merge."""
+ g = EntityKnowledgeGraph()
+ g.add_entity(_entity("X", constraint_matches={"c1": 0.5}))
+ g.add_entity(_entity("X", constraint_matches={"c2": 0.9}))
+ assert g.entities["X"].constraint_matches == {"c1": 0.5, "c2": 0.9}
+
+
+# ---------------------------------------------------------------------------
+# EntityKnowledgeGraph.get_entities_by_constraint
+# ---------------------------------------------------------------------------
+
+
+class TestGetEntitiesByConstraint:
+ """Verify threshold filtering and confidence-descending sort."""
+
+ def test_filters_below_threshold(self):
+ """Entities below min_confidence are excluded."""
+ g = EntityKnowledgeGraph()
+ g.add_entity(_entity("A", constraint_matches={"c1": 0.3}))
+ g.add_entity(_entity("B", constraint_matches={"c1": 0.7}))
+ result = g.get_entities_by_constraint("c1", min_confidence=0.5)
+ assert [e.name for e in result] == ["B"]
+
+ def test_sorted_descending(self):
+ """Results are sorted by confidence descending."""
+ g = EntityKnowledgeGraph()
+ g.add_entity(_entity("A", constraint_matches={"c1": 0.6}))
+ g.add_entity(_entity("B", constraint_matches={"c1": 0.9}))
+ g.add_entity(_entity("C", constraint_matches={"c1": 0.75}))
+ result = g.get_entities_by_constraint("c1", min_confidence=0.5)
+ assert [e.name for e in result] == ["B", "C", "A"]
+
+ def test_no_matching_constraint(self):
+ """Entities without the constraint are excluded."""
+ g = EntityKnowledgeGraph()
+ g.add_entity(_entity("A", constraint_matches={"c2": 0.9}))
+ assert g.get_entities_by_constraint("c1") == []
+
+ def test_empty_graph(self):
+ """Empty graph returns empty list."""
+ g = EntityKnowledgeGraph()
+ assert g.get_entities_by_constraint("c1") == []
+
+
+# ---------------------------------------------------------------------------
+# _identify_entity_type
+# ---------------------------------------------------------------------------
+
+
+class TestIdentifyEntityType:
+ """Verify keyword-based entity type identification."""
+
+ def _call(self, query):
+ s = _make_strategy()
+ return BrowseCompEntityStrategy._identify_entity_type(s, query)
+
+ def test_company_keyword(self):
+ """'corporation' -> 'company'."""
+ assert self._call("Which corporation was founded in 1990?") == "company"
+
+ def test_person_keyword(self):
+ """'individual' -> 'person'."""
+ assert self._call("Which individual won the award?") == "person"
+
+ def test_event_keyword(self):
+ """'competition' -> 'event'."""
+ assert self._call("What competition took place in 2020?") == "event"
+
+ def test_location_keyword(self):
+ """'city' -> 'location'."""
+ assert self._call("What city is known for X?") == "location"
+
+ def test_product_keyword(self):
+ """'software' -> 'product'."""
+ assert self._call("Which software was released?") == "product"
+
+ def test_who_fallback(self):
+ """'who' without other keywords -> 'person'."""
+ assert self._call("Who did this?") == "person"
+
+ def test_which_fallback(self):
+ """'which' without other keywords -> 'product'."""
+ assert self._call("Which one is best?") == "product"
+
+ def test_what_company_fallback(self):
+ """'what' + 'company' -> 'company'."""
+ assert self._call("What company does this?") == "company"
+
+ def test_generic_fallback(self):
+ """No keywords at all -> 'entity'."""
+ assert self._call("Tell me about the answer") == "entity"
+
+
+# ---------------------------------------------------------------------------
+# entity_specificity
+# ---------------------------------------------------------------------------
+
+
+class TestEntitySpecificity:
+ """Verify multi-factor specificity scoring."""
+
+ def _call(self, entity):
+ return BrowseCompEntityStrategy.entity_specificity(Mock(), entity)
+
+ def test_single_short_word(self):
+ """Short single word: length * 0.1 + 1 word * 2.0."""
+ score = self._call("Abc")
+ assert abs(score - (3 * 0.1 + 1 * 2.0)) < 1e-9
+
+ def test_company_suffix_bonus(self):
+ """Company suffix adds 10.0."""
+ score = self._call("Acme Corp")
+ assert score >= 10.0
+
+ def test_hyphen_bonus(self):
+ """Hyphenated entity gets +5.0."""
+ base = self._call("PRAN")
+ with_hyphen = self._call("PRAN-RFL")
+ # Hyphen adds 5.0 (and possibly more from length/words)
+ assert with_hyphen > base + 4.0
+
+ def test_all_uppercase_bonus(self):
+ """All-uppercase entity >= 3 chars gets +8.0."""
+ score = self._call("IBM")
+ # 3 * 0.1 + 1 * 2.0 + 8.0 = 10.3
+ assert abs(score - 10.3) < 1e-9
+
+ def test_multi_word_higher(self):
+ """More words -> higher score due to word_count * 2.0."""
+ one_word = self._call("Apple")
+ two_words = self._call("Apple Inc")
+ assert two_words > one_word
+
+
+# ---------------------------------------------------------------------------
+# _extract_constraint_terms
+# ---------------------------------------------------------------------------
+
+
+class TestExtractConstraintTerms:
+ """Verify prefix stripping, regex extraction, and word filtering."""
+
+ def _call(self, value, ctype=ConstraintType.PROPERTY):
+ c = _constraint("c1", ctype, value)
+ # Use real ConstraintType enum values (lowercase)
+ # The method checks constraint.type.value against uppercase strings
+ return BrowseCompEntityStrategy._extract_constraint_terms(Mock(), c)
+
+ def test_long_words_extracted(self):
+ """Words > 4 chars (not stopwords) are extracted."""
+ result = self._call("something really interesting")
+ assert "something" in result
+ assert "really" in result
+ assert "interesting" in result
+
+ def test_capped_at_five(self):
+ """No more than 5 terms returned."""
+ result = self._call("alpha bravo charlie delta echo foxtrot")
+ assert len(result) <= 5
+
+ def test_prefix_stripped(self):
+ """'Must be' prefix is removed before extraction."""
+ result = self._call("Must be a large entity")
+ # "Must" and "be" are stripped; remaining words > 4 chars kept
+ assert "large" in result
+ assert "entity" in result
+
+ def test_short_words_excluded(self):
+ """Words <= 4 chars are not included as general terms."""
+ result = self._call("a big cat")
+ # None of these words > 4 chars
+ assert all(len(t) > 4 or t.isdigit() for t in result) or result == []
+
+ def test_stopword_excluded(self):
+ """Modal verbs in the stopword list are excluded."""
+ result = self._call("should would could must")
+ # All 4-5 char words that are in the exclusion list
+ assert "should" not in result
+ assert "would" not in result
+ assert "could" not in result
+
+
+# ---------------------------------------------------------------------------
+# extract_entity_candidates
+# ---------------------------------------------------------------------------
+
+
+class TestExtractEntityCandidates:
+ """Verify regex-based candidate extraction and specificity sort."""
+
+ def _call(self, constraint_values):
+ s = _make_strategy()
+ # Bind the real entity_specificity method so sorted() can use it
+ s.entity_specificity = (
+ BrowseCompEntityStrategy.entity_specificity.__get__(s)
+ )
+ constraints = [
+ _constraint(f"c{i}", value=v)
+ for i, v in enumerate(constraint_values)
+ ]
+ return BrowseCompEntityStrategy.extract_entity_candidates(
+ s, constraints
+ )
+
+ def test_extracts_proper_nouns(self):
+ """Capitalized multi-word names are extracted."""
+ result = self._call(["John Smith is the founder"])
+ assert "John Smith" in result or "John" in result
+
+ def test_extracts_company_patterns(self):
+ """Company suffixes (Group, Inc, etc.) are captured."""
+ result = self._call(["Founded by Acme Corp in 2000"])
+ assert any("Acme" in r for r in result)
+
+ def test_extracts_acronyms(self):
+ """All-uppercase acronyms >= 2 chars are extracted."""
+ result = self._call(["The PRAN-RFL group"])
+ # Should find PRAN-RFL or PRAN or RFL
+ assert any("PRAN" in r or "RFL" in r for r in result)
+
+ def test_deduplicated(self):
+ """Duplicate names across constraints are removed."""
+ result = self._call(["John Smith", "John Smith again"])
+ john_count = sum(1 for r in result if r == "John Smith")
+ assert john_count <= 1
+
+ def test_sorted_by_specificity(self):
+ """Results are sorted by specificity score descending."""
+ s = _make_strategy()
+ s.entity_specificity = (
+ BrowseCompEntityStrategy.entity_specificity.__get__(s)
+ )
+ constraints = [_constraint("c1", value="IBM Corp or Apple")]
+ result = BrowseCompEntityStrategy.extract_entity_candidates(
+ s, constraints
+ )
+ if len(result) >= 2:
+ scores = [
+ BrowseCompEntityStrategy.entity_specificity(s, r)
+ for r in result
+ ]
+ assert scores == sorted(scores, reverse=True)
+
+
+# ---------------------------------------------------------------------------
+# _generate_entity_searches
+# ---------------------------------------------------------------------------
+
+
+class TestGenerateEntitySearches:
+ """Verify type-based search query generation with regex extraction."""
+
+ def _call(self, entity_type, constraints):
+ return BrowseCompEntityStrategy._generate_entity_searches(
+ Mock(), entity_type, constraints
+ )
+
+ def test_company_base_searches(self):
+ """Company type produces company-related base queries."""
+ result = self._call("company", [])
+ assert any("companies" in q or "corporation" in q for q in result)
+
+ def test_person_base_searches(self):
+ """Person type produces person-related base queries."""
+ result = self._call("person", [])
+ assert any("people" in q or "person" in q for q in result)
+
+ def test_event_base_searches(self):
+ """Event type produces event-related base queries."""
+ result = self._call("event", [])
+ assert any("events" in q or "event" in q for q in result)
+
+ def test_unknown_type_no_base(self):
+ """Unknown entity type produces no base searches."""
+ result = self._call("widget", [])
+ assert len(result) == 0
+
+ def test_constraint_type_branches_use_uppercase_comparison(self):
+ """Constraint type branches compare against uppercase strings but
+ ConstraintType enum values are lowercase, so these branches are
+ currently unreachable. Verify only base searches are generated."""
+ c = _constraint("c1", ConstraintType.STATISTIC, "has 42 employees")
+ result = self._call("company", [c])
+ # The "STATISTIC" uppercase comparison doesn't match "statistic",
+ # so no number-extraction queries are added — only the 3 base queries
+ assert len(result) == 3
+
+
+# ---------------------------------------------------------------------------
+# _summarize_knowledge
+# ---------------------------------------------------------------------------
+
+
+class TestSummarizeKnowledge:
+ """Verify knowledge summary formatting."""
+
+ def test_empty_graph(self):
+ """Empty graph -> empty summary."""
+ s = _make_strategy()
+ result = BrowseCompEntityStrategy._summarize_knowledge(s)
+ assert result == ""
+
+ def test_entities_listed(self):
+ """Entities are listed with confidence percentages."""
+ s = _make_strategy()
+ s.knowledge_graph.add_entity(
+ _entity("Acme", confidence=0.85, entity_type="company")
+ )
+ result = BrowseCompEntityStrategy._summarize_knowledge(s)
+ assert "Acme" in result
+ assert "85" in result # 0.85 formatted as 85.00%
+
+ def test_top_five_only(self):
+ """Only top 5 entities by confidence are shown."""
+ s = _make_strategy()
+ for i in range(8):
+ s.knowledge_graph.add_entity(
+ _entity(f"E{i}", confidence=i * 0.1, entity_type="company")
+ )
+ result = BrowseCompEntityStrategy._summarize_knowledge(s)
+ # Top 5 are E7, E6, E5, E4, E3
+ assert "E7" in result
+ assert "E0" not in result
+
+ def test_properties_shown(self):
+ """Entity properties are displayed."""
+ s = _make_strategy()
+ s.knowledge_graph.add_entity(
+ _entity("X", confidence=0.5, properties={"color": "blue"})
+ )
+ result = BrowseCompEntityStrategy._summarize_knowledge(s)
+ assert "color=blue" in result
+
+ def test_constraint_evidence_shown(self):
+ """Constraint evidence section is included when present."""
+ s = _make_strategy()
+ s.knowledge_graph.add_entity(_entity("X", confidence=0.5))
+ s.knowledge_graph.constraint_evidence["some constraint"] = {
+ "X": {"score": 0.75}
+ }
+ result = BrowseCompEntityStrategy._summarize_knowledge(s)
+ assert "Constraint verification" in result
+ assert "75" in result # 0.75 formatted as 75.00%
diff --git a/tests/advanced_search_system/strategies/test_constrained_search_pure_logic.py b/tests/advanced_search_system/strategies/test_constrained_search_pure_logic.py
new file mode 100644
index 0000000000..09c9b25538
--- /dev/null
+++ b/tests/advanced_search_system/strategies/test_constrained_search_pure_logic.py
@@ -0,0 +1,283 @@
+"""
+Pure-logic tests for ConstrainedSearchStrategy.
+
+Tests restrictiveness scoring, constraint ranking, candidate deduplication,
+and query generation — no LLM or search calls.
+"""
+
+from unittest.mock import Mock
+
+from local_deep_research.advanced_search_system.candidates.base_candidate import (
+ Candidate,
+)
+from local_deep_research.advanced_search_system.constraints.base_constraint import (
+ Constraint,
+ ConstraintType,
+)
+from local_deep_research.advanced_search_system.strategies.constrained_search_strategy import (
+ ConstrainedSearchStrategy,
+)
+
+
+def _constraint(id, ctype=ConstraintType.PROPERTY, value="v", weight=1.0):
+ return Constraint(
+ id=id, type=ctype, description=f"desc {id}", value=value, weight=weight
+ )
+
+
+def _make_strategy(constraints=None):
+ """Build a minimal Mock with the attributes read by pure-logic methods."""
+ s = Mock(spec=[])
+ s.constraints = constraints or []
+ return s
+
+
+# ---------------------------------------------------------------------------
+# _calculate_restrictiveness_score
+# ---------------------------------------------------------------------------
+
+
+class TestCalculateRestrictivenessScore:
+ """Verify type-based and value-based scoring components."""
+
+ def _score(self, ctype=ConstraintType.PROPERTY, value="v"):
+ c = _constraint("c1", ctype, value)
+ return ConstrainedSearchStrategy._calculate_restrictiveness_score(
+ Mock(), c
+ )
+
+ def test_statistic_highest_type_score(self):
+ """STATISTIC type gets 10 points."""
+ assert self._score(ConstraintType.STATISTIC) >= 10
+
+ def test_event_type_score(self):
+ """EVENT type gets 8 points."""
+ assert self._score(ConstraintType.EVENT, "something") == 8
+
+ def test_location_type_score(self):
+ """LOCATION type gets 6 points."""
+ assert self._score(ConstraintType.LOCATION, "something") == 6
+
+ def test_property_type_score(self):
+ """PROPERTY type gets 4 points."""
+ assert self._score(ConstraintType.PROPERTY, "something") == 4
+
+ def test_digits_bonus(self):
+ """Values containing digits get +5."""
+ base = self._score(ConstraintType.PROPERTY, "abc")
+ with_digit = self._score(ConstraintType.PROPERTY, "abc 42")
+ assert with_digit - base == 5
+
+ def test_long_value_bonus(self):
+ """Values with > 3 words get +3."""
+ short = self._score(ConstraintType.PROPERTY, "one two three")
+ long = self._score(ConstraintType.PROPERTY, "one two three four")
+ assert long - short == 3
+
+ def test_specificity_keywords_bonus(self):
+ """Values with 'specific', 'exact', 'only', or 'must' get +2."""
+ base = self._score(ConstraintType.PROPERTY, "something")
+ with_kw = self._score(ConstraintType.PROPERTY, "exact something")
+ assert with_kw - base == 2
+
+ def test_combined_bonuses(self):
+ """Digits + long value + keyword = +10 total bonus."""
+ # PROPERTY(4) + digits(5) + long(3) + keyword(2) = 14
+ score = self._score(
+ ConstraintType.PROPERTY,
+ "must have exactly 100 specific items",
+ )
+ assert score == 14
+
+ def test_empty_value(self):
+ """Empty string value adds no bonus (falsy guard)."""
+ score = self._score(ConstraintType.PROPERTY, "")
+ assert score == 4 # Type score only
+
+
+# ---------------------------------------------------------------------------
+# _rank_constraints_by_restrictiveness
+# ---------------------------------------------------------------------------
+
+
+class TestRankConstraintsByRestrictiveness:
+ """Verify that constraints are sorted most-restrictive-first."""
+
+ def test_type_ordering(self):
+ """STATISTIC > EVENT > LOCATION > PROPERTY."""
+ s = _make_strategy(
+ constraints=[
+ _constraint("prop", ConstraintType.PROPERTY, "alpha"),
+ _constraint("stat", ConstraintType.STATISTIC, "alpha"),
+ _constraint("evt", ConstraintType.EVENT, "alpha"),
+ _constraint("loc", ConstraintType.LOCATION, "alpha"),
+ ]
+ )
+ ranked = ConstrainedSearchStrategy._rank_constraints_by_restrictiveness(
+ s
+ )
+ ids = [c.id for c in ranked]
+ assert ids == ["stat", "evt", "loc", "prop"]
+
+ def test_bonus_can_reorder(self):
+ """A PROPERTY with many bonuses can outrank a plain EVENT."""
+ s = _make_strategy(
+ constraints=[
+ _constraint("evt", ConstraintType.EVENT, "plain"), # 8
+ _constraint(
+ "prop",
+ ConstraintType.PROPERTY,
+ "must have exact 500 specific items", # 4+5+3+2 = 14
+ ),
+ ]
+ )
+ ranked = ConstrainedSearchStrategy._rank_constraints_by_restrictiveness(
+ s
+ )
+ assert ranked[0].id == "prop"
+
+ def test_empty_constraints(self):
+ """Empty list returns empty."""
+ s = _make_strategy(constraints=[])
+ assert (
+ ConstrainedSearchStrategy._rank_constraints_by_restrictiveness(s)
+ == []
+ )
+
+
+# ---------------------------------------------------------------------------
+# _deduplicate_candidates
+# ---------------------------------------------------------------------------
+
+
+class TestDeduplicateCandidates:
+ """Verify case-insensitive, strip-based deduplication."""
+
+ def _dedup(self, names):
+ candidates = [Candidate(name=n) for n in names]
+ return ConstrainedSearchStrategy._deduplicate_candidates(
+ Mock(), candidates
+ )
+
+ def test_no_duplicates(self):
+ """Distinct names all kept."""
+ result = self._dedup(["Alice", "Bob"])
+ assert len(result) == 2
+
+ def test_case_insensitive(self):
+ """'alice' and 'Alice' are duplicates."""
+ result = self._dedup(["Alice", "alice"])
+ assert len(result) == 1
+
+ def test_strips_whitespace(self):
+ """Leading/trailing whitespace is ignored."""
+ result = self._dedup(["Alice", " Alice "])
+ assert len(result) == 1
+
+ def test_preserves_first(self):
+ """First occurrence is kept."""
+ result = self._dedup(["Alice", "ALICE"])
+ assert result[0].name == "Alice"
+
+ def test_empty_list(self):
+ """Empty input returns empty."""
+ assert self._dedup([]) == []
+
+
+# ---------------------------------------------------------------------------
+# _generate_additional_queries
+# ---------------------------------------------------------------------------
+
+
+class TestGenerateAdditionalQueries:
+ """Verify type-branched query template generation."""
+
+ def _call(self, ctype, value="test data"):
+ c = _constraint("c1", ctype, value)
+ return ConstrainedSearchStrategy._generate_additional_queries(Mock(), c)
+
+ def test_always_has_reference_queries(self):
+ """All types get reference/authoritative/official queries."""
+ result = self._call(ConstraintType.PROPERTY)
+ assert any("reference" in q for q in result)
+ assert any("authoritative" in q for q in result)
+ assert any("official" in q for q in result)
+
+ def test_statistic_gets_dataset_queries(self):
+ """STATISTIC type gets spreadsheet/dataset/statistical analysis."""
+ result = self._call(ConstraintType.STATISTIC)
+ assert any("spreadsheet" in q or "dataset" in q for q in result)
+
+ def test_property_gets_characterized_queries(self):
+ """PROPERTY type gets 'characterized by' etc."""
+ result = self._call(ConstraintType.PROPERTY)
+ assert any("characterized by" in q for q in result)
+
+ def test_other_gets_generic(self):
+ """Other types get exhaustive/thorough/detailed."""
+ result = self._call(ConstraintType.LOCATION)
+ assert any("exhaustive" in q or "thorough" in q for q in result)
+
+ def test_value_in_queries(self):
+ """All queries contain the constraint value."""
+ result = self._call(ConstraintType.PROPERTY, "blue eyes")
+ assert all("blue eyes" in q for q in result)
+
+
+# ---------------------------------------------------------------------------
+# _generate_constraint_specific_queries
+# ---------------------------------------------------------------------------
+
+
+class TestGenerateConstraintSpecificQueries:
+ """Verify type-specific query expansion with context from other constraints."""
+
+ def _call(self, ctype, value="test data", other_constraints=None):
+ c = _constraint("c1", ctype, value)
+ s = _make_strategy(constraints=[c] + (other_constraints or []))
+ return ConstrainedSearchStrategy._generate_constraint_specific_queries(
+ s, c
+ )
+
+ def test_statistic_queries(self):
+ """STATISTIC produces list/complete/database style queries."""
+ result = self._call(ConstraintType.STATISTIC)
+ assert any("database" in q for q in result)
+ assert any("statistics" in q for q in result)
+
+ def test_event_queries(self):
+ """EVENT produces during/timeline style queries."""
+ result = self._call(ConstraintType.EVENT)
+ assert any("timeline" in q for q in result)
+
+ def test_property_queries(self):
+ """PROPERTY produces with/having/characterized by style queries."""
+ result = self._call(ConstraintType.PROPERTY)
+ assert any("characterized by" in q for q in result)
+
+ def test_generic_queries(self):
+ """Other types get generic list/examples queries."""
+ result = self._call(ConstraintType.TEMPORAL)
+ assert any("list" in q for q in result)
+
+ def test_includes_description(self):
+ """Constraint description is included as a query."""
+ c = Constraint(
+ id="c1",
+ type=ConstraintType.PROPERTY,
+ description="has blue eyes",
+ value="blue eyes",
+ )
+ s = _make_strategy(constraints=[c])
+ result = (
+ ConstrainedSearchStrategy._generate_constraint_specific_queries(
+ s, c
+ )
+ )
+ assert "has blue eyes" in result
+
+ def test_context_from_other_constraints(self):
+ """Context from other constraints is appended in combined queries."""
+ other = _constraint("c2", ConstraintType.PROPERTY, "red hair")
+ result = self._call(ConstraintType.PROPERTY, "blue eyes", [other])
+ assert any("red hair" in q for q in result)
diff --git a/tests/advanced_search_system/strategies/test_evidence_based_pure_logic.py b/tests/advanced_search_system/strategies/test_evidence_based_pure_logic.py
new file mode 100644
index 0000000000..9a235c92dc
--- /dev/null
+++ b/tests/advanced_search_system/strategies/test_evidence_based_pure_logic.py
@@ -0,0 +1,210 @@
+"""
+Pure-logic tests for EvidenceBasedStrategy.
+
+Tests _has_sufficient_answer (threshold + critical constraint checks) and
+_get_distinctive_constraints (priority-indexed sort with naming guarantee)
+— no LLM or search calls.
+"""
+
+from unittest.mock import Mock
+
+from local_deep_research.advanced_search_system.candidates.base_candidate import (
+ Candidate,
+)
+from local_deep_research.advanced_search_system.constraints.base_constraint import (
+ Constraint,
+ ConstraintType,
+)
+from local_deep_research.advanced_search_system.evidence.base_evidence import (
+ Evidence,
+ EvidenceType,
+)
+from local_deep_research.advanced_search_system.strategies.evidence_based_strategy import (
+ EvidenceBasedStrategy,
+)
+
+
+def _constraint(id, ctype=ConstraintType.PROPERTY, weight=1.0, value="v"):
+ return Constraint(
+ id=id,
+ type=ctype,
+ description="",
+ value=value,
+ weight=weight,
+ )
+
+
+def _evidence(confidence=0.8):
+ return Evidence(
+ claim="test",
+ type=EvidenceType.DIRECT_STATEMENT,
+ source="test",
+ confidence=confidence,
+ )
+
+
+def _make_strategy(
+ candidates=None,
+ constraints=None,
+ confidence_threshold=0.85,
+ evidence_threshold=0.6,
+):
+ """Build a minimal Mock with the attributes used by pure-logic methods."""
+ s = Mock(spec=[])
+ s.candidates = candidates or []
+ s.constraints = constraints or []
+ s.confidence_threshold = confidence_threshold
+ s.evidence_threshold = evidence_threshold
+ return s
+
+
+# ---------------------------------------------------------------------------
+# _has_sufficient_answer
+# ---------------------------------------------------------------------------
+
+
+class TestHasSufficientAnswer:
+ """Verify sufficient-answer determination: score threshold + critical evidence."""
+
+ def test_no_candidates(self):
+ """No candidates -> False."""
+ s = _make_strategy(candidates=[])
+ assert EvidenceBasedStrategy._has_sufficient_answer(s) is False
+
+ def test_top_candidate_below_threshold(self):
+ """Top candidate score below confidence_threshold -> False."""
+ c = Candidate(name="X", score=0.5)
+ s = _make_strategy(candidates=[c])
+ assert EvidenceBasedStrategy._has_sufficient_answer(s) is False
+
+ def test_passes_with_all_critical_evidence(self):
+ """High score + all critical constraints have strong evidence -> True."""
+ c = Candidate(name="X", score=0.9)
+ con = _constraint("c1", weight=0.9)
+ c.add_evidence("c1", _evidence(confidence=0.7))
+ s = _make_strategy(
+ candidates=[c],
+ constraints=[con],
+ confidence_threshold=0.85,
+ evidence_threshold=0.6,
+ )
+ assert EvidenceBasedStrategy._has_sufficient_answer(s) is True
+
+ def test_fails_with_weak_critical_evidence(self):
+ """High score but critical constraint evidence below threshold -> False."""
+ c = Candidate(name="X", score=0.9)
+ con = _constraint("c1", weight=0.9)
+ c.add_evidence("c1", _evidence(confidence=0.3)) # Below 0.6
+ s = _make_strategy(
+ candidates=[c],
+ constraints=[con],
+ confidence_threshold=0.85,
+ evidence_threshold=0.6,
+ )
+ assert EvidenceBasedStrategy._has_sufficient_answer(s) is False
+
+ def test_fails_with_missing_critical_evidence(self):
+ """High score but critical constraint has no evidence -> False."""
+ c = Candidate(name="X", score=0.9)
+ con = _constraint("c1", weight=0.9)
+ s = _make_strategy(
+ candidates=[c],
+ constraints=[con],
+ confidence_threshold=0.85,
+ evidence_threshold=0.6,
+ )
+ assert EvidenceBasedStrategy._has_sufficient_answer(s) is False
+
+ def test_non_critical_constraints_ignored(self):
+ """Constraints with weight < 0.8 don't block sufficiency."""
+ c = Candidate(name="X", score=0.9)
+ critical = _constraint("c1", weight=0.9)
+ non_critical = _constraint("c2", weight=0.5)
+ c.add_evidence("c1", _evidence(confidence=0.8))
+ # c2 has no evidence but weight < 0.8
+ s = _make_strategy(
+ candidates=[c],
+ constraints=[critical, non_critical],
+ )
+ assert EvidenceBasedStrategy._has_sufficient_answer(s) is True
+
+ def test_multiple_critical_all_needed(self):
+ """All critical constraints must have sufficient evidence."""
+ c = Candidate(name="X", score=0.9)
+ c1 = _constraint("c1", weight=0.9)
+ c2 = _constraint("c2", weight=0.85)
+ c.add_evidence("c1", _evidence(confidence=0.8))
+ # c2 missing evidence
+ s = _make_strategy(candidates=[c], constraints=[c1, c2])
+ assert EvidenceBasedStrategy._has_sufficient_answer(s) is False
+
+
+# ---------------------------------------------------------------------------
+# _get_distinctive_constraints
+# ---------------------------------------------------------------------------
+
+
+class TestGetDistinctiveConstraints:
+ """Verify priority-sorted constraint selection with naming guarantee."""
+
+ def test_priority_order(self):
+ """NAME_PATTERN > LOCATION > EVENT > STATISTIC > PROPERTY > TEMPORAL."""
+ constraints = [
+ _constraint("prop", ConstraintType.PROPERTY),
+ _constraint("name", ConstraintType.NAME_PATTERN),
+ _constraint("loc", ConstraintType.LOCATION),
+ _constraint("evt", ConstraintType.EVENT),
+ ]
+ s = _make_strategy(constraints=constraints)
+ result = EvidenceBasedStrategy._get_distinctive_constraints(s)
+ ids = [c.id for c in result]
+ # Top 3 by priority: NAME_PATTERN, LOCATION, EVENT
+ assert ids == ["name", "loc", "evt"]
+
+ def test_returns_max_three(self):
+ """At most 3 constraints returned."""
+ constraints = [
+ _constraint(f"c{i}", ConstraintType.PROPERTY) for i in range(5)
+ ]
+ s = _make_strategy(constraints=constraints)
+ result = EvidenceBasedStrategy._get_distinctive_constraints(s)
+ assert len(result) == 3
+
+ def test_naming_guarantee(self):
+ """If top 3 lack NAME_PATTERN/LOCATION, one is swapped in."""
+ constraints = [
+ _constraint("stat", ConstraintType.STATISTIC),
+ _constraint("evt", ConstraintType.EVENT),
+ _constraint("prop", ConstraintType.PROPERTY),
+ _constraint("loc", ConstraintType.LOCATION), # 4th by priority
+ ]
+ s = _make_strategy(constraints=constraints)
+ result = EvidenceBasedStrategy._get_distinctive_constraints(s)
+ # Location should be swapped in for the least important (property)
+ ids = [c.id for c in result]
+ assert "loc" in ids
+
+ def test_naming_already_present(self):
+ """No swap needed if NAME_PATTERN already in top 3."""
+ constraints = [
+ _constraint("name", ConstraintType.NAME_PATTERN),
+ _constraint("stat", ConstraintType.STATISTIC),
+ _constraint("evt", ConstraintType.EVENT),
+ _constraint("prop", ConstraintType.PROPERTY),
+ ]
+ s = _make_strategy(constraints=constraints)
+ result = EvidenceBasedStrategy._get_distinctive_constraints(s)
+ ids = [c.id for c in result]
+ assert ids == ["name", "evt", "stat"]
+
+ def test_weight_tiebreaker(self):
+ """Within same type, higher weight comes first."""
+ constraints = [
+ _constraint("p1", ConstraintType.PROPERTY, weight=0.5),
+ _constraint("p2", ConstraintType.PROPERTY, weight=0.9),
+ _constraint("p3", ConstraintType.PROPERTY, weight=0.7),
+ ]
+ s = _make_strategy(constraints=constraints)
+ result = EvidenceBasedStrategy._get_distinctive_constraints(s)
+ ids = [c.id for c in result]
+ assert ids == ["p2", "p3", "p1"]
diff --git a/tests/advanced_search_system/strategies/test_evidence_v2_pure_logic.py b/tests/advanced_search_system/strategies/test_evidence_v2_pure_logic.py
new file mode 100644
index 0000000000..3a0a1e93ea
--- /dev/null
+++ b/tests/advanced_search_system/strategies/test_evidence_v2_pure_logic.py
@@ -0,0 +1,396 @@
+"""
+Pure-logic tests for EnhancedEvidenceBasedStrategy.
+
+Tests algorithmic methods that require no LLM or search calls:
+pattern initialization, source diversity scoring, deduplication,
+semantic variation generation, and pattern application.
+"""
+
+from unittest.mock import Mock
+
+from local_deep_research.advanced_search_system.candidates.base_candidate import (
+ Candidate,
+)
+from local_deep_research.advanced_search_system.constraints.base_constraint import (
+ Constraint,
+ ConstraintType,
+)
+from local_deep_research.advanced_search_system.strategies.evidence_based_strategy_v2 import (
+ EnhancedEvidenceBasedStrategy,
+ QueryPattern,
+ SourceProfile,
+)
+
+
+def _make_strategy(**overrides):
+ """Build a minimal Mock with attributes that the pure-logic methods read."""
+ s = Mock(spec=[])
+ s.candidates = overrides.get("candidates", [])
+ s.candidate_limit = overrides.get("candidate_limit", 20)
+ s.source_profiles = overrides.get("source_profiles", {})
+ return s
+
+
+# ---------------------------------------------------------------------------
+# _initialize_patterns
+# ---------------------------------------------------------------------------
+
+
+class TestInitializePatterns:
+ """Verify _initialize_patterns returns correct pattern catalogue."""
+
+ def test_returns_dict(self):
+ """Should return a dict of QueryPattern instances."""
+ result = EnhancedEvidenceBasedStrategy._initialize_patterns(Mock())
+ assert isinstance(result, dict)
+
+ def test_expected_keys(self):
+ """All six named patterns should be present."""
+ result = EnhancedEvidenceBasedStrategy._initialize_patterns(Mock())
+ expected = {
+ "property_basic",
+ "property_character",
+ "event_show",
+ "statistic_episodes",
+ "cross_constraint",
+ "semantic_expansion",
+ }
+ assert set(result.keys()) == expected
+
+ def test_property_patterns_have_property_type(self):
+ """Property patterns should list PROPERTY in constraint_types."""
+ result = EnhancedEvidenceBasedStrategy._initialize_patterns(Mock())
+ for key in ("property_basic", "property_character"):
+ assert ConstraintType.PROPERTY in result[key].constraint_types
+
+ def test_event_pattern_has_event_type(self):
+ """Event pattern should list EVENT in constraint_types."""
+ result = EnhancedEvidenceBasedStrategy._initialize_patterns(Mock())
+ assert ConstraintType.EVENT in result["event_show"].constraint_types
+
+ def test_statistic_pattern_has_statistic_type(self):
+ """Statistic pattern should list STATISTIC in constraint_types."""
+ result = EnhancedEvidenceBasedStrategy._initialize_patterns(Mock())
+ assert (
+ ConstraintType.STATISTIC
+ in result["statistic_episodes"].constraint_types
+ )
+
+ def test_cross_constraint_has_empty_types(self):
+ """Cross-constraint pattern is type-agnostic."""
+ result = EnhancedEvidenceBasedStrategy._initialize_patterns(Mock())
+ assert result["cross_constraint"].constraint_types == []
+
+ def test_patterns_are_querypattern_instances(self):
+ """Every value should be a QueryPattern dataclass."""
+ result = EnhancedEvidenceBasedStrategy._initialize_patterns(Mock())
+ for v in result.values():
+ assert isinstance(v, QueryPattern)
+
+
+# ---------------------------------------------------------------------------
+# _initialize_sources
+# ---------------------------------------------------------------------------
+
+
+class TestInitializeSources:
+ """Verify _initialize_sources returns correct source catalogue."""
+
+ def test_returns_dict(self):
+ """Should return a dict of SourceProfile instances."""
+ result = EnhancedEvidenceBasedStrategy._initialize_sources(Mock())
+ assert isinstance(result, dict)
+
+ def test_expected_sources(self):
+ """All five named sources should be present."""
+ result = EnhancedEvidenceBasedStrategy._initialize_sources(Mock())
+ expected = {"wikipedia", "imdb", "fandom", "tv_databases", "web"}
+ assert set(result.keys()) == expected
+
+ def test_source_names_match_keys(self):
+ """Each source_name field should match its dict key."""
+ result = EnhancedEvidenceBasedStrategy._initialize_sources(Mock())
+ for key, profile in result.items():
+ assert profile.source_name == key
+
+ def test_profiles_are_sourceprofile_instances(self):
+ """Every value should be a SourceProfile dataclass."""
+ result = EnhancedEvidenceBasedStrategy._initialize_sources(Mock())
+ for v in result.values():
+ assert isinstance(v, SourceProfile)
+
+ def test_wikipedia_specialties(self):
+ """Wikipedia should cover characters, properties, general."""
+ result = EnhancedEvidenceBasedStrategy._initialize_sources(Mock())
+ assert "characters" in result["wikipedia"].specialties
+ assert "general" in result["wikipedia"].specialties
+
+
+# ---------------------------------------------------------------------------
+# _calculate_source_diversity (Shannon entropy)
+# ---------------------------------------------------------------------------
+
+
+class TestCalculateSourceDiversity:
+ """Verify Shannon-entropy source diversity calculation."""
+
+ def _call(self, profiles):
+ s = _make_strategy(source_profiles=profiles)
+ return EnhancedEvidenceBasedStrategy._calculate_source_diversity(s)
+
+ def test_empty_profiles(self):
+ """No profiles at all -> 0.0."""
+ assert self._call({}) == 0.0
+
+ def test_no_usage(self):
+ """Profiles exist but none used -> 0.0."""
+ profiles = {
+ "a": SourceProfile(source_name="a", usage_count=0),
+ "b": SourceProfile(source_name="b", usage_count=0),
+ }
+ assert self._call(profiles) == 0.0
+
+ def test_single_source_used(self):
+ """Only one source used -> 0.0 (log2(1) = 0)."""
+ profiles = {
+ "a": SourceProfile(source_name="a", usage_count=5),
+ "b": SourceProfile(source_name="b", usage_count=0),
+ }
+ # Only one source in used_sources -> max_entropy = -log2(1/1) = 0
+ # Division by zero guard returns 0.0
+ assert self._call(profiles) == 0.0
+
+ def test_uniform_two_sources(self):
+ """Two sources used equally -> diversity = 1.0."""
+ profiles = {
+ "a": SourceProfile(source_name="a", usage_count=10),
+ "b": SourceProfile(source_name="b", usage_count=10),
+ }
+ assert self._call(profiles) == 1.0
+
+ def test_uniform_three_sources(self):
+ """Three sources used equally -> diversity = 1.0."""
+ profiles = {
+ "a": SourceProfile(source_name="a", usage_count=5),
+ "b": SourceProfile(source_name="b", usage_count=5),
+ "c": SourceProfile(source_name="c", usage_count=5),
+ }
+ assert abs(self._call(profiles) - 1.0) < 1e-9
+
+ def test_skewed_distribution(self):
+ """Skewed usage -> 0 < diversity < 1."""
+ profiles = {
+ "a": SourceProfile(source_name="a", usage_count=90),
+ "b": SourceProfile(source_name="b", usage_count=10),
+ }
+ diversity = self._call(profiles)
+ assert 0.0 < diversity < 1.0
+
+ def test_heavily_skewed(self):
+ """Very skewed usage -> close to 0 but positive."""
+ profiles = {
+ "a": SourceProfile(source_name="a", usage_count=999),
+ "b": SourceProfile(source_name="b", usage_count=1),
+ }
+ diversity = self._call(profiles)
+ assert 0.0 < diversity < 0.2
+
+
+# ---------------------------------------------------------------------------
+# _find_common_terms
+# ---------------------------------------------------------------------------
+
+
+class TestFindCommonTerms:
+ """Verify set-intersection of constraint value words."""
+
+ def _call(self, val1, val2):
+ c1 = Constraint(
+ id="c1", type=ConstraintType.PROPERTY, description="", value=val1
+ )
+ c2 = Constraint(
+ id="c2", type=ConstraintType.PROPERTY, description="", value=val2
+ )
+ return EnhancedEvidenceBasedStrategy._find_common_terms(Mock(), c1, c2)
+
+ def test_overlapping_terms(self):
+ """Shared words should be returned."""
+ result = self._call("red blue green", "blue green yellow")
+ assert set(result) == {"blue", "green"}
+
+ def test_no_overlap(self):
+ """No shared words -> empty list."""
+ assert self._call("cat dog", "fish bird") == []
+
+ def test_case_insensitive(self):
+ """Matching should be case-insensitive (lowered)."""
+ result = self._call("Alpha Beta", "alpha gamma")
+ assert "alpha" in result
+
+ def test_empty_values(self):
+ """Empty constraint values -> empty result."""
+ # split() on empty string returns [] -> empty set intersection
+ assert self._call("", "") == []
+
+
+# ---------------------------------------------------------------------------
+# _is_common_word
+# ---------------------------------------------------------------------------
+
+
+class TestIsCommonWord:
+ """Verify stopword detection."""
+
+ def _call(self, name):
+ return EnhancedEvidenceBasedStrategy._is_common_word(Mock(), name)
+
+ def test_common_word(self):
+ """'the' is a common word."""
+ assert self._call("the") is True
+
+ def test_proper_name(self):
+ """A proper name should not be flagged."""
+ assert self._call("Elizabeth") is False
+
+ def test_case_insensitive(self):
+ """'THE' should still be detected."""
+ assert self._call("THE") is True
+
+ def test_preposition(self):
+ """'from' is in the common word set."""
+ assert self._call("from") is True
+
+ def test_uncommon_short_word(self):
+ """'ax' is short but not in the set."""
+ assert self._call("ax") is False
+
+
+# ---------------------------------------------------------------------------
+# _add_unique_candidates
+# ---------------------------------------------------------------------------
+
+
+class TestAddUniqueCandidates:
+ """Verify deduplication and limit enforcement."""
+
+ def test_adds_new_candidates(self):
+ """New candidates are appended."""
+ s = _make_strategy(candidates=[], candidate_limit=10)
+ new = [Candidate(name="Alice"), Candidate(name="Bob")]
+ EnhancedEvidenceBasedStrategy._add_unique_candidates(s, new)
+ names = [c.name for c in s.candidates]
+ assert names == ["Alice", "Bob"]
+
+ def test_deduplicates_by_name(self):
+ """Duplicate names (case-insensitive) are skipped."""
+ s = _make_strategy(
+ candidates=[Candidate(name="Alice")],
+ candidate_limit=10,
+ )
+ new = [Candidate(name="alice"), Candidate(name="Bob")]
+ EnhancedEvidenceBasedStrategy._add_unique_candidates(s, new)
+ names = [c.name for c in s.candidates]
+ assert names == ["Alice", "Bob"]
+
+ def test_enforces_limit(self):
+ """Total candidates should not exceed candidate_limit."""
+ s = _make_strategy(candidates=[], candidate_limit=3)
+ new = [Candidate(name=f"C{i}") for i in range(5)]
+ EnhancedEvidenceBasedStrategy._add_unique_candidates(s, new)
+ assert len(s.candidates) == 3
+
+ def test_empty_input(self):
+ """Empty new-candidates list doesn't modify existing."""
+ existing = [Candidate(name="Alice")]
+ s = _make_strategy(candidates=existing, candidate_limit=10)
+ EnhancedEvidenceBasedStrategy._add_unique_candidates(s, [])
+ assert len(s.candidates) == 1
+
+
+# ---------------------------------------------------------------------------
+# _generate_semantic_variations
+# ---------------------------------------------------------------------------
+
+
+class TestGenerateSemanticVariations:
+ """Verify query variation generation by constraint type."""
+
+ def _call(self, ctype, value="test value"):
+ c = Constraint(id="c1", type=ctype, description="desc", value=value)
+ return EnhancedEvidenceBasedStrategy._generate_semantic_variations(
+ Mock(), c
+ )
+
+ def test_property_variations(self):
+ """PROPERTY type should produce 'entity with …' style variations."""
+ result = self._call(ConstraintType.PROPERTY)
+ assert any("entity with" in v for v in result)
+
+ def test_event_variations(self):
+ """EVENT type should produce 'when …' style variation."""
+ result = self._call(ConstraintType.EVENT)
+ assert any("when" in v for v in result)
+
+ def test_statistic_variations(self):
+ """STATISTIC type should produce 'number …' style variation."""
+ result = self._call(ConstraintType.STATISTIC)
+ assert any("number" in v for v in result)
+
+ def test_unknown_type_generic(self):
+ """Non-standard type falls through to generic variations."""
+ result = self._call(ConstraintType.LOCATION)
+ assert any(
+ "specific" in v or "about" in v or "regarding" in v for v in result
+ )
+
+ def test_capped_at_five(self):
+ """No more than 5 variations returned."""
+ result = self._call(ConstraintType.PROPERTY)
+ assert len(result) <= 5
+
+ def test_variations_contain_value(self):
+ """All variations should incorporate the constraint value."""
+ result = self._call(ConstraintType.PROPERTY, "blue eyes")
+ assert all("blue eyes" in v for v in result)
+
+
+# ---------------------------------------------------------------------------
+# _apply_pattern_to_constraint
+# ---------------------------------------------------------------------------
+
+
+class TestApplyPatternToConstraint:
+ """Verify placeholder substitution in query patterns."""
+
+ def _call(self, pattern_str, value, ctype=ConstraintType.PROPERTY):
+ pattern = QueryPattern(pattern=pattern_str, constraint_types=[])
+ constraint = Constraint(
+ id="c1", type=ctype, description="", value=value
+ )
+ return EnhancedEvidenceBasedStrategy._apply_pattern_to_constraint(
+ Mock(), pattern, constraint
+ )
+
+ def test_value_substitution(self):
+ """'{value}' placeholder is replaced."""
+ result = self._call("{value} query", "blue eyes")
+ assert result == "blue eyes query"
+
+ def test_constraint_type_substitution(self):
+ """'{constraint_type}' placeholder is replaced with enum value."""
+ result = self._call(
+ "{value} {constraint_type}", "test", ConstraintType.EVENT
+ )
+ assert result == "test event"
+
+ def test_no_placeholders(self):
+ """Pattern without placeholders is returned unchanged."""
+ result = self._call("static query", "ignored")
+ assert result == "static query"
+
+ def test_both_placeholders(self):
+ """Both {value} and {constraint_type} replaced in one pass."""
+ result = self._call(
+ "find {value} type {constraint_type}", "X", ConstraintType.STATISTIC
+ )
+ assert result == "find X type statistic"
diff --git a/tests/advanced_search_system/strategies/test_iterative_reasoning_pure_logic.py b/tests/advanced_search_system/strategies/test_iterative_reasoning_pure_logic.py
new file mode 100644
index 0000000000..dbfd9e0608
--- /dev/null
+++ b/tests/advanced_search_system/strategies/test_iterative_reasoning_pure_logic.py
@@ -0,0 +1,198 @@
+"""
+Pure-logic tests for IterativeReasoningStrategy._assess_answer
+and KnowledgeState.to_string.
+
+Tests the multi-factor confidence model (spread penalty, fact boost,
+uncertainty penalty, search boost, candidate penalty, 0.95 cap) and
+knowledge state formatting — no LLM or search calls.
+"""
+
+from unittest.mock import Mock
+
+from local_deep_research.advanced_search_system.strategies.iterative_reasoning_strategy import (
+ IterativeReasoningStrategy,
+ KnowledgeState,
+)
+
+
+def _make_strategy(
+ candidate_answers=None,
+ key_facts=None,
+ uncertainties=None,
+ search_history=None,
+):
+ """Build a minimal Mock with a KnowledgeState."""
+ s = Mock(spec=[])
+ s.knowledge_state = KnowledgeState(
+ original_query="test query",
+ candidate_answers=candidate_answers or [],
+ key_facts=key_facts or [],
+ uncertainties=uncertainties or [],
+ search_history=search_history or [],
+ )
+ return s
+
+
+# ---------------------------------------------------------------------------
+# KnowledgeState.to_string
+# ---------------------------------------------------------------------------
+
+
+class TestKnowledgeStateToString:
+ """Verify knowledge state formatting."""
+
+ def test_empty_state(self):
+ """Empty state shows 'Nothing yet' for facts and uncertainties."""
+ ks = KnowledgeState(original_query="What is X?")
+ result = ks.to_string()
+ assert "What is X?" in result
+ assert "Nothing yet" in result
+ assert "No searches yet" in result
+ assert "None yet" in result
+
+ def test_with_facts(self):
+ """Key facts are listed."""
+ ks = KnowledgeState(
+ original_query="Q",
+ key_facts=["Fact A", "Fact B"],
+ )
+ result = ks.to_string()
+ assert "Fact A" in result
+ assert "Fact B" in result
+
+ def test_with_candidates(self):
+ """Candidates are sorted by confidence descending."""
+ ks = KnowledgeState(
+ original_query="Q",
+ candidate_answers=[
+ {"answer": "Low", "confidence": 0.3},
+ {"answer": "High", "confidence": 0.9},
+ ],
+ )
+ result = ks.to_string()
+ # High should appear before Low
+ assert result.index("High") < result.index("Low")
+
+ def test_search_history_shows_last_three(self):
+ """Only last 3 searches are shown."""
+ ks = KnowledgeState(
+ original_query="Q",
+ search_history=[{"query": f"search {i}"} for i in range(5)],
+ )
+ result = ks.to_string()
+ assert "search 2" in result
+ assert "search 4" in result
+ # search 0 and 1 should not be shown (only last 3)
+ assert "search 0" not in result
+
+ def test_confidence_formatted(self):
+ """Current confidence is formatted as percentage."""
+ ks = KnowledgeState(original_query="Q", confidence=0.75)
+ result = ks.to_string()
+ assert "75.0%" in result
+
+
+# ---------------------------------------------------------------------------
+# _assess_answer
+# ---------------------------------------------------------------------------
+
+
+class TestAssessAnswer:
+ """Verify multi-factor confidence assessment."""
+
+ def _assess(self, **kwargs):
+ s = _make_strategy(**kwargs)
+ IterativeReasoningStrategy._assess_answer(s)
+ return s.knowledge_state.confidence
+
+ def test_no_candidates(self):
+ """No candidates -> confidence 0.0."""
+ assert self._assess(candidate_answers=[]) == 0.0
+
+ def test_single_candidate_base(self):
+ """Single candidate: confidence = candidate confidence + boosts."""
+ conf = self._assess(
+ candidate_answers=[{"answer": "A", "confidence": 0.7}],
+ )
+ # base 0.7 + fact_boost 0 + search_boost 0 - uncertainty 0 - candidate_penalty 0
+ assert abs(conf - 0.7) < 1e-9
+
+ def test_close_spread_penalty(self):
+ """Two candidates within 0.1 spread -> 20% reduction of base."""
+ conf = self._assess(
+ candidate_answers=[
+ {"answer": "A", "confidence": 0.8},
+ {"answer": "B", "confidence": 0.75},
+ ],
+ )
+ # spread = 0.05 < 0.1 -> base = 0.8 * 0.8 = 0.64
+ assert abs(conf - 0.64) < 1e-9
+
+ def test_wide_spread_no_penalty(self):
+ """Two candidates with spread >= 0.1 -> no reduction."""
+ conf = self._assess(
+ candidate_answers=[
+ {"answer": "A", "confidence": 0.8},
+ {"answer": "B", "confidence": 0.5},
+ ],
+ )
+ # spread = 0.3 >= 0.1 -> base stays 0.8
+ assert abs(conf - 0.8) < 1e-9
+
+ def test_fact_boost(self):
+ """Key facts add 0.05 each, capped at 0.2."""
+ conf = self._assess(
+ candidate_answers=[{"answer": "A", "confidence": 0.5}],
+ key_facts=["f1", "f2", "f3"],
+ )
+ # base 0.5 + fact_boost min(3*0.05, 0.2) = 0.15
+ assert abs(conf - 0.65) < 1e-9
+
+ def test_fact_boost_capped(self):
+ """Fact boost capped at 0.2."""
+ conf = self._assess(
+ candidate_answers=[{"answer": "A", "confidence": 0.5}],
+ key_facts=[f"f{i}" for i in range(10)],
+ )
+ # base 0.5 + fact_boost 0.2
+ assert abs(conf - 0.7) < 1e-9
+
+ def test_uncertainty_penalty(self):
+ """Uncertainties subtract 0.05 each, capped at 0.2."""
+ conf = self._assess(
+ candidate_answers=[{"answer": "A", "confidence": 0.8}],
+ uncertainties=["u1", "u2"],
+ )
+ # base 0.8 - uncertainty min(2*0.05, 0.2) = 0.1
+ assert abs(conf - 0.7) < 1e-9
+
+ def test_search_boost(self):
+ """Search history adds 0.02 each, capped at 0.1."""
+ conf = self._assess(
+ candidate_answers=[{"answer": "A", "confidence": 0.5}],
+ search_history=[{"query": f"q{i}"} for i in range(3)],
+ )
+ # base 0.5 + search_boost min(3*0.02, 0.1) = 0.06
+ assert abs(conf - 0.56) < 1e-9
+
+ def test_candidate_penalty(self):
+ """More than 3 candidates incur penalty of 0.05 each, capped at 0.15."""
+ conf = self._assess(
+ candidate_answers=[
+ {"answer": f"A{i}", "confidence": 0.8 - i * 0.15}
+ for i in range(5)
+ ],
+ )
+ # 5 candidates -> penalty = min((5-3)*0.05, 0.15) = 0.1
+ # spread: 0.8 vs 0.65 = 0.15 >= 0.1 -> no spread penalty
+ # base 0.8 - 0.1 = 0.7
+ assert abs(conf - 0.7) < 1e-9
+
+ def test_capped_at_095(self):
+ """Confidence never exceeds 0.95."""
+ conf = self._assess(
+ candidate_answers=[{"answer": "A", "confidence": 0.95}],
+ key_facts=[f"f{i}" for i in range(10)],
+ search_history=[{"query": f"q{i}"} for i in range(10)],
+ )
+ assert conf == 0.95
diff --git a/tests/advanced_search_system/strategies/test_smart_decomp_pure_logic.py b/tests/advanced_search_system/strategies/test_smart_decomp_pure_logic.py
new file mode 100644
index 0000000000..d33633fbe1
--- /dev/null
+++ b/tests/advanced_search_system/strategies/test_smart_decomp_pure_logic.py
@@ -0,0 +1,53 @@
+"""
+Pure-logic tests for SmartDecompositionStrategy._is_browsecomp_style.
+
+Tests indicator-phrase counting with the >= 3 threshold,
+requiring no LLM or search calls.
+"""
+
+from unittest.mock import Mock
+
+from local_deep_research.advanced_search_system.strategies.smart_decomposition_strategy import (
+ SmartDecompositionStrategy,
+)
+
+
+class TestIsBrowsecompStyle:
+ """Verify BrowseComp-style detection based on indicator phrase counting."""
+
+ def _call(self, query):
+ return SmartDecompositionStrategy._is_browsecomp_style(Mock(), query)
+
+ def test_zero_indicators(self):
+ """Query with no indicator phrases -> False."""
+ assert self._call("What is the capital of France?") is False
+
+ def test_one_indicator(self):
+ """Query with one indicator -> False."""
+ assert self._call("What is the name of the president?") is False
+
+ def test_two_indicators(self):
+ """Query with two indicators -> False (need >= 3)."""
+ assert (
+ self._call("What is the name of something between two cities?")
+ is False
+ )
+
+ def test_three_indicators(self):
+ """Query with exactly three indicators -> True."""
+ query = "What is the name of the specific scenic location where search and rescue operates?"
+ assert self._call(query) is True
+
+ def test_many_indicators(self):
+ """Query with many indicators -> True."""
+ query = (
+ "What is the name of the specific scenic location with a viewpoint "
+ "where someone fell from during search and rescue SAR incidents "
+ "involving a body part since the last ice age?"
+ )
+ assert self._call(query) is True
+
+ def test_case_insensitive(self):
+ """Indicator matching should be case-insensitive."""
+ query = "WHAT IS THE NAME of a SPECIFIC SCENIC LOCATION with SEARCH AND RESCUE"
+ assert self._call(query) is True
diff --git a/tests/advanced_search_system/test_candidate_scoring.py b/tests/advanced_search_system/test_candidate_scoring.py
new file mode 100644
index 0000000000..624ef597ec
--- /dev/null
+++ b/tests/advanced_search_system/test_candidate_scoring.py
@@ -0,0 +1,254 @@
+"""
+Pure-logic tests for Candidate, Constraint, and EvidenceType.
+
+Tests scoring, unverified-constraint filtering, weak-evidence detection,
+search-term generation, criticality checks, and base confidence mapping,
+requiring no LLM or search calls.
+"""
+
+from local_deep_research.advanced_search_system.candidates.base_candidate import (
+ Candidate,
+)
+from local_deep_research.advanced_search_system.constraints.base_constraint import (
+ Constraint,
+ ConstraintType,
+)
+from local_deep_research.advanced_search_system.evidence.base_evidence import (
+ Evidence,
+ EvidenceType,
+)
+
+
+def _constraint(id, ctype=ConstraintType.PROPERTY, weight=1.0, value="v"):
+ return Constraint(
+ id=id, type=ctype, description="", value=value, weight=weight
+ )
+
+
+def _evidence(confidence=0.8):
+ return Evidence(
+ claim="test",
+ type=EvidenceType.DIRECT_STATEMENT,
+ source="test",
+ confidence=confidence,
+ )
+
+
+# ---------------------------------------------------------------------------
+# Candidate.calculate_score
+# ---------------------------------------------------------------------------
+
+
+class TestCandidateCalculateScore:
+ """Verify weighted-average scoring of candidate evidence."""
+
+ def test_no_constraints(self):
+ """No constraints -> 0.0."""
+ c = Candidate(name="X")
+ assert c.calculate_score([]) == 0.0
+
+ def test_single_constraint_with_evidence(self):
+ """One constraint, full evidence -> confidence * weight / weight."""
+ c = Candidate(name="X")
+ con = _constraint("c1", weight=1.0)
+ c.add_evidence("c1", _evidence(confidence=0.9))
+ score = c.calculate_score([con])
+ assert abs(score - 0.9) < 1e-9
+
+ def test_mixed_weights(self):
+ """Two constraints with different weights."""
+ c = Candidate(name="X")
+ c1 = _constraint("c1", weight=2.0)
+ c2 = _constraint("c2", weight=1.0)
+ c.add_evidence("c1", _evidence(confidence=0.8))
+ c.add_evidence("c2", _evidence(confidence=0.5))
+ # (0.8*2.0 + 0.5*1.0) / (2.0+1.0) = 2.1/3.0 = 0.7
+ score = c.calculate_score([c1, c2])
+ assert abs(score - 0.7) < 1e-9
+
+ def test_missing_evidence(self):
+ """Constraint without evidence contributes 0 to numerator."""
+ c = Candidate(name="X")
+ c1 = _constraint("c1", weight=1.0)
+ c2 = _constraint("c2", weight=1.0)
+ c.add_evidence("c1", _evidence(confidence=1.0))
+ # c2 has no evidence -> 0 contribution
+ score = c.calculate_score([c1, c2])
+ assert abs(score - 0.5) < 1e-9
+
+ def test_updates_score_attribute(self):
+ """calculate_score should also set self.score."""
+ c = Candidate(name="X")
+ con = _constraint("c1")
+ c.add_evidence("c1", _evidence(confidence=0.7))
+ c.calculate_score([con])
+ assert abs(c.score - 0.7) < 1e-9
+
+
+# ---------------------------------------------------------------------------
+# Candidate.get_unverified_constraints
+# ---------------------------------------------------------------------------
+
+
+class TestGetUnverifiedConstraints:
+ """Verify filtering of constraints without evidence."""
+
+ def test_all_verified(self):
+ """All constraints have evidence -> empty list."""
+ c = Candidate(name="X")
+ con = _constraint("c1")
+ c.add_evidence("c1", _evidence())
+ assert c.get_unverified_constraints([con]) == []
+
+ def test_none_verified(self):
+ """No evidence at all -> all constraints returned."""
+ c = Candidate(name="X")
+ cons = [_constraint("c1"), _constraint("c2")]
+ result = c.get_unverified_constraints(cons)
+ assert len(result) == 2
+
+ def test_partial(self):
+ """Some constraints verified, some not."""
+ c = Candidate(name="X")
+ c.add_evidence("c1", _evidence())
+ cons = [_constraint("c1"), _constraint("c2"), _constraint("c3")]
+ result = c.get_unverified_constraints(cons)
+ assert [r.id for r in result] == ["c2", "c3"]
+
+
+# ---------------------------------------------------------------------------
+# Candidate.get_weak_evidence
+# ---------------------------------------------------------------------------
+
+
+class TestGetWeakEvidence:
+ """Verify filtering of low-confidence evidence."""
+
+ def test_default_threshold(self):
+ """Default threshold 0.5: evidence at 0.3 is weak."""
+ c = Candidate(name="X")
+ c.add_evidence("c1", _evidence(confidence=0.3))
+ c.add_evidence("c2", _evidence(confidence=0.8))
+ assert c.get_weak_evidence() == ["c1"]
+
+ def test_custom_threshold(self):
+ """Custom threshold 0.9: evidence at 0.8 is now weak."""
+ c = Candidate(name="X")
+ c.add_evidence("c1", _evidence(confidence=0.8))
+ assert c.get_weak_evidence(threshold=0.9) == ["c1"]
+
+ def test_no_weak(self):
+ """All evidence above threshold -> empty list."""
+ c = Candidate(name="X")
+ c.add_evidence("c1", _evidence(confidence=0.9))
+ assert c.get_weak_evidence() == []
+
+ def test_all_weak(self):
+ """All evidence below threshold."""
+ c = Candidate(name="X")
+ c.add_evidence("c1", _evidence(confidence=0.1))
+ c.add_evidence("c2", _evidence(confidence=0.2))
+ result = c.get_weak_evidence()
+ assert set(result) == {"c1", "c2"}
+
+
+# ---------------------------------------------------------------------------
+# Constraint.to_search_terms
+# ---------------------------------------------------------------------------
+
+
+class TestConstraintToSearchTerms:
+ """Verify search-term generation by constraint type."""
+
+ def test_property(self):
+ """PROPERTY -> raw value."""
+ c = _constraint("c1", ConstraintType.PROPERTY, value="blue eyes")
+ assert c.to_search_terms() == "blue eyes"
+
+ def test_name_pattern(self):
+ """NAME_PATTERN -> value + 'name trail mountain'."""
+ c = _constraint("c1", ConstraintType.NAME_PATTERN, value="body part")
+ result = c.to_search_terms()
+ assert "body part" in result
+ assert "name trail mountain" in result
+
+ def test_event(self):
+ """EVENT -> value + 'accident incident'."""
+ c = _constraint("c1", ConstraintType.EVENT, value="fell from")
+ result = c.to_search_terms()
+ assert "fell from" in result
+ assert "accident incident" in result
+
+ def test_statistic(self):
+ """STATISTIC -> value + 'statistics data'."""
+ c = _constraint("c1", ConstraintType.STATISTIC, value="84.5x ratio")
+ result = c.to_search_terms()
+ assert "84.5x ratio" in result
+ assert "statistics data" in result
+
+ def test_other_type(self):
+ """Other types -> str(value)."""
+ c = _constraint("c1", ConstraintType.LOCATION, value="Colorado")
+ assert c.to_search_terms() == "Colorado"
+
+
+# ---------------------------------------------------------------------------
+# Constraint.is_critical
+# ---------------------------------------------------------------------------
+
+
+class TestConstraintIsCritical:
+ """Verify criticality determination."""
+
+ def test_name_pattern_always_critical(self):
+ """NAME_PATTERN is critical regardless of weight."""
+ c = _constraint("c1", ConstraintType.NAME_PATTERN, weight=0.1)
+ assert c.is_critical() is True
+
+ def test_high_weight_critical(self):
+ """Weight > 0.8 is critical for non-NAME_PATTERN."""
+ c = _constraint("c1", ConstraintType.PROPERTY, weight=0.9)
+ assert c.is_critical() is True
+
+ def test_low_weight_not_critical(self):
+ """Weight <= 0.8 is not critical for non-NAME_PATTERN."""
+ c = _constraint("c1", ConstraintType.PROPERTY, weight=0.8)
+ assert c.is_critical() is False
+
+ def test_boundary_weight(self):
+ """Weight exactly 0.8 -> not critical (> 0.8 required)."""
+ c = _constraint("c1", ConstraintType.EVENT, weight=0.8)
+ assert c.is_critical() is False
+
+
+# ---------------------------------------------------------------------------
+# EvidenceType.base_confidence
+# ---------------------------------------------------------------------------
+
+
+class TestEvidenceTypeBaseConfidence:
+ """Verify base confidence mapping for each evidence type."""
+
+ def test_direct_statement(self):
+ assert EvidenceType.DIRECT_STATEMENT.base_confidence == 0.95
+
+ def test_official_record(self):
+ assert EvidenceType.OFFICIAL_RECORD.base_confidence == 0.90
+
+ def test_research_finding(self):
+ assert EvidenceType.RESEARCH_FINDING.base_confidence == 0.85
+
+ def test_statistical_data(self):
+ assert EvidenceType.STATISTICAL_DATA.base_confidence == 0.85
+
+ def test_news_report(self):
+ assert EvidenceType.NEWS_REPORT.base_confidence == 0.75
+
+ def test_inference(self):
+ assert EvidenceType.INFERENCE.base_confidence == 0.50
+
+ def test_correlation(self):
+ assert EvidenceType.CORRELATION.base_confidence == 0.30
+
+ def test_speculation(self):
+ assert EvidenceType.SPECULATION.base_confidence == 0.10