~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.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
refactor: delete 6 dead files + 17 test files in advanced_search_system (#3184)
LearningCircuitb516e5fe3461
diff --git a/docs/strategies/deleted/pr-3184-dead-advanced-search-files.md b/docs/strategies/deleted/pr-3184-dead-advanced-search-files.mdnew file mode 100644index 0000000000..426f4dde94--- /dev/null+++ b/docs/strategies/deleted/pr-3184-dead-advanced-search-files.md@@ -0,0 +1,154 @@+# PR #3184 — delete 6 dead advanced_search_system files + 17 test files++Components deleted in PR #3184 (see that PR for the full pre-deletion code —+this file only summarises what was novel).++All six were unreachable from `search_system_factory.py` and had zero+production imports at deletion; each was orphaned experimental work.+Multi-round subagent novelty audit confirmed every file before deletion.++---++## Component: `AdaptiveQueryGenerator`++- File deleted: `src/local_deep_research/advanced_search_system/query_generation/adaptive_query_generator.py` (405 LOC at deletion).+- Reachability: no producers or consumers outside the module.+- Closest reachable successors: `SmartQueryStrategy` (`src/local_deep_research/advanced_search_system/strategies/smart_query_strategy.py`) for LLM-driven query synthesis, and `EnhancedEvidenceBasedStrategy` (`evidence_based_strategy_v2.py`) for pattern learning.++### Useful ideas from the pre-deletion version++- **Hand-curated query-template library with hardcoded success rates** — a small registry of query shapes (entity+property+location, event+temporal+statistic, name+comparison) seeded at 0.6–0.7 success and updated from usage. Superseded by v2's `QueryPattern` dataclass doing the same thing, though less granular.+- **LLM-synonym semantic-expansion cache** — for each constraint value, fetched 3 alternative phrasings once and built `(term OR syn1 OR syn2)` queries from them. Not actively exercised anywhere today; v2 has a "semantic_expansion" pattern name but uses static templates.+- **Constraint-tuple success tracking** — counted which *combinations* of constraint types led to successful candidate discoveries (not just individual constraints) and sorted by frequency. This combination-ordering heuristic is absent in successors.+- **Type-specific single-constraint fallback templates** — hardcoded fallback queries for each constraint type (e.g. `'"{value}" names list'` for `NAME_PATTERN`, `'"{value}" incidents accidents'` for `EVENT`) guaranteeing query generation even when multi-constraint templates fail. Successors regenerate via LLM, losing the guaranteed-coverage floor.+- **4-tier on-demand fallback escalation** — simplify → broaden (AND → OR) → decompose to single constraints → LLM-generated alternatives. `SmartQueryStrategy._generate_query_variations` generates variants up front instead, which is cheaper but less reactive.++### Why deletion was safe++v2 and `SmartQueryStrategy` reimplement the most important pieces (pattern learning, semantic expansion concept) at coarser granularity. Type-specific hardcoded templates are replaced by general LLM synthesis — flexible but loses guaranteed-minimal-coverage.++### Recovery path++If the semantic-expansion cache or combination-tuple learning proves valuable in benchmarks, add it as an optional flag on `EnhancedEvidenceBasedStrategy` and wire it into `_update_patterns()`.++---++## Component: `DiversityManager`++- File deleted: `src/local_deep_research/advanced_search_system/source_management/diversity_manager.py` (613 LOC at deletion).+- Reachability: zero references across `src/` and `tests/`.+- Closest reachable successor: `EnhancedEvidenceBasedStrategy._calculate_source_diversity` (`evidence_based_strategy_v2.py` ~lines 887-909). The successor does a fraction of what the deleted file did.++### Useful ideas from the pre-deletion version++This was the richest file in the PR by far — nine distinct ideas worth flagging:++- **Multi-dimensional source profiling** — per-source record of URL, domain, type, credibility, specialties, temporal coverage, geographic focus, unified in one profile object. Successor tracks only name + usage stats.+- **Structured `DiversityMetrics` dataclass** — separate scores for type, temporal, geographic, credibility distribution plus a specialty-coverage breakdown. Successor collapses everything into one entropy aggregate.+- **Credibility scoring with domain heuristics** — source-type base scores (academic 0.9 / government 0.85 / news 0.7 / wiki 0.75 / blog 0.5 / forum 0.4 / social 0.3) adjusted by domain signals (HTTPS, presence of citations, author info). No equivalent today.+- **LLM-driven source-type detection** — content-excerpt prompt to classify ambiguous sources instead of pattern-matching URLs. No equivalent today.+- **Temporal and geographic extraction from content** — regex + content analysis to derive year range and geographic focus. No equivalent today.+- **Diversity gap identification + actionable recommendations** — explicitly detected missing types / regions / time ranges and generated search modifiers to fill them. No recommendation engine anywhere today.+- **Source-effectiveness feedback loop** — boosted credibility on constraint satisfaction; tracked per-source evidence quality and timestamps. Successor tracks count + success rate only.+- **Constraint-aware source selection** — preferred specialised sources per constraint type (academic for properties, IMDB for statistics, Wikipedia for locations). Successor uses generic least-used-first.+- **Diversity-preserving selection** — refused to add an Nth source of one type if another type was underrepresented. Score-ranking alone doesn't do this.++### Why deletion was safe++Orphaned experimental system. No caller invoked any of `select_diverse_sources`, `recommend_additional_sources`, `calculate_diversity_metrics`, or `track_source_effectiveness`. Production strategies use the simpler entropy-based balancing in v2 plus category-based candidate diversity in `DiversityExplorer`.++### Recovery path++If source-profile coherence or credibility heuristics become necessary, reintroduce the `type_priorities` mapping and credibility-enhancement logic as composable helpers on `EnhancedEvidenceBasedStrategy`, not as a standalone manager.++---++## Component: `CrossConstraintManager`++- File deleted: `src/local_deep_research/advanced_search_system/search_optimization/cross_constraint_manager.py` (624 LOC at deletion).+- Reachability: zero references anywhere.+- Closest reachable successor: `EnhancedEvidenceBasedStrategy._analyze_constraint_relationships` (`evidence_based_strategy_v2.py` ~lines 836-850). Does far less.++### Useful ideas from the pre-deletion version++- **Typed constraint relationships** — pairwise `ConstraintRelationship` classified as `complementary / dependent / exclusive` via LLM with a strength score in `[0, 1]`. Successor only tracks untyped adjacency lists.+- **Three-layer constraint clustering** — type-based → relationship-graph-connected-component → LLM-driven semantic clustering, with a cluster-coherence score (weighted average relationship strength × cluster size). No equivalent today.+- **Progressive multi-constraint query generation** — built a family of queries ramping up constraint count (top-2, then top-3, …) rather than generating one combined query. Not replicated in successors.+- **Pairwise cross-validation queries** — dedicated per-pair queries of the form "does candidate satisfy constraint A *and* constraint B together?" Absent today.+- **Cross-constraint candidate validation** — joint-confidence scoring that explicitly boosted complementary constraint pairs. Successors do per-constraint evidence gathering without joint coupling.++### Why deletion was safe++Pure search-optimization layer that was never wired into the factory. The core multi-constraint mechanics (pairing, combined searches, evidence aggregation) are now inline methods on `EnhancedEvidenceBasedStrategy` and the former `ImprovedEvidenceBasedStrategy`; the relationship-typing + clustering-coherence content is genuinely lost, but with no benchmark data it's not clear it was paying for itself.++### Recovery path++If relationship typing becomes load-bearing, rebuild as a mixin on `EnhancedEvidenceBasedStrategy` reusing the `ConstraintRelationship` / `ConstraintCluster` dataclass shapes from the pre-deletion file. Don't restore the 624-LOC parallel manager.++---++## Component: `IntelligentConstraintRelaxer`++- File deleted: `src/local_deep_research/advanced_search_system/constraint_checking/intelligent_constraint_relaxer.py` (501 LOC at deletion).+- Reachability: not imported anywhere.+- Closest reachable successors: `ConstrainedSearchStrategy._rank_constraints_by_restrictiveness` and `ParallelConstrainedStrategy._create_relaxed_combinations`.++### Useful ideas from the pre-deletion version++- **Explicit constraint-type priority hierarchy** — hardcoded priority map (`NAME_PATTERN=10, STATISTIC=3, COMPARISON=1`, etc.) distinguishing "essential, never relax" from "safe to drop first." Successors use a generic restrictiveness score based on length/presence-of-numbers; no semantic-importance knowledge.+- **Progressive relaxation with `min_constraints=2` floor** — generated relaxations in priority order (drop 1 low-priority, then 2, then 3) while preserving enough structure for the query to mean something. Successors skip to binary phases (strict → relaxed → individual).+- **Type-specific semantic variations** — four dedicated relaxers (STATISTIC / COMPARISON / TEMPORAL / PROPERTY) producing semantically-aware alternatives: ±10% / ±20% / ±50% tolerance bands for statistics, term mappings like "times more" → "significantly more" for comparisons, year → decade → year-range for temporal. Successors strip constraints to bare values, losing these mappings.+- **Rejection-impact analysis** — `analyze_relaxation_impact` labelled each relaxation as high/low-impact with a user-facing warning ("High-priority constraints removed. Results may be less accurate."). No equivalent tracing today.++### Why deletion was safe++Ranking by restrictiveness and phased-search fallback together cover the "coarse" relaxation shape without the specialised class. The per-type semantic variations are less sophisticated now, but the codebase prioritises breadth over depth of relaxation.++### Recovery path++Put the constraint-type-to-priority map on `Constraint.is_critical()` (in `base_constraint.py`) as a lookup table. If the per-type variation logic matters later, port the four `_relax_*_constraint` method bodies into a helper used by `ConstrainedSearchStrategy` — don't restore the file.++---++## Component: `BrowseCompAnswerDecoder`++- File deleted: `src/local_deep_research/advanced_search_system/answer_decoding/browsecomp_answer_decoder.py` (422 LOC at deletion).+- Reachability: exported in `answer_decoding/__init__.py` at deletion but never instantiated anywhere in production code.+- Closest reachable successor: dataset-level decryption helpers in `src/local_deep_research/benchmarks/datasets/utils.py` and `browsecomp.py` (XOR + hardcoded-key fallback only).++### Useful ideas from the pre-deletion version++- **Multi-scheme encoding detection pipeline** — attempted base64, hex, URL-encoding, ROT13, and Caesar in one pattern-driven sweep. Successor only handles XOR+base64, which is sufficient for current BrowseComp datasets but not obviously future-proof.+- **Caesar cipher scored by an English-frequency heuristic** — ranked shifts 1–25 using letter-frequency scoring (top-10 letters +2, top-20 +1) plus common-word bonuses, returning only shifts above threshold. More general than the hardcoded-key lookup in the successor.+- **Plaintext-vs-encoded heuristics** — short-answer detection, English-indicator word presence, year/money/name/percentage regex, character-diversity floor. Useful for avoiding false decoding of legitimate plaintext answers; no equivalent today.+- **Character-distribution answer validation** — ≥80% printable, no control characters, ≥30% letters, <50% punctuation. Successor's range check (ASCII 32–126 only) is much looser.+- **`analyze_answer_encoding` diagnostic mode** — returned a full per-scheme breakdown of matches, decodings, and validity. Debug tool, not production-critical.++### Why deletion was safe++The decoder was only a hypothetical extension layer; real BrowseComp decryption happens at dataset load time with XOR+password-derived keys. No benchmark runner or strategy depended on it.++### Recovery path++If a dataset arrives using Caesar, ROT13, or multi-scheme encoding, lift the `_decode_caesar` / `_english_score` functions and the plaintext heuristics from the pre-deletion file into `benchmarks/datasets/utils.py`. Don't restore the whole decoder module.++---++## Component: `EvidenceRequirements` (and its helpers)++- File deleted: `src/local_deep_research/advanced_search_system/evidence/requirements.py` (122 LOC at deletion).+- Reachability: exported in `evidence/__init__.py` but never imported or instantiated anywhere.+- Closest reachable successor: `EvidenceEvaluator` (`evidence/evaluator.py`) + `base_evidence.py`.++### Useful ideas from the pre-deletion version++- **Per-constraint-type confidence floors** — distinct minimum-confidence thresholds per constraint type: `STATISTIC=0.8, EVENT=0.7, PROPERTY=0.6, NAME_PATTERN=0.5`. Current code uses a single global threshold (typically 0.85 or factory-default 0.95) for all types, losing this nuance.+- **Per-constraint preferred/acceptable source guidance** — hand-curated source-type preferences per constraint (e.g. `NAME_PATTERN` → etymology / linguistic_analysis; `STATISTIC` → government databases). Never made it into retrieval or evaluation.++### Why deletion was safe++Never called. `EvidenceEvaluator` uses `EvidenceType.base_confidence` in `base_evidence.py` and per-match score adjustments, bypassing constraint-typed requirements entirely.++### Recovery path++If constraint-aware confidence floors prove useful, add a `constraint_type` kwarg to `EvidenceEvaluator.extract_evidence` and apply the per-type threshold there. Don't restore a standalone class.diff --git a/src/local_deep_research/advanced_search_system/answer_decoding/__init__.py b/src/local_deep_research/advanced_search_system/answer_decoding/__init__.pyindex f16c9762c9..e6fed9798d 100644--- a/src/local_deep_research/advanced_search_system/answer_decoding/__init__.py+++ b/src/local_deep_research/advanced_search_system/answer_decoding/__init__.py@@ -1,5 +1,3 @@"""Answer decoding module for BrowseComp."""-from .browsecomp_answer_decoder import BrowseCompAnswerDecoder--__all__ = ["BrowseCompAnswerDecoder"]+__all__: list[str] = []diff --git a/src/local_deep_research/advanced_search_system/answer_decoding/browsecomp_answer_decoder.py b/src/local_deep_research/advanced_search_system/answer_decoding/browsecomp_answer_decoder.pydeleted file mode 100644index b23a4f8701..0000000000--- a/src/local_deep_research/advanced_search_system/answer_decoding/browsecomp_answer_decoder.py+++ /dev/null@@ -1,421 +0,0 @@-"""-BrowseComp Answer Decoding Pipeline--This module handles encoded answers found in BrowseComp datasets.-Some BrowseComp answers appear to be encoded (e.g., "Y00Qh+ep") and need-decoding to extract the actual answer.--Based on BROWSECOMP_IMPROVEMENT_STRATEGY.md recommendations.-"""--import base64-from loguru import logger-import re-import urllib.parse-from typing import Any, Dict, Optional, Tuple---class BrowseCompAnswerDecoder:- """- Handle encoded BrowseComp answers with multiple decoding schemes.-- Features:- 1. Automatic encoding detection- 2. Multiple decoding scheme support- 3. Answer validation- 4. Fallback to original if decoding fails- """-- def __init__(self):- self.encoding_schemes = [- "base64",- "hex",- "url_encoding",- "rot13",- "caesar_cipher",- ]-- # Patterns that suggest encoded content- self.encoded_patterns = [- r"^[A-Za-z0-9+/]+=*$", # Base64 pattern- r"^[0-9A-Fa-f]+$", # Hex pattern- r"%[0-9A-Fa-f]{2}", # URL encoded- r"^[A-Za-z0-9]{8,}$", # Random string pattern- ]-- def decode_answer(self, raw_answer: str) -> Tuple[str, Optional[str]]:- """- Attempt to decode a potentially encoded answer.-- Args:- raw_answer: The raw answer string that may be encoded-- Returns:- Tuple of (decoded_answer, encoding_scheme_used)- If no decoding works, returns (original_answer, None)- """- if not raw_answer or len(raw_answer.strip()) == 0:- return raw_answer, None-- # Clean the input- clean_answer = raw_answer.strip()-- # Check if answer looks like plaintext first- if self.is_likely_direct_answer(clean_answer):- logger.debug(f"Answer appears to be plaintext: {clean_answer}")- return clean_answer, None-- logger.info(- f"Attempting to decode potentially encoded answer: {clean_answer}"- )-- # Try each encoding scheme- for scheme in self.encoding_schemes:- try:- decoded = self.apply_decoding_scheme(clean_answer, scheme)- if decoded and self.validate_decoded_answer(decoded):- logger.info(- f"Successfully decoded using {scheme}: {clean_answer} -> {decoded}"- )- return decoded, scheme-- except Exception as e:- logger.debug(f"Failed to decode with {scheme}: {e}")- continue-- # No successful decoding- logger.warning(- f"Could not decode answer, returning original: {clean_answer}"- )- return clean_answer, None-- def is_likely_direct_answer(self, answer: str) -> bool:- """- Check if answer looks like plaintext rather than encoded.-- Args:- answer: The answer string to check-- Returns:- True if answer appears to be plaintext- """- # Very short answers are likely plaintext- if len(answer) < 4:- return True-- # Check for common English words- english_indicators = [- "the",- "and",- "or",- "of",- "in",- "to",- "a",- "an",- "company",- "group",- "inc",- "ltd",- "corp",- "corporation",- "person",- "people",- "event",- "year",- "years",- "million",- "billion",- "thousand",- ]-- answer_lower = answer.lower()- if any(word in answer_lower for word in english_indicators):- return True-- # Check for sentence-like structure- if " " in answer and len(answer.split()) > 1:- # Has spaces and multiple words - likely plaintext- return True-- # Check if it matches common answer patterns- common_patterns = [- r"^\d{4}$", # Year- r"^\$?\d+\.?\d*[KMB]?$", # Number/money- r"^[A-Z][a-z]+ [A-Z][a-z]+$", # Name format- r"^\d+%$", # Percentage- ]-- for pattern in common_patterns:- if re.match(pattern, answer):- return True-- # Check character distribution - encoded text often has unusual distribution- char_diversity = (- len(set(answer)) / len(answer) if len(answer) > 0 else 0- )- if char_diversity < 0.3: # Low diversity suggests repetitive/encoded- return False-- # If none of the encoded patterns match, probably plaintext- is_encoded = any(- re.search(pattern, answer) for pattern in self.encoded_patterns- )- return not is_encoded-- def apply_decoding_scheme(self, text: str, scheme: str) -> Optional[str]:- """- Apply a specific decoding scheme to text.-- Args:- text: Text to decode- scheme: Decoding scheme to use-- Returns:- Decoded text or None if decoding fails- """- try:- if scheme == "base64":- return self._decode_base64(text)- if scheme == "hex":- return self._decode_hex(text)- if scheme == "url_encoding":- return self._decode_url(text)- if scheme == "rot13":- return self._decode_rot13(text)- if scheme == "caesar_cipher":- return self._decode_caesar(text)- logger.warning(f"Unknown decoding scheme: {scheme}")- return None-- except Exception as e:- logger.debug(f"Failed to apply {scheme} decoding: {e}")- return None-- def _decode_base64(self, text: str) -> Optional[str]:- """Decode base64 encoded text."""- try:- # Add padding if needed- missing_padding = len(text) % 4- if missing_padding:- text += "=" * (4 - missing_padding)-- decoded_bytes = base64.b64decode(text)- return decoded_bytes.decode("utf-8")-- except Exception:- return None-- def _decode_hex(self, text: str) -> Optional[str]:- """Decode hexadecimal encoded text."""- try:- # Remove any whitespace or non-hex characters- clean_hex = re.sub(r"[^0-9A-Fa-f]", "", text)-- # Must have even length- if len(clean_hex) % 2 != 0:- return None-- decoded_bytes = bytes.fromhex(clean_hex)- return decoded_bytes.decode("utf-8")-- except Exception:- return None-- def _decode_url(self, text: str) -> Optional[str]:- """Decode URL encoded text."""- try:- return urllib.parse.unquote(text)- except Exception:- return None-- def _decode_rot13(self, text: str) -> Optional[str]:- """Decode ROT13 encoded text."""- try:- import codecs-- return codecs.decode(text, "rot13")- except Exception:- return None-- def _decode_caesar(self, text: str) -> Optional[str]:- """- Try different Caesar cipher shifts.- Returns the most English-like result.- """- best_result = None- best_score: float = 0.0-- # Try shifts 1-25- for shift in range(1, 26):- try:- decoded = self._caesar_shift(text, shift)- score = self._english_score(decoded)-- if score > best_score:- best_score = score- best_result = decoded-- except Exception:- continue-- # Only return if it looks reasonably English-like- return best_result if best_score > 0.3 else None-- def _caesar_shift(self, text: str, shift: int) -> str:- """Apply Caesar cipher shift."""- result = []-- for char in text:- if char.isalpha():- # Determine if uppercase or lowercase- start = ord("A") if char.isupper() else ord("a")- # Apply shift with wraparound- shifted = (ord(char) - start + shift) % 26 + start- result.append(chr(shifted))- else:- result.append(char)-- return "".join(result)-- def _english_score(self, text: str) -> float:- """- Score how English-like a text appears.- Simple heuristic based on common letters and words.- """- if not text:- return 0.0-- text_lower = text.lower()-- # Common English letter frequencies (approximate)- common_letters = "etaoinshrdlcumwfgypbvkjxqz"- letter_score = 0- letter_count = 0-- for char in text_lower:- if char.isalpha():- letter_count += 1- # More common letters get higher scores- if char in common_letters[:10]: # Top 10 most common- letter_score += 2- elif char in common_letters[:20]: # Top 20- letter_score += 1-- if letter_count == 0:- return 0.0-- base_score = letter_score / letter_count-- # Bonus for common English words- common_words = [- "the",- "and",- "of",- "to",- "a",- "in",- "is",- "it",- "you",- "that",- ]- word_bonus = sum(1 for word in common_words if word in text_lower)-- return min(1.0, base_score + word_bonus * 0.1)-- def validate_decoded_answer(self, decoded: str) -> bool:- """- Validate that decoded text looks like a reasonable answer.-- Args:- decoded: The decoded text to validate-- Returns:- True if decoded text appears valid- """- if not decoded or len(decoded.strip()) == 0:- return False-- # Remove leading/trailing whitespace- decoded = decoded.strip()-- # Check length - should be reasonable- if len(decoded) < 1 or len(decoded) > 1000:- return False-- # Check for readable characters- printable_count = sum(1 for c in decoded if c.isprintable())- if printable_count / len(decoded) < 0.8: # At least 80% printable- return False-- # Check for control characters (bad sign)- if any(ord(c) < 32 and c not in "\t\n\r" for c in decoded):- return False-- # Check character distribution- char_types = {- "alpha": sum(1 for c in decoded if c.isalpha()),- "digit": sum(1 for c in decoded if c.isdigit()),- "space": sum(1 for c in decoded if c.isspace()),- "punct": sum(- 1 for c in decoded if not c.isalnum() and not c.isspace()- ),- }-- total_chars = len(decoded)-- # Should have some letters- if char_types["alpha"] / total_chars < 0.3:- return False-- # Shouldn't be mostly punctuation- if char_types["punct"] / total_chars > 0.5:- return False-- return True-- def analyze_answer_encoding(self, answer: str) -> Dict[str, Any]:- """- Analyze an answer to determine likely encoding type.-- Returns analysis results for debugging/logging.- """- analysis: Dict[str, Any] = {- "original": answer,- "length": len(answer),- "likely_plaintext": self.is_likely_direct_answer(answer),- "pattern_matches": [],- "attempted_decodings": {},- }-- # Check which patterns match- for i, pattern in enumerate(self.encoded_patterns):- if re.search(pattern, answer):- analysis["pattern_matches"].append(- {- "pattern": pattern,- "type": ["base64", "hex", "url", "random"][i],- }- )-- # Try each decoding scheme- for scheme in self.encoding_schemes:- try:- decoded = self.apply_decoding_scheme(answer, scheme)- is_valid = (- self.validate_decoded_answer(decoded) if decoded else False- )-- analysis["attempted_decodings"][scheme] = {- "decoded": decoded,- "valid": is_valid,- "length": len(decoded) if decoded else 0,- }- except Exception:- logger.exception(f"Error decoding with scheme {scheme}")- analysis["attempted_decodings"][scheme] = {- "error": "Decoding failed"- }-- return analysisdiff --git a/src/local_deep_research/advanced_search_system/constraint_checking/intelligent_constraint_relaxer.py b/src/local_deep_research/advanced_search_system/constraint_checking/intelligent_constraint_relaxer.pydeleted file mode 100644index 060806ccf9..0000000000--- a/src/local_deep_research/advanced_search_system/constraint_checking/intelligent_constraint_relaxer.py+++ /dev/null@@ -1,493 +0,0 @@-"""-Intelligent Constraint Relaxation Strategy--This module implements progressive constraint relaxation to improve BrowseComp-performance when strict constraint matching fails.--Based on BROWSECOMP_IMPROVEMENT_STRATEGY.md recommendations for handling-complex multi-constraint queries that may not have perfect matches.-"""--from loguru import logger-from typing import Dict, List---class IntelligentConstraintRelaxer:- """- Progressive constraint relaxation based on search results and constraint reliability.-- Features:- 1. Maintains essential identifying constraints- 2. Relaxes problematic constraint types first- 3. Creates multiple search attempts with different constraint sets- 4. Preserves constraint importance hierarchy- """-- def __init__(self):- # Constraint priorities (higher = more important, never relax)- self.constraint_priorities = {- "NAME_PATTERN": 10, # Never relax - essential for identification- "EXISTENCE": 9, # Rarely relax - basic entity existence- "LOCATION": 8, # Usually important for identification- "TEMPORAL": 7, # Dates often crucial but sometimes fuzzy- "PROPERTY": 6, # Basic properties, moderately important- "EVENT": 5, # Events can be important but sometimes optional- "STATISTIC": 3, # Often relax - numbers frequently imprecise- "COMPARISON": 1, # Frequently relax - relative comparisons problematic- "RELATIONSHIP": 2, # Often problematic due to complexity- }-- # Minimum constraints to keep for meaningful search- self.min_constraints = 2-- # Constraint relaxation strategies by type- self.relaxation_strategies = {- "STATISTIC": self._relax_statistical_constraint,- "COMPARISON": self._relax_comparison_constraint,- "TEMPORAL": self._relax_temporal_constraint,- "PROPERTY": self._relax_property_constraint,- }-- def relax_constraints_progressively(- self,- constraints: List[object],- candidates_found: List[object],- target_candidates: int = 5,- ) -> List[List[object]]:- """- Generate progressive constraint relaxation sets based on search results.-- Args:- constraints: Original constraint list- candidates_found: Current candidates found- target_candidates: Target number of candidates to find-- Returns:- List of relaxed constraint sets to try- """- if len(candidates_found) >= target_candidates:- logger.debug("Sufficient candidates found, no relaxation needed")- return [constraints] # No relaxation needed-- logger.info(- f"Only {len(candidates_found)} candidates found, generating relaxation strategies"- )-- # Sort constraints by relaxation priority (lowest first)- relaxable_constraints = sorted(- constraints,- key=lambda c: self.constraint_priorities.get(- self._get_constraint_type(c), 5- ),- )-- relaxed_sets = []-- # Strategy 1: Remove least important constraints progressively- for i in range(1, min(len(constraints), 4)): # Max 3 relaxation levels- relaxed_set = relaxable_constraints[- :-i- ] # Remove i lowest priority constraints-- if len(relaxed_set) >= self.min_constraints:- relaxed_sets.append(relaxed_set)- logger.debug(- f"Relaxation level {i}: Removed {i} constraints, {len(relaxed_set)} remaining"- )-- # Strategy 2: Create constraint variations for difficult constraints- variation_sets = self._create_constraint_variations(constraints)- relaxed_sets.extend(variation_sets)-- # Strategy 3: Keep only high-priority constraints- high_priority_constraints = [- c- for c in constraints- if self.constraint_priorities.get(self._get_constraint_type(c), 5)- >= 7- ]-- if len(high_priority_constraints) >= self.min_constraints:- relaxed_sets.append(high_priority_constraints)- logger.debug(- f"High-priority only: {len(high_priority_constraints)} constraints"- )-- # Remove duplicates while preserving order- unique_sets = []- seen_sets = set()-- for constraint_set in relaxed_sets:- # Create a hashable representation- set_signature = tuple(sorted(str(c) for c in constraint_set))- if set_signature not in seen_sets:- seen_sets.add(set_signature)- unique_sets.append(constraint_set)-- logger.info(- f"Generated {len(unique_sets)} unique relaxation strategies"- )- return unique_sets-- def _create_constraint_variations(- self, constraints: List[object]- ) -> List[List[object]]:- """- Create variations of difficult constraints to improve matching.-- Args:- constraints: Original constraints-- Returns:- List of constraint sets with variations- """- variation_sets = []-- for i, constraint in enumerate(constraints):- constraint_type = self._get_constraint_type(constraint)-- if constraint_type in self.relaxation_strategies:- # Create variations for this constraint- variations = self.relaxation_strategies[constraint_type](- constraint- )-- if variations:- # Replace original constraint with each variation- for variation in variations:- new_set = constraints.copy()- new_set[i] = variation- variation_sets.append(new_set)-- return variation_sets-- def _relax_statistical_constraint(self, constraint: object) -> List[object]:- """- Create relaxed variations of statistical constraints.-- Statistical constraints often fail due to:- - Outdated numbers- - Rounding differences- - Different measurement units- """- variations = []- constraint_text = str(constraint)-- # Extract numbers from constraint- import re-- numbers = re.findall(r"\d+(?:\.\d+)?", constraint_text)-- for number_str in numbers:- try:- number = float(number_str)-- # Create range variations (+/- 10%, 20%, 50%)- for tolerance in [0.1, 0.2, 0.5]:- lower = number * (1 - tolerance)- upper = number * (1 + tolerance)-- # Replace exact number with range- relaxed_text = constraint_text.replace(- number_str, f"between {lower:.0f} and {upper:.0f}"- )-- variations.append(- self._create_relaxed_constraint(- constraint, relaxed_text- )- )-- # Create "approximately" version- approx_text = constraint_text.replace(- number_str, f"approximately {number_str}"- )- variations.append(- self._create_relaxed_constraint(constraint, approx_text)- )-- except ValueError:- continue-- return variations[:3] # Limit to avoid too many variations-- def _relax_comparison_constraint(self, constraint: object) -> List[object]:- """- Create relaxed variations of comparison constraints.-- Comparison constraints often fail due to:- - Relative terms are context-dependent- - "Times more" calculations are complex- - Baseline comparisons may be unclear- """- variations = []- constraint_text = str(constraint).lower()-- # Replace strict comparisons with looser ones- relaxation_mappings = {- "times more": "significantly more",- "times larger": "much larger",- "times bigger": "much bigger",- "exactly": "approximately",- "must be": "should be",- "is the": "is among the",- "largest": "one of the largest",- "smallest": "one of the smallest",- "highest": "among the highest",- "lowest": "among the lowest",- }-- for strict_term, relaxed_term in relaxation_mappings.items():- if strict_term in constraint_text:- relaxed_text = constraint_text.replace(- strict_term, relaxed_term- )- variations.append(- self._create_relaxed_constraint(constraint, relaxed_text)- )-- # Remove comparison altogether - focus on the main entity/property- comparison_indicators = [- "more than",- "less than",- "compared to",- "relative to",- ]- for indicator in comparison_indicators:- if indicator in constraint_text:- # Extract the part before the comparison- parts = constraint_text.split(indicator)- if len(parts) > 1:- main_part = parts[0].strip()- variations.append(- self._create_relaxed_constraint(constraint, main_part)- )-- return variations[:3]-- def _relax_temporal_constraint(self, constraint: object) -> List[object]:- """- Create relaxed variations of temporal constraints.-- Temporal constraints often fail due to:- - Exact dates vs approximate dates- - Different calendar systems- - Founding vs incorporation dates- """- variations = []- constraint_text = str(constraint)-- # Extract years- import re-- years = re.findall(r"\b(19\d{2}|20\d{2})\b", constraint_text)-- for year_str in years:- year = int(year_str)-- # Create decade ranges- decade_start = (year // 10) * 10- decade_text = constraint_text.replace(year_str, f"{decade_start}s")- variations.append(- self._create_relaxed_constraint(constraint, decade_text)- )-- # Create +/- ranges- for range_years in [1, 2, 5]:- range_text = constraint_text.replace(- year_str,- f"between {year - range_years} and {year + range_years}",- )- variations.append(- self._create_relaxed_constraint(constraint, range_text)- )-- # Replace exact temporal terms with approximate ones- temporal_relaxations = {- "founded in": "founded around",- "established in": "established around",- "created in": "created around",- "started in": "started around",- "exactly": "approximately",- }-- for exact_term, relaxed_term in temporal_relaxations.items():- if exact_term in constraint_text.lower():- relaxed_text = constraint_text.replace(exact_term, relaxed_term)- variations.append(- self._create_relaxed_constraint(constraint, relaxed_text)- )-- return variations[:3]-- def _relax_property_constraint(self, constraint: object) -> List[object]:- """- Create relaxed variations of property constraints.-- Property constraints can be relaxed by:- - Making specific properties more general- - Allowing alternative phrasings- - Focusing on key attributes- """- variations = []- constraint_text = str(constraint).lower()-- # Make specific properties more general- property_generalizations = {- "multinational": "international",- "conglomerate": "large company",- "corporation": "company",- "subsidiary": "part of",- "headquarters": "based",- "founded": "established",- "specialized": "focused",- "leading": "major",- }-- for specific, general in property_generalizations.items():- if specific in constraint_text:- relaxed_text = constraint_text.replace(specific, general)- variations.append(- self._create_relaxed_constraint(constraint, relaxed_text)- )-- # Remove adjectives to make constraints less specific- adjective_patterns = [- r"\b(very|extremely|highly|most|largest|biggest|smallest)\s+",- r"\b(major|minor|primary|secondary|main|key)\s+",- ]-- for pattern in adjective_patterns:- import re-- if re.search(pattern, constraint_text):- relaxed_text = re.sub(pattern, "", constraint_text)- variations.append(- self._create_relaxed_constraint(constraint, relaxed_text)- )-- return variations[:2]-- def _create_relaxed_constraint(- self, original_constraint: object, relaxed_text: str- ) -> object:- """- Create a new constraint object with relaxed text.-- This is a helper method that preserves the constraint structure- while updating the constraint value/text.- """- # Try to create a copy of the constraint with updated text- if hasattr(original_constraint, "__dict__"):- # Create a copy of the constraint object- import copy-- relaxed_constraint = copy.deepcopy(original_constraint)-- # Update the constraint value/description- if hasattr(relaxed_constraint, "value"):- relaxed_constraint.value = relaxed_text- elif hasattr(relaxed_constraint, "description"):- relaxed_constraint.description = relaxed_text- elif hasattr(relaxed_constraint, "text"):- relaxed_constraint.text = relaxed_text-- return relaxed_constraint- # If we can't copy the constraint, return a simple string representation- return relaxed_text-- def _get_constraint_type(self, constraint: object) -> str:- """Extract constraint type from constraint object."""- if hasattr(constraint, "type"):- if hasattr(constraint.type, "value"):- return constraint.type.value- return str(constraint.type)- if hasattr(constraint, "constraint_type"):- return constraint.constraint_type- # Try to infer from constraint text- constraint_text = str(constraint).lower()-- if any(- word in constraint_text for word in ["name", "called", "known as"]- ):- return "NAME_PATTERN"- if any(- word in constraint_text for word in ["location", "country", "city"]- ):- return "LOCATION"- if any(- word in constraint_text for word in ["year", "date", "when", "time"]- ):- return "TEMPORAL"- if any(- word in constraint_text for word in ["number", "count", "amount"]- ):- return "STATISTIC"- if any(- word in constraint_text- for word in ["event", "happened", "occurred"]- ):- return "EVENT"- if any(- word in constraint_text- for word in ["than", "more", "less", "compared"]- ):- return "COMPARISON"- return "PROPERTY"-- def analyze_relaxation_impact(- self,- original_constraints: List[object],- relaxed_constraints: List[object],- ) -> Dict:- """- Analyze the impact of constraint relaxation.-- Returns analysis of what was changed and the expected impact.- """- analysis = {- "original_count": len(original_constraints),- "relaxed_count": len(relaxed_constraints),- "constraints_removed": len(original_constraints)- - len(relaxed_constraints),- "constraint_changes": [],- "priority_impact": "low",- "recommendation": "",- }-- # Check what types of constraints were removed/modified- original_types = [- self._get_constraint_type(c) for c in original_constraints- ]- relaxed_types = [- self._get_constraint_type(c) for c in relaxed_constraints- ]-- removed_types = []- for orig_type in original_types:- if orig_type not in relaxed_types:- removed_types.append(orig_type)-- # Assess impact based on what was removed- high_impact_types = {"NAME_PATTERN", "EXISTENCE", "LOCATION"}- medium_impact_types = {"TEMPORAL", "EVENT", "PROPERTY"}-- if any(t in removed_types for t in high_impact_types):- analysis["priority_impact"] = "high"- analysis["recommendation"] = (- "High-priority constraints removed. Results may be less accurate."- )- elif any(t in removed_types for t in medium_impact_types):- analysis["priority_impact"] = "medium"- analysis["recommendation"] = (- "Medium-priority constraints removed. Check results carefully."- )- else:- analysis["priority_impact"] = "low"- analysis["recommendation"] = (- "Low-priority constraints removed. Results should remain accurate."- )-- analysis["removed_constraint_types"] = removed_types-- return analysisdiff --git a/src/local_deep_research/advanced_search_system/evidence/__init__.py b/src/local_deep_research/advanced_search_system/evidence/__init__.pyindex 4ec86451b9..259018737c 100644--- a/src/local_deep_research/advanced_search_system/evidence/__init__.py+++ b/src/local_deep_research/advanced_search_system/evidence/__init__.py@@ -2,11 +2,9 @@from .base_evidence import Evidence, EvidenceTypefrom .evaluator import EvidenceEvaluator-from .requirements import EvidenceRequirements__all__ = ["Evidence","EvidenceEvaluator",- "EvidenceRequirements","EvidenceType",]diff --git a/src/local_deep_research/advanced_search_system/evidence/requirements.py b/src/local_deep_research/advanced_search_system/evidence/requirements.pydeleted file mode 100644index 3981444394..0000000000--- a/src/local_deep_research/advanced_search_system/evidence/requirements.py+++ /dev/null@@ -1,122 +0,0 @@-"""-Evidence requirements for different constraint types.-"""--from typing import Dict, List--from ..constraints.base_constraint import ConstraintType---class EvidenceRequirements:- """Define evidence requirements for different constraint types."""-- @staticmethod- def get_requirements(- constraint_type: ConstraintType,- ) -> Dict[str, List[str]]:- """Get evidence requirements for a constraint type.-- Args:- constraint_type: The type of constraint-- Returns:- Dictionary of evidence types and their sources- """- requirements = {- ConstraintType.PROPERTY: {- "preferred": ["direct_statement", "official_record"],- "acceptable": ["research_finding", "inference"],- "sources": [- "scientific papers",- "official documents",- "encyclopedias",- ],- },- ConstraintType.NAME_PATTERN: {- "preferred": ["direct_statement", "linguistic_analysis"],- "acceptable": ["correlation", "inference"],- "sources": [- "etymology sources",- "naming databases",- "historical records",- ],- },- ConstraintType.EVENT: {- "preferred": ["news_report", "official_record"],- "acceptable": ["testimonial", "correlation"],- "sources": [- "news archives",- "government reports",- "witness accounts",- ],- },- ConstraintType.STATISTIC: {- "preferred": ["statistical_data", "official_record"],- "acceptable": ["research_finding"],- "sources": [- "government databases",- "research papers",- "official reports",- ],- },- ConstraintType.TEMPORAL: {- "preferred": ["official_record", "news_report"],- "acceptable": ["historical_record", "inference"],- "sources": ["archives", "newspapers", "official timelines"],- },- ConstraintType.LOCATION: {- "preferred": ["geographical_data", "official_record"],- "acceptable": ["mapping_data", "inference"],- "sources": [- "geographical surveys",- "maps",- "location databases",- ],- },- ConstraintType.COMPARISON: {- "preferred": ["statistical_comparison", "research_finding"],- "acceptable": ["inference", "correlation"],- "sources": [- "comparative studies",- "statistical analyses",- "research papers",- ],- },- ConstraintType.EXISTENCE: {- "preferred": ["direct_statement", "official_record"],- "acceptable": ["news_report", "inference"],- "sources": [- "official registries",- "databases",- "authoritative sources",- ],- },- }-- return requirements.get(- constraint_type,- {- "preferred": ["direct_statement"],- "acceptable": ["inference"],- "sources": ["general sources"],- },- )-- @staticmethod- def get_minimum_confidence(constraint_type: ConstraintType) -> float:- """Get minimum confidence required for constraint type.-- Args:- constraint_type: The type of constraint-- Returns:- Minimum confidence threshold- """- thresholds = {- ConstraintType.STATISTIC: 0.8, # High accuracy needed- ConstraintType.EVENT: 0.7, # Moderate accuracy- ConstraintType.PROPERTY: 0.6, # Some flexibility- ConstraintType.NAME_PATTERN: 0.5, # More interpretive- }-- return thresholds.get(constraint_type, 0.6)diff --git a/src/local_deep_research/advanced_search_system/query_generation/adaptive_query_generator.py b/src/local_deep_research/advanced_search_system/query_generation/adaptive_query_generator.pydeleted file mode 100644index 9d786097f2..0000000000--- a/src/local_deep_research/advanced_search_system/query_generation/adaptive_query_generator.py+++ /dev/null@@ -1,404 +0,0 @@-"""-Adaptive query generation system for improved search performance.-"""--from collections import defaultdict-from dataclasses import dataclass-from typing import Dict, List, Optional, Set, Tuple--from langchain_core.language_models import BaseChatModel--from ...utilities.search_utilities import remove_think_tags-from ..constraints.base_constraint import Constraint, ConstraintType---@dataclass-class QueryPattern:- """Represents a successful query pattern."""-- template: str- constraint_types: List[ConstraintType]- success_rate: float- example_queries: List[str]- discovered_entities: Set[str]---class AdaptiveQueryGenerator:- """- Generates search queries that adapt based on past performance.-- Features:- 1. Pattern learning from successful queries- 2. Semantic expansion for broader coverage- 3. Constraint combination optimization- 4. Failure recovery strategies- """-- def __init__(self, model: BaseChatModel):- """Initialize the adaptive query generator."""- self.model = model- self.successful_patterns: List[QueryPattern] = []- self.failed_queries: Set[str] = set()- self.semantic_expansions: Dict[str, List[str]] = {}- self.constraint_combinations: Dict[- Tuple[ConstraintType, ...], float- ] = defaultdict(float)-- # Initialize default patterns- self._initialize_default_patterns()-- def _initialize_default_patterns(self):- """Initialize with proven query patterns."""- default_patterns = [- QueryPattern(- template='"{entity}" {property} {location}',- constraint_types=[- ConstraintType.NAME_PATTERN,- ConstraintType.PROPERTY,- ConstraintType.LOCATION,- ],- success_rate=0.7,- example_queries=['"mountain" formed ice age Colorado'],- discovered_entities=set(),- ),- QueryPattern(- template="{event} {temporal} {statistic}",- constraint_types=[- ConstraintType.EVENT,- ConstraintType.TEMPORAL,- ConstraintType.STATISTIC,- ],- success_rate=0.6,- example_queries=["accident 2000-2021 statistics"],- discovered_entities=set(),- ),- QueryPattern(- template='"{name_pattern}" AND {comparison} {value}',- constraint_types=[- ConstraintType.NAME_PATTERN,- ConstraintType.COMPARISON,- ],- success_rate=0.65,- example_queries=['"body part" AND "84.5 times" ratio'],- discovered_entities=set(),- ),- ]- self.successful_patterns.extend(default_patterns)-- def generate_query(- self, constraints: List[Constraint], context: Optional[Dict] = None- ) -> str:- """Generate an adaptive query based on constraints and context."""- # Try pattern-based generation first- pattern_query = self._generate_from_patterns(constraints)- if pattern_query and pattern_query not in self.failed_queries:- return pattern_query-- # Try semantic expansion- expanded_query = self._generate_with_expansion(constraints)- if expanded_query and expanded_query not in self.failed_queries:- return expanded_query-- # Fall back to LLM-based generation- return self._generate_with_llm(constraints, context)-- def _generate_from_patterns(- self, constraints: List[Constraint]- ) -> Optional[str]:- """Generate query using learned patterns."""- constraint_types = [c.type for c in constraints]-- # Find matching patterns- matching_patterns = []- for pattern in self.successful_patterns:- if all(t in constraint_types for t in pattern.constraint_types):- matching_patterns.append(pattern)-- if not matching_patterns:- return None-- # Use the highest success rate pattern- best_pattern = max(matching_patterns, key=lambda p: p.success_rate)-- # Fill in the template- template_vars = {}- for constraint in constraints:- if constraint.type == ConstraintType.NAME_PATTERN:- template_vars["name_pattern"] = constraint.value- template_vars["entity"] = constraint.value- elif constraint.type == ConstraintType.PROPERTY:- template_vars["property"] = constraint.value- elif constraint.type == ConstraintType.LOCATION:- template_vars["location"] = constraint.value- elif constraint.type == ConstraintType.EVENT:- template_vars["event"] = constraint.value- elif constraint.type == ConstraintType.TEMPORAL:- template_vars["temporal"] = constraint.value- elif constraint.type == ConstraintType.STATISTIC:- template_vars["statistic"] = constraint.value- elif constraint.type == ConstraintType.COMPARISON:- template_vars["comparison"] = f'"{constraint.value}"'- template_vars["value"] = constraint.value-- try:- return best_pattern.template.format(**template_vars)- except KeyError:- return None-- def _generate_with_expansion(- self, constraints: List[Constraint]- ) -> Optional[str]:- """Generate query with semantic expansion."""- expanded_terms = []-- for constraint in constraints:- # Get expansions for this value- if constraint.value not in self.semantic_expansions:- self.semantic_expansions[constraint.value] = (- self._get_semantic_expansions(- constraint.value, constraint.type- )- )-- expansions = self.semantic_expansions[constraint.value]- if expansions:- # Use OR to include expansions- expanded = (- f"({constraint.value} OR {' OR '.join(expansions[:2])})"- )- expanded_terms.append(expanded)- else:- expanded_terms.append(f'"{constraint.value}"')-- return " AND ".join(expanded_terms)-- def _get_semantic_expansions(- self, term: str, constraint_type: ConstraintType- ) -> List[str]:- """Get semantic expansions for a term."""- prompt = f"""-Generate 3 alternative phrases or related terms for "{term}" in the context of {constraint_type.value}.--These should be:-1. Synonyms or near-synonyms-2. Related concepts-3. Alternative phrasings--Return only the terms, one per line.-"""-- response = self.model.invoke(prompt)- expansions = [- line.strip()- for line in remove_think_tags(response.content).strip().split("\n")- if line.strip()- ]-- return [f'"{exp}"' for exp in expansions[:3]]-- def _generate_with_llm(- self, constraints: List[Constraint], context: Optional[Dict] = None- ) -> str:- """Generate query using LLM with context awareness."""- constraint_desc = self._format_constraints(constraints)-- context_info = ""- if context:- if "failed_queries" in context:- context_info += "\nFailed queries to avoid:\n" + "\n".join(- context["failed_queries"][:3]- )- if "successful_queries" in context:- context_info += "\nSuccessful query patterns:\n" + "\n".join(- context["successful_queries"][:3]- )-- prompt = f"""-Create an effective search query for these constraints:--{constraint_desc}-{context_info}--Guidelines:-1. Focus on finding specific named entities-2. Use operators (AND, OR, quotes) effectively-3. Combine constraints strategically-4. Make the query neither too broad nor too narrow--Return only the search query.-"""-- response = self.model.invoke(prompt)- return remove_think_tags(response.content).strip()-- def update_patterns(- self,- query: str,- constraints: List[Constraint],- success: bool,- entities_found: List[str],- ):- """Update patterns based on query performance."""- if success and entities_found:- # Extract pattern from successful query- pattern = self._extract_pattern(query, constraints)- if pattern:- # Update or add pattern- existing = next(- (- p- for p in self.successful_patterns- if p.template == pattern.template- ),- None,- )-- if existing:- existing.success_rate = (existing.success_rate + 1.0) / 2- existing.example_queries.append(query)- existing.discovered_entities.update(entities_found)- else:- self.successful_patterns.append(pattern)-- # Update constraint combinations- constraint_types = tuple(sorted(c.type for c in constraints))- self.constraint_combinations[constraint_types] += 1- else:- self.failed_queries.add(query)-- def _extract_pattern(- self, query: str, constraints: List[Constraint]- ) -> Optional[QueryPattern]:- """Extract a reusable pattern from a successful query."""- # Simple pattern extraction - could be made more sophisticated- pattern = query-- # Replace specific values with placeholders- for constraint in constraints:- if constraint.value in query:- placeholder = f"{{{constraint.type.value}}}"- pattern = pattern.replace(constraint.value, placeholder)-- # Only create pattern if it has placeholders- if "{" in pattern:- return QueryPattern(- template=pattern,- constraint_types=[c.type for c in constraints],- success_rate=1.0,- example_queries=[query],- discovered_entities=set(),- )-- return None-- def _format_constraints(self, constraints: List[Constraint]) -> str:- """Format constraints for prompts."""- formatted = []- for c in constraints:- formatted.append(- f"- {c.type.value}: {c.description} [value: {c.value}]"- )- return "\n".join(formatted)-- def generate_fallback_queries(- self, original_query: str, constraints: List[Constraint]- ) -> List[str]:- """Generate fallback queries when the original fails."""- fallback_queries = []-- # 1. Simplified query (fewer constraints)- if len(constraints) > 2:- priority_constraints = sorted(- constraints, key=lambda c: c.weight, reverse=True- )[:2]- simplified = self.generate_query(priority_constraints)- fallback_queries.append(simplified)-- # 2. Broadened query (with OR instead of AND)- terms = [f'"{c.value}"' for c in constraints]- broadened = " OR ".join(terms)- fallback_queries.append(broadened)-- # 3. Decomposed queries (one constraint at a time)- for constraint in constraints[:3]:- single_query = self._generate_single_constraint_query(constraint)- fallback_queries.append(single_query)-- # 4. Alternative phrasing- alt_prompt = f"""-The query "{original_query}" failed. Create 2 alternative queries with different phrasing.--Constraints to satisfy:-{self._format_constraints(constraints)}--Return only the queries, one per line.-"""-- response = self.model.invoke(alt_prompt)- alt_queries = [- line.strip()- for line in remove_think_tags(response.content).strip().split("\n")- if line.strip()- ]- fallback_queries.extend(alt_queries)-- # Remove duplicates and failed queries- unique_fallbacks = []- for q in fallback_queries:- if q and q not in self.failed_queries and q not in unique_fallbacks:- unique_fallbacks.append(q)-- return unique_fallbacks[:5]-- def _generate_single_constraint_query(self, constraint: Constraint) -> str:- """Generate a query for a single constraint."""- type_specific_templates = {- ConstraintType.NAME_PATTERN: '"{value}" names list',- ConstraintType.LOCATION: '"{value}" places locations',- ConstraintType.EVENT: '"{value}" incidents accidents',- ConstraintType.PROPERTY: 'things with "{value}" property',- ConstraintType.STATISTIC: '"{value}" statistics data',- ConstraintType.TEMPORAL: "events in {value}",- ConstraintType.COMPARISON: '"{value}" comparison ratio',- ConstraintType.EXISTENCE: 'has "{value}" feature',- }-- template = type_specific_templates.get(constraint.type, '"{value}"')-- return template.format(value=constraint.value)-- def optimize_constraint_combinations(- self, constraints: List[Constraint]- ) -> List[List[Constraint]]:- """Optimize constraint combinations based on past success."""- combinations = []-- # Sort constraint combinations by success rate- sorted_combos = sorted(- self.constraint_combinations.items(),- key=lambda x: x[1],- reverse=True,- )-- # Try successful combinations first- for combo_types, _ in sorted_combos:- matching_constraints = []- for ctype in combo_types:- matching = [c for c in constraints if c.type == ctype]- if matching:- matching_constraints.append(matching[0])-- if len(matching_constraints) == len(combo_types):- combinations.append(matching_constraints)-- # Add individual constraints- combinations.extend([[c] for c in constraints])-- # Add pairs not yet tried- for i in range(len(constraints)):- for j in range(i + 1, len(constraints)):- pair = [constraints[i], constraints[j]]- if pair not in combinations:- combinations.append(pair)-- return combinations[:10] # Limit to top 10diff --git a/src/local_deep_research/advanced_search_system/search_optimization/cross_constraint_manager.py b/src/local_deep_research/advanced_search_system/search_optimization/cross_constraint_manager.pydeleted file mode 100644index bc479e87a2..0000000000--- a/src/local_deep_research/advanced_search_system/search_optimization/cross_constraint_manager.py+++ /dev/null@@ -1,624 +0,0 @@-"""-Cross-constraint search optimization manager.-"""--import itertools-from collections import defaultdict-from dataclasses import dataclass, field-from typing import Dict, List, Optional, Set, Tuple--from langchain_core.language_models import BaseChatModel--from ...utilities.search_utilities import remove_think_tags-from ..candidates.base_candidate import Candidate-from ..constraints.base_constraint import Constraint---@dataclass-class ConstraintRelationship:- """Represents a relationship between constraints."""-- constraint1_id: str- constraint2_id: str- relationship_type: str # 'complementary', 'dependent', 'exclusive'- strength: float # 0.0 to 1.0- evidence: List[str] = field(default_factory=list)---@dataclass-class ConstraintCluster:- """Group of related constraints that should be searched together."""-- constraints: List[Constraint]- cluster_type: str # 'temporal', 'spatial', 'causal', 'descriptive'- coherence_score: float- search_queries: List[str] = field(default_factory=list)---class CrossConstraintManager:- """- Manages cross-constraint relationships and optimizes multi-constraint searches.-- Key features:- 1. Identifies relationships between constraints- 2. Clusters related constraints for efficient searching- 3. Generates cross-constraint validation queries- 4. Tracks cross-constraint evidence patterns- """-- def __init__(self, model: BaseChatModel):- """Initialize the cross-constraint manager."""- self.model = model- self.relationships: Dict[Tuple[str, str], ConstraintRelationship] = {}- self.clusters: List[ConstraintCluster] = []- self.cross_validation_patterns: Dict[str, List[Dict]] = defaultdict(- list- )- self.constraint_graph: Dict[str, Set[str]] = defaultdict(set)-- def analyze_constraint_relationships(- self, constraints: List[Constraint]- ) -> Dict[Tuple[str, str], ConstraintRelationship]:- """Analyze relationships between constraints."""- relationships = {}-- # Analyze each pair of constraints- for c1, c2 in itertools.combinations(constraints, 2):- relationship = self._analyze_pair(c1, c2)- if (- relationship.strength > 0.3- ): # Only keep meaningful relationships- key = (c1.id, c2.id)- relationships[key] = relationship-- # Update constraint graph- self.constraint_graph[c1.id].add(c2.id)- self.constraint_graph[c2.id].add(c1.id)-- self.relationships.update(relationships)- return relationships-- def _analyze_pair(- self, c1: Constraint, c2: Constraint- ) -> ConstraintRelationship:- """Analyze the relationship between two constraints."""- prompt = f"""-Analyze the relationship between these two constraints:--Constraint 1: {c1.description} (Type: {c1.type.value})-Constraint 2: {c2.description} (Type: {c2.type.value})--Determine:-1. Relationship type (complementary, dependent, exclusive, or none)-2. Strength of relationship (0.0 to 1.0)-3. Brief explanation--Format:-Type: [relationship_type]-Strength: [0.0-1.0]-Evidence: [explanation]-"""-- response = self.model.invoke(prompt)- content = remove_think_tags(response.content)-- # Parse response- rel_type = "none"- strength = 0.0- evidence = []-- for line in content.strip().split("\n"):- if line.startswith("Type:"):- rel_type = line.split(":", 1)[1].strip().lower()- elif line.startswith("Strength:"):- try:- strength = float(line.split(":", 1)[1].strip())- except ValueError:- strength = 0.0- elif line.startswith("Evidence:"):- evidence.append(line.split(":", 1)[1].strip())-- return ConstraintRelationship(- constraint1_id=c1.id,- constraint2_id=c2.id,- relationship_type=rel_type,- strength=strength,- evidence=evidence,- )-- def create_constraint_clusters(- self, constraints: List[Constraint]- ) -> List[ConstraintCluster]:- """Create clusters of related constraints."""- # First, analyze relationships if not done- if not self.relationships:- self.analyze_constraint_relationships(constraints)-- # Create clusters using different strategies- clusters = []-- # 1. Type-based clusters- type_groups = defaultdict(list)- for c in constraints:- type_groups[c.type].append(c)-- for group in type_groups.values():- if len(group) > 1:- cluster = ConstraintCluster(- constraints=group,- cluster_type="type_based",- coherence_score=0.7,- )- clusters.append(cluster)-- # 2. Relationship-based clusters- strong_relationships = [- rel for rel in self.relationships.values() if rel.strength > 0.6- ]-- relationship_clusters = self._create_relationship_clusters(- constraints, strong_relationships- )- clusters.extend(relationship_clusters)-- # 3. Semantic clusters- semantic_clusters = self._create_semantic_clusters(constraints)- clusters.extend(semantic_clusters)-- # Remove duplicate clusters- unique_clusters = self._deduplicate_clusters(clusters)-- self.clusters = unique_clusters- return unique_clusters-- def _create_relationship_clusters(- self,- constraints: List[Constraint],- relationships: List[ConstraintRelationship],- ) -> List[ConstraintCluster]:- """Create clusters based on strong relationships."""- clusters = []- processed = set()-- # Build adjacency list- adj_list = defaultdict(list)- for rel in relationships:- adj_list[rel.constraint1_id].append(rel.constraint2_id)- adj_list[rel.constraint2_id].append(rel.constraint1_id)-- # Find connected components- for constraint in constraints:- if constraint.id in processed:- continue-- # BFS to find connected component- component = []- queue = [constraint.id]- visited = {constraint.id}-- while queue:- current_id = queue.pop(0)- current = next(- (c for c in constraints if c.id == current_id), None- )- if current:- component.append(current)- processed.add(current_id)-- for neighbor_id in adj_list[current_id]:- if neighbor_id not in visited:- visited.add(neighbor_id)- queue.append(neighbor_id)-- if len(component) > 1:- cluster = ConstraintCluster(- constraints=component,- cluster_type="relationship_based",- coherence_score=self._calculate_cluster_coherence(- component- ),- )- clusters.append(cluster)-- return clusters-- def _create_semantic_clusters(- self, constraints: List[Constraint]- ) -> List[ConstraintCluster]:- """Create clusters based on semantic similarity."""- prompt = f"""-Group these constraints into semantic clusters based on their meaning and intent:--{self._format_constraints_for_clustering(constraints)}--For each cluster:-1. List the constraint IDs-2. Describe the cluster theme-3. Rate coherence (0.0-1.0)--Format:-CLUSTER_1:-Constraints: [id1, id2, ...]-Theme: [description]-Coherence: [0.0-1.0]-"""-- response = self.model.invoke(prompt)- content = remove_think_tags(response.content)-- clusters = []- current_cluster = {}-- for line in content.strip().split("\n"):- line = line.strip()-- if line.startswith("CLUSTER_"):- if current_cluster and "constraints" in current_cluster:- # Create cluster from previous data- constraint_ids = current_cluster["constraints"]- cluster_constraints = [- c for c in constraints if c.id in constraint_ids- ]-- if len(cluster_constraints) > 1:- cluster = ConstraintCluster(- constraints=cluster_constraints,- cluster_type="semantic",- coherence_score=float(- current_cluster.get("coherence", 0.5)- ),- )- clusters.append(cluster)-- current_cluster = {}-- elif line.startswith("Constraints:"):- ids_str = line.split(":", 1)[1].strip()- # Extract IDs from various formats- import re-- ids = re.findall(r"c\d+", ids_str)- current_cluster["constraints"] = ids-- elif line.startswith("Theme:"):- current_cluster["theme"] = line.split(":", 1)[1].strip()-- elif line.startswith("Coherence:"):- try:- current_cluster["coherence"] = float(- line.split(":", 1)[1].strip()- )- except ValueError:- current_cluster["coherence"] = 0.5-- # Don't forget the last cluster- if current_cluster and "constraints" in current_cluster:- constraint_ids = current_cluster["constraints"]- cluster_constraints = [- c for c in constraints if c.id in constraint_ids- ]-- if len(cluster_constraints) > 1:- cluster = ConstraintCluster(- constraints=cluster_constraints,- cluster_type="semantic",- coherence_score=float(- current_cluster.get("coherence", 0.5)- ),- )- clusters.append(cluster)-- return clusters-- def generate_cross_constraint_queries(- self, cluster: ConstraintCluster- ) -> List[str]:- """Generate optimized queries for a constraint cluster."""- queries = []-- # 1. Combined query (all constraints)- combined_query = self._generate_combined_query(cluster.constraints)- queries.append(combined_query)-- # 2. Progressive queries (build up constraints)- progressive_queries = self._generate_progressive_queries(- cluster.constraints- )- queries.extend(progressive_queries)-- # 3. Intersection queries (shared aspects)- intersection_query = self._generate_intersection_query(- cluster.constraints- )- if intersection_query:- queries.append(intersection_query)-- # 4. Validation queries (cross-check)- validation_queries = self._generate_validation_queries(- cluster.constraints- )- queries.extend(validation_queries)-- # Store queries in cluster- cluster.search_queries = queries-- return queries-- def _generate_combined_query(self, constraints: List[Constraint]) -> str:- """Generate a query combining all constraints."""- prompt = f"""-Create a search query that finds entities satisfying ALL of these related constraints:--{self._format_constraints_for_query(constraints)}--The query should:-1. Efficiently combine all constraints-2. Use appropriate operators (AND, OR)-3. Focus on finding specific entities-4. Be neither too broad nor too narrow--Return only the search query.-"""-- response = self.model.invoke(prompt)- return remove_think_tags(response.content).strip()-- def _generate_progressive_queries(- self, constraints: List[Constraint]- ) -> List[str]:- """Generate queries that progressively add constraints."""- queries = []-- # Sort by weight/importance- sorted_constraints = sorted(- constraints, key=lambda c: c.weight, reverse=True- )-- # Build up constraints- for i in range(2, min(len(sorted_constraints) + 1, 4)):- subset = sorted_constraints[:i]- query = self._generate_combined_query(subset)- queries.append(query)-- return queries-- def _generate_intersection_query(- self, constraints: List[Constraint]- ) -> Optional[str]:- """Generate a query focused on the intersection of constraints."""- if len(constraints) < 2:- return None-- prompt = f"""-Identify the common theme or intersection among these constraints:--{self._format_constraints_for_query(constraints)}--Create a search query that targets this common aspect.-Return only the search query, or 'NONE' if no clear intersection exists.-"""-- response = self.model.invoke(prompt)- query = remove_think_tags(response.content).strip()-- if query.upper() == "NONE":- return None-- return query-- def _generate_validation_queries(- self, constraints: List[Constraint]- ) -> List[str]:- """Generate queries for cross-validation."""- queries = []-- # Pairwise validation queries- for c1, c2 in itertools.combinations(constraints[:3], 2):- prompt = f"""-Create a validation query that checks if an entity satisfies both:-- {c1.description}-- {c2.description}--Return only the search query.-"""-- response = self.model.invoke(prompt)- query = remove_think_tags(response.content).strip()- queries.append(query)-- return queries[:2] # Limit to 2 validation queries-- def validate_candidate_across_constraints(- self, candidate: Candidate, constraints: List[Constraint]- ) -> Dict[str, float]:- """Validate a candidate across multiple constraints simultaneously."""- validation_scores = {}-- # Find relevant clusters for these constraints- relevant_clusters = [- cluster- for cluster in self.clusters- if any(c in cluster.constraints for c in constraints)- ]-- for cluster in relevant_clusters:- # Use cluster-specific queries for validation- cluster_score = self._validate_with_cluster(candidate, cluster)-- # Update individual constraint scores- for constraint in cluster.constraints:- if constraint in constraints:- validation_scores[constraint.id] = max(- validation_scores.get(constraint.id, 0.0), cluster_score- )-- # Additional pairwise validation- for c1, c2 in itertools.combinations(constraints, 2):- if (c1.id, c2.id) in self.relationships:- rel = self.relationships[(c1.id, c2.id)]- if rel.relationship_type == "complementary":- # Boost scores for complementary constraints- pair_score = self._validate_pair(candidate, c1, c2)- validation_scores[c1.id] = max(- validation_scores.get(c1.id, 0.0), pair_score- )- validation_scores[c2.id] = max(- validation_scores.get(c2.id, 0.0), pair_score- )-- return validation_scores-- def _validate_with_cluster(- self, candidate: Candidate, cluster: ConstraintCluster- ) -> float:- """Validate candidate using cluster-based approach."""- if not cluster.search_queries:- cluster.search_queries = self.generate_cross_constraint_queries(- cluster- )-- # Use the most comprehensive query- validation_query = cluster.search_queries[0]-- prompt = f"""-Does "{candidate.name}" satisfy this multi-constraint query:-Query: {validation_query}--Constraints being checked:-{self._format_constraints_for_query(cluster.constraints)}--Provide a confidence score (0.0-1.0) based on how well the candidate matches.--Format:-Score: [0.0-1.0]-Explanation: [brief explanation]-"""-- response = self.model.invoke(prompt)- content = remove_think_tags(response.content)-- # Parse score- score = 0.0- for line in content.strip().split("\n"):- if line.startswith("Score:"):- try:- score = float(line.split(":", 1)[1].strip())- except ValueError:- score = 0.0- break-- return score-- def _validate_pair(- self, candidate: Candidate, c1: Constraint, c2: Constraint- ) -> float:- """Validate candidate against a pair of constraints."""- prompt = f"""-Evaluate if "{candidate.name}" satisfies BOTH constraints:--1. {c1.description} (Type: {c1.type.value})-2. {c2.description} (Type: {c2.type.value})--Consider how these constraints relate to each other and whether the candidate satisfies both.--Provide a confidence score (0.0-1.0).--Format:-Score: [0.0-1.0]-"""-- response = self.model.invoke(prompt)- content = remove_think_tags(response.content)-- # Parse score- score = 0.0- for line in content.strip().split("\n"):- if line.startswith("Score:"):- try:- score = float(line.split(":", 1)[1].strip())- except ValueError:- score = 0.0- break-- return score-- def _calculate_cluster_coherence(- self, constraints: List[Constraint]- ) -> float:- """Calculate coherence score for a constraint cluster."""- if len(constraints) < 2:- return 0.0-- # Calculate based on relationship strengths- total_strength = 0.0- pair_count = 0-- for c1, c2 in itertools.combinations(constraints, 2):- key = (c1.id, c2.id)- if key in self.relationships:- total_strength += self.relationships[key].strength- pair_count += 1-- if pair_count == 0:- return 0.5 # Default coherence-- average_strength = total_strength / pair_count-- # Adjust for cluster size (larger clusters with high average strength are better)- size_factor = min(len(constraints) / 5.0, 1.0)-- return average_strength * (0.7 + 0.3 * size_factor)-- def _deduplicate_clusters(- self, clusters: List[ConstraintCluster]- ) -> List[ConstraintCluster]:- """Remove duplicate clusters."""- unique_clusters = []- seen_sets = []-- for cluster in clusters:- constraint_set = {c.id for c in cluster.constraints}-- # Check if we've seen this set- is_duplicate = False- for seen_set in seen_sets:- if constraint_set == seen_set:- is_duplicate = True- break-- if not is_duplicate:- unique_clusters.append(cluster)- seen_sets.append(constraint_set)-- return unique_clusters-- def _format_constraints_for_clustering(- self, constraints: List[Constraint]- ) -> str:- """Format constraints for clustering prompt."""- formatted = []- for c in constraints:- formatted.append(- f"{c.id}: {c.description} (Type: {c.type.value}, Weight: {c.weight})"- )- return "\n".join(formatted)-- def _format_constraints_for_query(- self, constraints: List[Constraint]- ) -> str:- """Format constraints for query generation."""- formatted = []- for c in constraints:- formatted.append(f"- {c.description} [{c.type.value}]")- return "\n".join(formatted)-- def optimize_search_order(- self, clusters: List[ConstraintCluster]- ) -> List[ConstraintCluster]:- """Optimize the order in which clusters should be searched."""- # Sort by coherence and cluster size- return sorted(- clusters,- key=lambda c: c.coherence_score * len(c.constraints),- reverse=True,- )diff --git a/src/local_deep_research/advanced_search_system/source_management/diversity_manager.py b/src/local_deep_research/advanced_search_system/source_management/diversity_manager.pydeleted file mode 100644index e2116f5d2e..0000000000--- a/src/local_deep_research/advanced_search_system/source_management/diversity_manager.py+++ /dev/null@@ -1,613 +0,0 @@-"""-Source diversity management for improved evidence quality.-"""--import re-from collections import defaultdict-from dataclasses import dataclass, field-from datetime import datetime, UTC-from typing import Any, Dict, List, Optional, Set, Tuple--from langchain_core.language_models import BaseChatModel--from ..constraints.base_constraint import Constraint, ConstraintType---@dataclass-class SourceProfile:- """Profile of a source for diversity tracking."""-- url: str- domain: str- source_type: str # 'academic', 'news', 'government', 'wiki', 'blog', etc.- credibility_score: float- specialties: List[str] = field(default_factory=list)- temporal_coverage: Optional[Tuple[datetime, datetime]] = None- geographic_focus: Optional[str] = None- evidence_count: int = 0- last_accessed: Optional[datetime] = None---@dataclass-class DiversityMetrics:- """Metrics for source diversity assessment."""-- type_diversity: float # 0.0 to 1.0- temporal_diversity: float- geographic_diversity: float- credibility_distribution: Dict[str, float]- specialty_coverage: Dict[str, int]- overall_score: float---class SourceDiversityManager:- """- Manages source diversity to ensure comprehensive evidence collection.-- Key features:- 1. Tracks source types and characteristics- 2. Ensures diverse source selection- 3. Prioritizes high-credibility sources- 4. Manages geographic and temporal diversity- """-- def __init__(self, model: BaseChatModel):- """Initialize the source diversity manager."""- self.model = model- self.source_profiles: Dict[str, SourceProfile] = {}- self.source_types: Dict[str, Set[str]] = defaultdict(set)- self.type_priorities: Dict[str, float] = {- "academic": 0.9,- "government": 0.85,- "news": 0.7,- "wiki": 0.75,- "blog": 0.5,- "forum": 0.4,- "social": 0.3,- }- self.minimum_source_types: int = 3- self.credibility_threshold: float = 0.6-- def analyze_source(- self, url: str, content: Optional[str] = None- ) -> SourceProfile:- """Analyze a source and create its profile."""- if url in self.source_profiles:- profile = self.source_profiles[url]- profile.evidence_count += 1- profile.last_accessed = datetime.now(UTC)- return profile-- # Extract domain- domain = self._extract_domain(url)-- # Determine source type- source_type = self._determine_source_type(url, domain, content)-- # Calculate credibility- credibility = self._calculate_credibility(- url, domain, source_type, content- )-- # Extract specialties- specialties = self._extract_specialties(url, content)-- # Determine temporal and geographic coverage- temporal_coverage = self._extract_temporal_coverage(content)- geographic_focus = self._extract_geographic_focus(url, content)-- profile = SourceProfile(- url=url,- domain=domain,- source_type=source_type,- credibility_score=credibility,- specialties=specialties,- temporal_coverage=temporal_coverage,- geographic_focus=geographic_focus,- evidence_count=1,- last_accessed=datetime.now(UTC),- )-- self.source_profiles[url] = profile- self.source_types[source_type].add(url)-- return profile-- def _extract_domain(self, url: str) -> str:- """Extract domain from URL."""- import re-- pattern = r"https?://(?:www\.)?([^/]+)"- match = re.match(pattern, url)- if match:- return match.group(1)- return url-- def _determine_source_type(- self, url: str, domain: str, content: Optional[str]- ) -> str:- """Determine the type of source."""- # Check known patterns- academic_domains = [- ".edu",- ".ac.",- "scholar",- "pubmed",- "arxiv",- "jstor",- ]- government_domains = [".gov", ".mil"]- news_domains = [- "news",- "times",- "post",- "guardian",- "bbc",- "cnn",- "reuters",- ]- wiki_domains = ["wikipedia", "wiki"]-- lower_domain = domain.lower()- lower_url = url.lower()-- # Check patterns- for pattern in academic_domains:- if pattern in lower_domain or pattern in lower_url:- return "academic"-- for pattern in government_domains:- if pattern in lower_domain:- return "government"-- for pattern in wiki_domains:- if pattern in lower_domain:- return "wiki"-- for pattern in news_domains:- if pattern in lower_domain:- return "news"-- # Use content analysis as fallback- if content:- return self._analyze_content_type(content)-- return "general"-- def _analyze_content_type(self, content: str) -> str:- """Analyze content to determine source type."""- prompt = f"""-Analyze this content excerpt and determine the source type:--{content[:500]}--Choose from: academic, government, news, wiki, blog, forum, social, general--Return only the source type.-"""-- response = self.model.invoke(prompt)- source_type = response.content.strip().lower()-- if source_type in self.type_priorities:- return source_type- return "general"-- def _calculate_credibility(- self, url: str, domain: str, source_type: str, content: Optional[str]- ) -> float:- """Calculate credibility score for a source."""- # Base score from source type- base_score = self.type_priorities.get(source_type, 0.5)-- # Adjust based on domain characteristics- if ".edu" in domain or ".gov" in domain:- base_score = min(base_score + 0.1, 1.0)-- # Check for HTTPS- if url.startswith("https://"):- base_score = min(base_score + 0.05, 1.0)-- # Additional analysis if content provided- if content:- # Check for citations/references- if re.search(r"\[\d+\]|\(\d{4}\)", content):- base_score = min(base_score + 0.1, 1.0)-- # Check for author information- if re.search(- r"[Aa]uthor:|[Bb]y\s+[A-Z][a-z]+\s+[A-Z][a-z]+", content- ):- base_score = min(base_score + 0.05, 1.0)-- return base_score-- def _extract_specialties(- self, url: str, content: Optional[str]- ) -> List[str]:- """Extract topic specialties from source."""- specialties = []-- # URL-based extraction- url_keywords = re.findall(r"/([a-z]+)/", url.lower())- specialties.extend([kw for kw in url_keywords if len(kw) > 3][:3])-- # Content-based extraction if available- if content:- prompt = f"""-Identify the main topic areas or specialties covered in this content:--{content[:500]}--Return up to 3 topic areas, one per line.-"""-- response = self.model.invoke(prompt)- topics = [- line.strip()- for line in response.content.strip().split("\n")- if line.strip()- ]- specialties.extend(topics[:3])-- return list(set(specialties))[:5]-- def _extract_temporal_coverage(- self, content: Optional[str]- ) -> Optional[Tuple[datetime, datetime]]:- """Extract temporal coverage from content."""- if not content:- return None-- # Look for year patterns- years = re.findall(r"\b(19\d{2}|20\d{2})\b", content)-- if years:- years = [int(year) for year in years]- min_year = min(years)- max_year = max(years)-- try:- return (datetime(min_year, 1, 1), datetime(max_year, 12, 31))- except ValueError:- return None-- return None-- def _extract_geographic_focus(- self, url: str, content: Optional[str]- ) -> Optional[str]:- """Extract geographic focus from source."""- # Check URL for geographic indicators- geo_patterns = {- "us": "United States",- "uk": "United Kingdom",- "ca": "Canada",- "au": "Australia",- "eu": "Europe",- }-- for pattern, location in geo_patterns.items():- if f".{pattern}" in url or f"/{pattern}/" in url:- return location-- # Content-based extraction- if content:- # Look for country/region mentions- locations = re.findall(- r"\b(?:United States|UK|Canada|Australia|Europe|Asia|Africa|Americas)\b",- content[:1000],- re.IGNORECASE,- )-- if locations:- # Return most frequent- from collections import Counter-- location_counts = Counter(locations)- return location_counts.most_common(1)[0][0]-- return None-- def calculate_diversity_metrics(- self, sources: List[str]- ) -> DiversityMetrics:- """Calculate diversity metrics for a set of sources."""- if not sources:- return DiversityMetrics(- type_diversity=0.0,- temporal_diversity=0.0,- geographic_diversity=0.0,- credibility_distribution={},- specialty_coverage={},- overall_score=0.0,- )-- # Get profiles- profiles = [- self.source_profiles.get(url) or self.analyze_source(url)- for url in sources- ]-- # Type diversity- source_types = [p.source_type for p in profiles]- unique_types = len(set(source_types))- type_diversity = min(unique_types / self.minimum_source_types, 1.0)-- # Temporal diversity- temporal_ranges = [- p.temporal_coverage for p in profiles if p.temporal_coverage- ]- temporal_diversity = self._calculate_temporal_diversity(temporal_ranges)-- # Geographic diversity- geo_focuses = [- p.geographic_focus for p in profiles if p.geographic_focus- ]- unique_geos = len(set(geo_focuses))- geographic_diversity = min(unique_geos / 3, 1.0) if geo_focuses else 0.0-- # Credibility distribution- credibility_distribution = {}- for p in profiles:- level = (- "high"- if p.credibility_score >= 0.8- else "medium"- if p.credibility_score >= 0.6- else "low"- )- credibility_distribution[level] = (- credibility_distribution.get(level, 0) + 1- )-- # Specialty coverage- specialty_coverage = {}- for p in profiles:- for specialty in p.specialties:- specialty_coverage[specialty] = (- specialty_coverage.get(specialty, 0) + 1- )-- # Overall score- overall_score = (- type_diversity * 0.3- + temporal_diversity * 0.2- + geographic_diversity * 0.2- + (credibility_distribution.get("high", 0) / len(profiles)) * 0.3- )-- return DiversityMetrics(- type_diversity=type_diversity,- temporal_diversity=temporal_diversity,- geographic_diversity=geographic_diversity,- credibility_distribution=credibility_distribution,- specialty_coverage=specialty_coverage,- overall_score=overall_score,- )-- def _calculate_temporal_diversity(- self, ranges: List[Tuple[datetime, datetime]]- ) -> float:- """Calculate temporal diversity from date ranges."""- if not ranges:- return 0.0-- # Calculate span coverage- all_years = set()- for start, end in ranges:- for year in range(start.year, end.year + 1):- all_years.add(year)-- # Diversity based on year span- if len(all_years) > 1:- year_span = max(all_years) - min(all_years)- # Normalize to 0-1 (20 years = max diversity)- return min(year_span / 20, 1.0)-- return 0.0-- def recommend_additional_sources(- self, current_sources: List[str], constraints: List[Constraint]- ) -> List[Dict[str, Any]]:- """Recommend additional sources to improve diversity."""- current_metrics = self.calculate_diversity_metrics(current_sources)- recommendations = []-- # Identify gaps- gaps = self._identify_diversity_gaps(current_metrics, constraints)-- for gap_type, gap_details in gaps.items():- if gap_type == "source_type":- # Recommend sources of missing types- for missing_type in gap_details:- rec = {- "type": "source_type",- "target": missing_type,- "query_modifier": self._get_source_type_modifier(- missing_type- ),- "reason": f"Add {missing_type} sources for better perspective",- }- recommendations.append(rec)-- elif gap_type == "temporal":- # Recommend sources for missing time periods- rec = {- "type": "temporal",- "target": gap_details,- "query_modifier": f'"{gap_details}" historical archive',- "reason": f"Add sources covering {gap_details}",- }- recommendations.append(rec)-- elif gap_type == "geographic":- # Recommend sources from missing regions- for region in gap_details:- rec = {- "type": "geographic",- "target": region,- "query_modifier": f"site:{self._get_region_domain(region)}",- "reason": f"Add sources from {region}",- }- recommendations.append(rec)-- elif gap_type == "credibility":- # Recommend higher credibility sources- rec = {- "type": "credibility",- "target": "high_credibility",- "query_modifier": "site:.edu OR site:.gov OR peer-reviewed",- "reason": "Add more authoritative sources",- }- recommendations.append(rec)-- return recommendations[:5] # Limit recommendations-- def _identify_diversity_gaps(- self, metrics: DiversityMetrics, constraints: List[Constraint]- ) -> Dict[str, Any]:- """Identify gaps in source diversity."""- gaps = {}-- # Source type gaps- if metrics.type_diversity < 0.7:- current_types = {- p.source_type for p in self.source_profiles.values()- }- desired_types = {"academic", "government", "news", "wiki"}- missing_types = desired_types - current_types- if missing_types:- gaps["source_type"] = list(missing_types)-- # Temporal gaps (based on constraints)- temporal_constraints = [- c for c in constraints if c.type == ConstraintType.TEMPORAL- ]- if temporal_constraints and metrics.temporal_diversity < 0.5:- # Extract years from constraints- years_needed = []- for c in temporal_constraints:- year_match = re.search(r"\b(19\d{2}|20\d{2})\b", c.value)- if year_match:- years_needed.append(year_match.group(1))-- if years_needed:- gaps["temporal"] = f"{min(years_needed)}-{max(years_needed)}"-- # Geographic gaps- location_constraints = [- c for c in constraints if c.type == ConstraintType.LOCATION- ]- if location_constraints and metrics.geographic_diversity < 0.5:- locations_needed = [c.value for c in location_constraints]- gaps["geographic"] = locations_needed-- # Credibility gaps- high_cred_ratio = metrics.credibility_distribution.get("high", 0) / max(- sum(metrics.credibility_distribution.values()), 1- )- if high_cred_ratio < 0.3:- gaps["credibility"] = True-- return gaps-- def _get_source_type_modifier(self, source_type: str) -> str:- """Get search modifier for specific source type."""- modifiers = {- "academic": "site:.edu OR site:scholar.google.com OR site:pubmed.gov",- "government": "site:.gov OR site:.mil",- "news": 'news OR "press release" OR journalism',- "wiki": "site:wikipedia.org OR wiki",- "blog": 'blog OR "posted by" OR comments',- }- return modifiers.get(source_type, "")-- def _get_region_domain(self, region: str) -> str:- """Get domain suffix for a region."""- region_domains = {- "United States": ".us OR .com",- "United Kingdom": ".uk",- "Canada": ".ca",- "Australia": ".au",- "Europe": ".eu OR .de OR .fr",- }- return region_domains.get(region, ".com")-- def select_diverse_sources(- self, available_sources: List[str], target_count: int- ) -> List[str]:- """Select a diverse subset of sources."""- if len(available_sources) <= target_count:- return available_sources-- # Score each source based on diversity contribution- source_scores = []-- for source in available_sources:- profile = self.source_profiles.get(source) or self.analyze_source(- source- )-- # Calculate diversity score- score = (- self.type_priorities.get(profile.source_type, 0.5) * 0.4- + profile.credibility_score * 0.3- + (1.0 if profile.specialties else 0.5) * 0.15- + (1.0 if profile.temporal_coverage else 0.5) * 0.15- )-- source_scores.append((source, score, profile))-- # Sort by score- source_scores.sort(key=lambda x: x[1], reverse=True)-- # Select diverse sources- selected = []- selected_types = set()- selected_geos = set()-- for source, score, profile in source_scores:- # Prioritize diversity- is_diverse = profile.source_type not in selected_types or (- profile.geographic_focus- and profile.geographic_focus not in selected_geos- )-- if is_diverse or len(selected) < target_count // 2:- selected.append(source)- selected_types.add(profile.source_type)- if profile.geographic_focus:- selected_geos.add(profile.geographic_focus)-- if len(selected) >= target_count:- break-- return selected-- def track_source_effectiveness(- self, source: str, evidence_quality: float, constraint_satisfied: bool- ):- """Track how effective a source is for evidence gathering."""- profile = self.source_profiles.get(source)- if not profile:- return-- # Update profile based on effectiveness- if constraint_satisfied:- # Boost credibility slightly- profile.credibility_score = min(- profile.credibility_score * 1.05, 1.0- )-- # Track in metadata- if "effectiveness" not in profile.__dict__:- profile.effectiveness = []-- profile.effectiveness.append(- {- "timestamp": datetime.now(UTC),- "evidence_quality": evidence_quality,- "constraint_satisfied": constraint_satisfied,- }- )diff --git a/tests/advanced_search_system/answer_decoding/test_browsecomp_answer_decoder.py b/tests/advanced_search_system/answer_decoding/test_browsecomp_answer_decoder.pydeleted file mode 100644index c96b304e38..0000000000--- a/tests/advanced_search_system/answer_decoding/test_browsecomp_answer_decoder.py+++ /dev/null@@ -1,348 +0,0 @@-"""-Tests for BrowseComp Answer Decoder.--Phase 34: Answer Decoding - Tests for browsecomp_answer_decoder.py-Tests encoding detection, multiple decoding schemes, and validation.-"""--import pytest-import base64--from local_deep_research.advanced_search_system.answer_decoding.browsecomp_answer_decoder import (- BrowseCompAnswerDecoder,-)---class TestBrowseCompAnswerDecoderInit:- """Tests for decoder initialization."""-- def test_initialization(self):- """Test decoder initializes with encoding schemes."""- decoder = BrowseCompAnswerDecoder()- assert len(decoder.encoding_schemes) > 0- assert "base64" in decoder.encoding_schemes- assert "hex" in decoder.encoding_schemes- assert "url_encoding" in decoder.encoding_schemes- assert "rot13" in decoder.encoding_schemes-- def test_initialization_has_encoded_patterns(self):- """Test decoder initializes with encoded patterns."""- decoder = BrowseCompAnswerDecoder()- assert len(decoder.encoded_patterns) > 0---class TestDecodeAnswer:- """Tests for decode_answer method."""-- def test_decode_empty_string(self):- """Test decoding empty string returns original."""- decoder = BrowseCompAnswerDecoder()- result, scheme = decoder.decode_answer("")- assert result == ""- assert scheme is None-- def test_decode_none_input(self):- """Test decoding None returns original."""- decoder = BrowseCompAnswerDecoder()- result, scheme = decoder.decode_answer(None)- assert result is None- assert scheme is None-- def test_decode_whitespace_only(self):- """Test decoding whitespace-only string."""- decoder = BrowseCompAnswerDecoder()- result, scheme = decoder.decode_answer(" ")- assert result == " "- assert scheme is None-- def test_decode_plaintext_answer(self):- """Test plaintext answer is returned unchanged."""- decoder = BrowseCompAnswerDecoder()- result, scheme = decoder.decode_answer("This is a normal answer")- assert result == "This is a normal answer"- assert scheme is None-- def test_decode_base64_answer(self):- """Test base64 encoded answer is decoded."""- decoder = BrowseCompAnswerDecoder()- # "Hello World" encoded in base64- encoded = base64.b64encode(b"Hello World").decode()- result, scheme = decoder.decode_answer(encoded)- # May or may not decode depending on validation- assert result is not None-- def test_decode_returns_tuple(self):- """Test decode_answer always returns tuple."""- decoder = BrowseCompAnswerDecoder()- result = decoder.decode_answer("test")- assert isinstance(result, tuple)- assert len(result) == 2-- def test_decode_strips_whitespace(self):- """Test decode_answer strips leading/trailing whitespace."""- decoder = BrowseCompAnswerDecoder()- result, _ = decoder.decode_answer(" answer ")- assert not result.startswith(" ")- assert not result.endswith(" ") or result == "answer"---class TestIsLikelyDirectAnswer:- """Tests for is_likely_direct_answer method."""-- def test_short_answer_is_direct(self):- """Test short answers are considered direct."""- decoder = BrowseCompAnswerDecoder()- assert decoder.is_likely_direct_answer("Yes") is True- assert decoder.is_likely_direct_answer("No") is True- assert decoder.is_likely_direct_answer("42") is True-- def test_english_words_are_direct(self):- """Test answers with common English words are direct."""- decoder = BrowseCompAnswerDecoder()- assert (- decoder.is_likely_direct_answer("The company was founded in 2010")- is True- )- assert decoder.is_likely_direct_answer("People of New York") is True- assert decoder.is_likely_direct_answer("Microsoft Corporation") is True-- def test_multi_word_answers_are_direct(self):- """Test multi-word answers are considered direct."""- decoder = BrowseCompAnswerDecoder()- assert decoder.is_likely_direct_answer("John Smith") is True- assert decoder.is_likely_direct_answer("New York City") is True-- def test_year_pattern_is_direct(self):- """Test year patterns are considered direct."""- decoder = BrowseCompAnswerDecoder()- assert decoder.is_likely_direct_answer("2024") is True- assert decoder.is_likely_direct_answer("1999") is True-- def test_number_pattern_is_direct(self):- """Test number patterns are considered direct."""- decoder = BrowseCompAnswerDecoder()- assert decoder.is_likely_direct_answer("$100") is True- assert decoder.is_likely_direct_answer("50%") is True-- def test_name_pattern_is_direct(self):- """Test name patterns are considered direct."""- decoder = BrowseCompAnswerDecoder()- # Two capitalized words - name format- assert decoder.is_likely_direct_answer("John Smith") is True-- def test_random_string_not_direct(self):- """Test random alphanumeric strings are not considered direct."""- decoder = BrowseCompAnswerDecoder()- # Long random string with no spaces- result = decoder.is_likely_direct_answer("Y00Qh+epXYZ123")- # This might be encoded- assert isinstance(result, bool)---class TestDecodingSchemes:- """Tests for individual decoding schemes."""-- def test_base64_decoding(self):- """Test base64 decoding scheme."""- decoder = BrowseCompAnswerDecoder()- # "Test" in base64- encoded = base64.b64encode(b"Test").decode()-- if hasattr(decoder, "apply_decoding_scheme"):- result = decoder.apply_decoding_scheme(encoded, "base64")- # May return decoded value or None- assert result is None or isinstance(result, str)-- def test_hex_decoding(self):- """Test hex decoding scheme."""- decoder = BrowseCompAnswerDecoder()- # "Test" in hex- encoded = "54657374"-- if hasattr(decoder, "apply_decoding_scheme"):- result = decoder.apply_decoding_scheme(encoded, "hex")- assert result is None or isinstance(result, str)-- def test_url_decoding(self):- """Test URL encoding scheme."""- decoder = BrowseCompAnswerDecoder()- # "Hello World" URL encoded- encoded = "Hello%20World"-- if hasattr(decoder, "apply_decoding_scheme"):- result = decoder.apply_decoding_scheme(encoded, "url_encoding")- assert (- result is None- or result == "Hello World"- or isinstance(result, str)- )-- def test_rot13_decoding(self):- """Test ROT13 decoding scheme."""- decoder = BrowseCompAnswerDecoder()- # "Hello" in ROT13 is "Uryyb"- encoded = "Uryyb"-- if hasattr(decoder, "apply_decoding_scheme"):- result = decoder.apply_decoding_scheme(encoded, "rot13")- assert result is None or isinstance(result, str)-- def test_unknown_scheme_handling(self):- """Test handling of unknown decoding scheme."""- decoder = BrowseCompAnswerDecoder()-- if hasattr(decoder, "apply_decoding_scheme"):- result = decoder.apply_decoding_scheme("test", "unknown_scheme")- # Should handle gracefully- assert result is None or isinstance(result, str)---class TestValidateDecodedAnswer:- """Tests for answer validation."""-- def test_validate_valid_answer(self):- """Test validation of valid decoded answer."""- decoder = BrowseCompAnswerDecoder()-- if hasattr(decoder, "validate_decoded_answer"):- # Normal text should be valid- assert (- decoder.validate_decoded_answer("This is a valid answer")- is True- )-- def test_validate_empty_answer(self):- """Test validation of empty answer."""- decoder = BrowseCompAnswerDecoder()-- if hasattr(decoder, "validate_decoded_answer"):- result = decoder.validate_decoded_answer("")- # Empty should likely be invalid- assert isinstance(result, bool)-- def test_validate_binary_content(self):- """Test validation rejects binary-like content."""- decoder = BrowseCompAnswerDecoder()-- if hasattr(decoder, "validate_decoded_answer"):- # Binary content should be rejected- result = decoder.validate_decoded_answer("\x00\x01\x02")- assert isinstance(result, bool)---class TestEncodedPatterns:- """Tests for encoded pattern detection."""-- def test_base64_pattern_detection(self):- """Test detection of base64-like patterns."""- decoder = BrowseCompAnswerDecoder()- # Check if patterns exist- assert (- any(- "base64" in str(p).lower() or "+" in p or "/" in p- for p in decoder.encoded_patterns- )- or len(decoder.encoded_patterns) > 0- )-- def test_hex_pattern_detection(self):- """Test detection of hex-like patterns."""- decoder = BrowseCompAnswerDecoder()- # Hex pattern should exist- assert len(decoder.encoded_patterns) > 0---class TestEdgeCases:- """Edge case tests for answer decoder."""-- def test_very_long_answer(self):- """Test handling of very long answer."""- decoder = BrowseCompAnswerDecoder()- long_answer = "A" * 10000- result, scheme = decoder.decode_answer(long_answer)- assert result is not None-- def test_unicode_answer(self):- """Test handling of unicode characters."""- decoder = BrowseCompAnswerDecoder()- result, scheme = decoder.decode_answer("こんにちは")- assert result is not None-- def test_special_characters(self):- """Test handling of special characters."""- decoder = BrowseCompAnswerDecoder()- result, scheme = decoder.decode_answer("Answer with @#$%^&*()")- assert result is not None-- def test_mixed_encoding(self):- """Test handling of mixed encoding patterns."""- decoder = BrowseCompAnswerDecoder()- # String that looks partially encoded- result, scheme = decoder.decode_answer("Normal text with Y00Qh+ep")- assert result is not None-- def test_numeric_only(self):- """Test handling of numeric-only strings."""- decoder = BrowseCompAnswerDecoder()- result, scheme = decoder.decode_answer("1234567890")- assert result == "1234567890" or result is not None-- def test_alphanumeric_mix(self):- """Test handling of alphanumeric strings."""- decoder = BrowseCompAnswerDecoder()- result, scheme = decoder.decode_answer("ABC123")- assert result is not None---class TestIntegration:- """Integration tests for answer decoder."""-- def test_full_decoding_workflow(self):- """Test complete decoding workflow."""- decoder = BrowseCompAnswerDecoder()-- # Test various answer types- test_cases = [- "Simple plaintext answer",- "2024",- "John Smith",- "$1,000,000",- "50%",- "The company was founded",- ]-- for answer in test_cases:- result, scheme = decoder.decode_answer(answer)- assert result is not None, f"Failed for: {answer}"- # Plaintext should return as-is- assert scheme is None or result == answer or isinstance(result, str)-- def test_robustness(self):- """Test decoder robustness with various inputs."""- decoder = BrowseCompAnswerDecoder()-- # Should not raise exceptions- test_inputs = [- "",- " ",- "a",- "ab",- "abc",- "test123",- "Test Answer",- "Multiple Word Answer Here",- "123",- "$99.99",- "Mix3d C0nt3nt",- "ALLCAPS",- "alllower",- ]-- for input_val in test_inputs:- try:- result, scheme = decoder.decode_answer(input_val)- assert result is not None or input_val == ""- except Exception as e:- pytest.fail(- f"Decoder raised exception for input '{input_val}': {e}"- )diff --git a/tests/advanced_search_system/constraint_checking/test_intelligent_constraint_relaxer.py b/tests/advanced_search_system/constraint_checking/test_intelligent_constraint_relaxer.pydeleted file mode 100644index dc59e86773..0000000000--- a/tests/advanced_search_system/constraint_checking/test_intelligent_constraint_relaxer.py+++ /dev/null@@ -1,1054 +0,0 @@-"""-Tests for intelligent_constraint_relaxer.py--Tests cover:-- IntelligentConstraintRelaxer initialization-- relax_constraints_progressively method-- _create_constraint_variations method-- _relax_statistical_constraint method-- _relax_comparison_constraint method-- _relax_temporal_constraint method-- _relax_property_constraint method-- _create_relaxed_constraint helper-- _get_constraint_type method-- analyze_relaxation_impact method-"""--from dataclasses import dataclass-from enum import Enum-from unittest.mock import Mock---class MockConstraintType(Enum):- """Mock constraint type for testing."""-- NAME_PATTERN = "NAME_PATTERN"- EXISTENCE = "EXISTENCE"- LOCATION = "LOCATION"- TEMPORAL = "TEMPORAL"- PROPERTY = "PROPERTY"- EVENT = "EVENT"- STATISTIC = "STATISTIC"- COMPARISON = "COMPARISON"- RELATIONSHIP = "RELATIONSHIP"---@dataclass-class MockConstraint:- """Mock constraint for testing."""-- id: str- type: MockConstraintType- value: str- description: str = ""-- def __str__(self):- return self.value---class TestIntelligentConstraintRelaxerInit:- """Tests for IntelligentConstraintRelaxer initialization."""-- def test_initializes_constraint_priorities(self):- """Test that constraint priorities are initialized."""- from local_deep_research.advanced_search_system.constraint_checking.intelligent_constraint_relaxer import (- IntelligentConstraintRelaxer,- )-- relaxer = IntelligentConstraintRelaxer()-- assert "NAME_PATTERN" in relaxer.constraint_priorities- assert "STATISTIC" in relaxer.constraint_priorities- assert (- relaxer.constraint_priorities["NAME_PATTERN"]- > relaxer.constraint_priorities["STATISTIC"]- )-- def test_initializes_min_constraints(self):- """Test that min_constraints is initialized."""- from local_deep_research.advanced_search_system.constraint_checking.intelligent_constraint_relaxer import (- IntelligentConstraintRelaxer,- )-- relaxer = IntelligentConstraintRelaxer()-- assert relaxer.min_constraints == 2-- def test_initializes_relaxation_strategies(self):- """Test that relaxation strategies are initialized."""- from local_deep_research.advanced_search_system.constraint_checking.intelligent_constraint_relaxer import (- IntelligentConstraintRelaxer,- )-- relaxer = IntelligentConstraintRelaxer()-- assert "STATISTIC" in relaxer.relaxation_strategies- assert "COMPARISON" in relaxer.relaxation_strategies- assert "TEMPORAL" in relaxer.relaxation_strategies- assert "PROPERTY" in relaxer.relaxation_strategies-- def test_name_pattern_has_highest_priority(self):- """Test that NAME_PATTERN has highest priority."""- from local_deep_research.advanced_search_system.constraint_checking.intelligent_constraint_relaxer import (- IntelligentConstraintRelaxer,- )-- relaxer = IntelligentConstraintRelaxer()-- assert relaxer.constraint_priorities["NAME_PATTERN"] == 10-- def test_comparison_has_lowest_priority(self):- """Test that COMPARISON has lowest priority."""- from local_deep_research.advanced_search_system.constraint_checking.intelligent_constraint_relaxer import (- IntelligentConstraintRelaxer,- )-- relaxer = IntelligentConstraintRelaxer()-- assert relaxer.constraint_priorities["COMPARISON"] == 1---class TestRelaxConstraintsProgressively:- """Tests for relax_constraints_progressively method."""-- def test_returns_original_when_sufficient_candidates(self):- """Test that original constraints returned when sufficient candidates found."""- from local_deep_research.advanced_search_system.constraint_checking.intelligent_constraint_relaxer import (- IntelligentConstraintRelaxer,- )-- relaxer = IntelligentConstraintRelaxer()- constraints = [- MockConstraint("c1", MockConstraintType.PROPERTY, "test property")- ]- candidates = [Mock() for _ in range(5)]-- result = relaxer.relax_constraints_progressively(- constraints, candidates, target_candidates=5- )-- assert result == [constraints]-- def test_generates_relaxation_strategies_when_insufficient_candidates(self):- """Test that relaxation strategies are generated."""- from local_deep_research.advanced_search_system.constraint_checking.intelligent_constraint_relaxer import (- IntelligentConstraintRelaxer,- )-- relaxer = IntelligentConstraintRelaxer()- constraints = [- MockConstraint("c1", MockConstraintType.PROPERTY, "property 1"),- MockConstraint("c2", MockConstraintType.STATISTIC, "statistic 100"),- MockConstraint("c3", MockConstraintType.COMPARISON, "times more"),- ]- candidates = []-- result = relaxer.relax_constraints_progressively(- constraints, candidates, target_candidates=5- )-- assert len(result) >= 1-- def test_respects_min_constraints(self):- """Test that relaxed sets respect min_constraints."""- from local_deep_research.advanced_search_system.constraint_checking.intelligent_constraint_relaxer import (- IntelligentConstraintRelaxer,- )-- relaxer = IntelligentConstraintRelaxer()- relaxer.min_constraints = 2- constraints = [- MockConstraint("c1", MockConstraintType.PROPERTY, "property 1"),- MockConstraint("c2", MockConstraintType.STATISTIC, "statistic"),- MockConstraint("c3", MockConstraintType.COMPARISON, "comparison"),- ]-- result = relaxer.relax_constraints_progressively(constraints, [])-- for relaxed_set in result:- assert len(relaxed_set) >= 2-- def test_keeps_high_priority_constraints(self):- """Test that high priority constraints are kept."""- from local_deep_research.advanced_search_system.constraint_checking.intelligent_constraint_relaxer import (- IntelligentConstraintRelaxer,- )-- relaxer = IntelligentConstraintRelaxer()- constraints = [- MockConstraint(- "c1", MockConstraintType.NAME_PATTERN, "name pattern"- ),- MockConstraint("c2", MockConstraintType.LOCATION, "location"),- MockConstraint("c3", MockConstraintType.COMPARISON, "comparison"),- ]-- result = relaxer.relax_constraints_progressively(constraints, [])-- # High priority only set should be generated- found_high_priority_only = False- for relaxed_set in result:- set_types = [relaxer._get_constraint_type(c) for c in relaxed_set]- if "NAME_PATTERN" in set_types and "COMPARISON" not in set_types:- found_high_priority_only = True- break-- assert found_high_priority_only-- def test_removes_duplicate_constraint_sets(self):- """Test that duplicate constraint sets are removed."""- from local_deep_research.advanced_search_system.constraint_checking.intelligent_constraint_relaxer import (- IntelligentConstraintRelaxer,- )-- relaxer = IntelligentConstraintRelaxer()- constraints = [- MockConstraint("c1", MockConstraintType.PROPERTY, "property"),- MockConstraint("c2", MockConstraintType.PROPERTY, "property 2"),- ]-- result = relaxer.relax_constraints_progressively(constraints, [])-- # Check for duplicates- signatures = []- for constraint_set in result:- sig = tuple(sorted(str(c) for c in constraint_set))- assert sig not in signatures- signatures.append(sig)-- def test_sorts_by_relaxation_priority(self):- """Test that constraints are sorted by relaxation priority."""- from local_deep_research.advanced_search_system.constraint_checking.intelligent_constraint_relaxer import (- IntelligentConstraintRelaxer,- )-- relaxer = IntelligentConstraintRelaxer()- constraints = [- MockConstraint("c1", MockConstraintType.NAME_PATTERN, "name"),- MockConstraint("c2", MockConstraintType.COMPARISON, "comparison"),- MockConstraint("c3", MockConstraintType.STATISTIC, "statistic"),- ]-- result = relaxer.relax_constraints_progressively(constraints, [])-- # At least one strategy should be generated- assert len(result) >= 1---class TestCreateConstraintVariations:- """Tests for _create_constraint_variations method."""-- def test_creates_variations_for_statistical_constraints(self):- """Test creating variations for statistical constraints."""- from local_deep_research.advanced_search_system.constraint_checking.intelligent_constraint_relaxer import (- IntelligentConstraintRelaxer,- )-- relaxer = IntelligentConstraintRelaxer()- constraints = [- MockConstraint(- "c1", MockConstraintType.STATISTIC, "population of 100000"- )- ]-- result = relaxer._create_constraint_variations(constraints)-- assert len(result) > 0-- def test_creates_variations_for_comparison_constraints(self):- """Test creating variations for comparison constraints."""- from local_deep_research.advanced_search_system.constraint_checking.intelligent_constraint_relaxer import (- IntelligentConstraintRelaxer,- )-- relaxer = IntelligentConstraintRelaxer()- constraints = [- MockConstraint("c1", MockConstraintType.COMPARISON, "3 times more")- ]-- result = relaxer._create_constraint_variations(constraints)-- assert len(result) > 0-- def test_creates_variations_for_temporal_constraints(self):- """Test creating variations for temporal constraints."""- from local_deep_research.advanced_search_system.constraint_checking.intelligent_constraint_relaxer import (- IntelligentConstraintRelaxer,- )-- relaxer = IntelligentConstraintRelaxer()- constraints = [- MockConstraint("c1", MockConstraintType.TEMPORAL, "founded in 1990")- ]-- result = relaxer._create_constraint_variations(constraints)-- assert len(result) > 0-- def test_creates_variations_for_property_constraints(self):- """Test creating variations for property constraints."""- from local_deep_research.advanced_search_system.constraint_checking.intelligent_constraint_relaxer import (- IntelligentConstraintRelaxer,- )-- relaxer = IntelligentConstraintRelaxer()- constraints = [- MockConstraint(- "c1", MockConstraintType.PROPERTY, "multinational corporation"- )- ]-- result = relaxer._create_constraint_variations(constraints)-- assert len(result) > 0-- def test_returns_empty_for_no_variations(self):- """Test that empty list returned when no variations possible."""- from local_deep_research.advanced_search_system.constraint_checking.intelligent_constraint_relaxer import (- IntelligentConstraintRelaxer,- )-- relaxer = IntelligentConstraintRelaxer()- constraints = [- MockConstraint("c1", MockConstraintType.NAME_PATTERN, "exact name")- ]-- result = relaxer._create_constraint_variations(constraints)-- # NAME_PATTERN has no relaxation strategy- assert result == []---class TestRelaxStatisticalConstraint:- """Tests for _relax_statistical_constraint method."""-- def test_creates_range_variations(self):- """Test creating range variations for numbers."""- from local_deep_research.advanced_search_system.constraint_checking.intelligent_constraint_relaxer import (- IntelligentConstraintRelaxer,- )-- relaxer = IntelligentConstraintRelaxer()- constraint = MockConstraint(- "c1", MockConstraintType.STATISTIC, "population 1000"- )-- result = relaxer._relax_statistical_constraint(constraint)-- assert len(result) > 0- # Check that at least one has "between" in it- assert any("between" in str(r).lower() for r in result)-- def test_creates_approximately_variation(self):- """Test creating approximately variation."""- from local_deep_research.advanced_search_system.constraint_checking.intelligent_constraint_relaxer import (- IntelligentConstraintRelaxer,- )-- relaxer = IntelligentConstraintRelaxer()- # The implementation creates range variations first, then approximately- # Since it limits to 3, we need to verify range variations are created- constraint = MockConstraint(- "c1", MockConstraintType.STATISTIC, "count 500"- )-- result = relaxer._relax_statistical_constraint(constraint)-- # Verify variations are created (ranges are created before approximately)- assert len(result) > 0-- def test_limits_variations_to_three(self):- """Test that variations are limited to 3."""- from local_deep_research.advanced_search_system.constraint_checking.intelligent_constraint_relaxer import (- IntelligentConstraintRelaxer,- )-- relaxer = IntelligentConstraintRelaxer()- constraint = MockConstraint(- "c1", MockConstraintType.STATISTIC, "value 100 or 200 or 300"- )-- result = relaxer._relax_statistical_constraint(constraint)-- assert len(result) <= 3-- def test_handles_decimal_numbers(self):- """Test handling decimal numbers."""- from local_deep_research.advanced_search_system.constraint_checking.intelligent_constraint_relaxer import (- IntelligentConstraintRelaxer,- )-- relaxer = IntelligentConstraintRelaxer()- constraint = MockConstraint(- "c1", MockConstraintType.STATISTIC, "ratio 3.14"- )-- result = relaxer._relax_statistical_constraint(constraint)-- assert len(result) > 0-- def test_handles_no_numbers(self):- """Test handling constraint with no numbers."""- from local_deep_research.advanced_search_system.constraint_checking.intelligent_constraint_relaxer import (- IntelligentConstraintRelaxer,- )-- relaxer = IntelligentConstraintRelaxer()- constraint = MockConstraint(- "c1", MockConstraintType.STATISTIC, "no numbers here"- )-- result = relaxer._relax_statistical_constraint(constraint)-- assert result == []---class TestRelaxComparisonConstraint:- """Tests for _relax_comparison_constraint method."""-- def test_relaxes_times_more(self):- """Test relaxing 'times more' to 'significantly more'."""- from local_deep_research.advanced_search_system.constraint_checking.intelligent_constraint_relaxer import (- IntelligentConstraintRelaxer,- )-- relaxer = IntelligentConstraintRelaxer()- constraint = MockConstraint(- "c1", MockConstraintType.COMPARISON, "5 times more"- )-- result = relaxer._relax_comparison_constraint(constraint)-- assert any("significantly more" in str(r).lower() for r in result)-- def test_relaxes_exactly(self):- """Test relaxing 'exactly' to 'approximately'."""- from local_deep_research.advanced_search_system.constraint_checking.intelligent_constraint_relaxer import (- IntelligentConstraintRelaxer,- )-- relaxer = IntelligentConstraintRelaxer()- constraint = MockConstraint(- "c1", MockConstraintType.COMPARISON, "exactly 100"- )-- result = relaxer._relax_comparison_constraint(constraint)-- assert any("approximately" in str(r).lower() for r in result)-- def test_relaxes_superlatives(self):- """Test relaxing superlatives like 'largest'."""- from local_deep_research.advanced_search_system.constraint_checking.intelligent_constraint_relaxer import (- IntelligentConstraintRelaxer,- )-- relaxer = IntelligentConstraintRelaxer()- constraint = MockConstraint(- "c1", MockConstraintType.COMPARISON, "the largest city"- )-- result = relaxer._relax_comparison_constraint(constraint)-- assert any("one of the largest" in str(r).lower() for r in result)-- def test_removes_comparison_indicators(self):- """Test removing comparison indicators."""- from local_deep_research.advanced_search_system.constraint_checking.intelligent_constraint_relaxer import (- IntelligentConstraintRelaxer,- )-- relaxer = IntelligentConstraintRelaxer()- constraint = MockConstraint(- "c1", MockConstraintType.COMPARISON, "bigger more than average"- )-- result = relaxer._relax_comparison_constraint(constraint)-- assert len(result) > 0-- def test_limits_variations_to_three(self):- """Test that variations are limited to 3."""- from local_deep_research.advanced_search_system.constraint_checking.intelligent_constraint_relaxer import (- IntelligentConstraintRelaxer,- )-- relaxer = IntelligentConstraintRelaxer()- constraint = MockConstraint(- "c1",- MockConstraintType.COMPARISON,- "times more largest highest compared to",- )-- result = relaxer._relax_comparison_constraint(constraint)-- assert len(result) <= 3---class TestRelaxTemporalConstraint:- """Tests for _relax_temporal_constraint method."""-- def test_creates_decade_variations(self):- """Test creating decade range variations."""- from local_deep_research.advanced_search_system.constraint_checking.intelligent_constraint_relaxer import (- IntelligentConstraintRelaxer,- )-- relaxer = IntelligentConstraintRelaxer()- constraint = MockConstraint(- "c1", MockConstraintType.TEMPORAL, "founded in 1995"- )-- result = relaxer._relax_temporal_constraint(constraint)-- assert any("1990s" in str(r) for r in result)-- def test_creates_range_variations(self):- """Test creating +/- range variations."""- from local_deep_research.advanced_search_system.constraint_checking.intelligent_constraint_relaxer import (- IntelligentConstraintRelaxer,- )-- relaxer = IntelligentConstraintRelaxer()- constraint = MockConstraint(- "c1", MockConstraintType.TEMPORAL, "started in 2000"- )-- result = relaxer._relax_temporal_constraint(constraint)-- assert any("between" in str(r).lower() for r in result)-- def test_relaxes_founded_to_around(self):- """Test relaxing 'founded in' to 'founded around'."""- from local_deep_research.advanced_search_system.constraint_checking.intelligent_constraint_relaxer import (- IntelligentConstraintRelaxer,- )-- relaxer = IntelligentConstraintRelaxer()- # The implementation creates decade and range variations first, then around- # Since it limits to 3 results, verify at least some variations are created- constraint = MockConstraint(- "c1", MockConstraintType.TEMPORAL, "founded in 1985"- )-- result = relaxer._relax_temporal_constraint(constraint)-- # Verify variations are created (decades and ranges take priority)- assert len(result) > 0-- def test_handles_no_years(self):- """Test handling constraint without years."""- from local_deep_research.advanced_search_system.constraint_checking.intelligent_constraint_relaxer import (- IntelligentConstraintRelaxer,- )-- relaxer = IntelligentConstraintRelaxer()- constraint = MockConstraint(- "c1", MockConstraintType.TEMPORAL, "recently established"- )-- result = relaxer._relax_temporal_constraint(constraint)-- # Should still work (might return empty list)- assert isinstance(result, list)-- def test_handles_21st_century_years(self):- """Test handling years in 2000s."""- from local_deep_research.advanced_search_system.constraint_checking.intelligent_constraint_relaxer import (- IntelligentConstraintRelaxer,- )-- relaxer = IntelligentConstraintRelaxer()- constraint = MockConstraint(- "c1", MockConstraintType.TEMPORAL, "created in 2015"- )-- result = relaxer._relax_temporal_constraint(constraint)-- assert any("2010s" in str(r) for r in result)-- def test_limits_variations_to_three(self):- """Test that variations are limited to 3."""- from local_deep_research.advanced_search_system.constraint_checking.intelligent_constraint_relaxer import (- IntelligentConstraintRelaxer,- )-- relaxer = IntelligentConstraintRelaxer()- constraint = MockConstraint(- "c1", MockConstraintType.TEMPORAL, "founded in 1990"- )-- result = relaxer._relax_temporal_constraint(constraint)-- assert len(result) <= 3---class TestRelaxPropertyConstraint:- """Tests for _relax_property_constraint method."""-- def test_generalizes_multinational(self):- """Test generalizing 'multinational' to 'international'."""- from local_deep_research.advanced_search_system.constraint_checking.intelligent_constraint_relaxer import (- IntelligentConstraintRelaxer,- )-- relaxer = IntelligentConstraintRelaxer()- constraint = MockConstraint(- "c1", MockConstraintType.PROPERTY, "multinational company"- )-- result = relaxer._relax_property_constraint(constraint)-- assert any("international" in str(r).lower() for r in result)-- def test_generalizes_corporation(self):- """Test generalizing 'corporation' to 'company'."""- from local_deep_research.advanced_search_system.constraint_checking.intelligent_constraint_relaxer import (- IntelligentConstraintRelaxer,- )-- relaxer = IntelligentConstraintRelaxer()- constraint = MockConstraint(- "c1", MockConstraintType.PROPERTY, "large corporation"- )-- result = relaxer._relax_property_constraint(constraint)-- assert any("company" in str(r).lower() for r in result)-- def test_removes_adjectives(self):- """Test removing adjectives like 'very', 'extremely'."""- from local_deep_research.advanced_search_system.constraint_checking.intelligent_constraint_relaxer import (- IntelligentConstraintRelaxer,- )-- relaxer = IntelligentConstraintRelaxer()- constraint = MockConstraint(- "c1", MockConstraintType.PROPERTY, "very large market"- )-- result = relaxer._relax_property_constraint(constraint)-- assert any("very" not in str(r).lower() for r in result)-- def test_limits_variations_to_two(self):- """Test that variations are limited to 2."""- from local_deep_research.advanced_search_system.constraint_checking.intelligent_constraint_relaxer import (- IntelligentConstraintRelaxer,- )-- relaxer = IntelligentConstraintRelaxer()- constraint = MockConstraint(- "c1",- MockConstraintType.PROPERTY,- "very major multinational conglomerate",- )-- result = relaxer._relax_property_constraint(constraint)-- assert len(result) <= 2-- def test_handles_no_matches(self):- """Test handling constraint with no matching terms."""- from local_deep_research.advanced_search_system.constraint_checking.intelligent_constraint_relaxer import (- IntelligentConstraintRelaxer,- )-- relaxer = IntelligentConstraintRelaxer()- constraint = MockConstraint(- "c1", MockConstraintType.PROPERTY, "unique property"- )-- result = relaxer._relax_property_constraint(constraint)-- assert isinstance(result, list)---class TestCreateRelaxedConstraint:- """Tests for _create_relaxed_constraint helper."""-- def test_updates_value_attribute(self):- """Test updating value attribute of constraint."""- from local_deep_research.advanced_search_system.constraint_checking.intelligent_constraint_relaxer import (- IntelligentConstraintRelaxer,- )-- relaxer = IntelligentConstraintRelaxer()- constraint = MockConstraint(- "c1", MockConstraintType.PROPERTY, "original value"- )-- result = relaxer._create_relaxed_constraint(constraint, "relaxed value")-- assert result.value == "relaxed value"-- def test_preserves_original_constraint(self):- """Test that original constraint is not modified."""- from local_deep_research.advanced_search_system.constraint_checking.intelligent_constraint_relaxer import (- IntelligentConstraintRelaxer,- )-- relaxer = IntelligentConstraintRelaxer()- constraint = MockConstraint(- "c1", MockConstraintType.PROPERTY, "original value"- )-- relaxer._create_relaxed_constraint(constraint, "relaxed value")-- assert constraint.value == "original value"-- def test_handles_constraint_without_dict(self):- """Test handling constraint without __dict__ attribute."""- from local_deep_research.advanced_search_system.constraint_checking.intelligent_constraint_relaxer import (- IntelligentConstraintRelaxer,- )-- relaxer = IntelligentConstraintRelaxer()-- result = relaxer._create_relaxed_constraint(- "string constraint", "relaxed"- )-- assert result == "relaxed"-- def test_updates_description_if_no_value(self):- """Test updating description attribute if no value attribute."""- from local_deep_research.advanced_search_system.constraint_checking.intelligent_constraint_relaxer import (- IntelligentConstraintRelaxer,- )-- @dataclass- class DescriptionConstraint:- id: str- description: str-- relaxer = IntelligentConstraintRelaxer()- constraint = DescriptionConstraint("c1", "original description")-- result = relaxer._create_relaxed_constraint(- constraint, "relaxed description"- )-- assert result.description == "relaxed description"---class TestGetConstraintType:- """Tests for _get_constraint_type method."""-- def test_gets_type_from_type_attribute(self):- """Test getting type from type attribute."""- from local_deep_research.advanced_search_system.constraint_checking.intelligent_constraint_relaxer import (- IntelligentConstraintRelaxer,- )-- relaxer = IntelligentConstraintRelaxer()- constraint = MockConstraint("c1", MockConstraintType.PROPERTY, "value")-- result = relaxer._get_constraint_type(constraint)-- assert result == "PROPERTY"-- def test_gets_type_from_constraint_type_attribute(self):- """Test getting type from constraint_type attribute."""- from local_deep_research.advanced_search_system.constraint_checking.intelligent_constraint_relaxer import (- IntelligentConstraintRelaxer,- )-- @dataclass- class TypedConstraint:- constraint_type: str-- relaxer = IntelligentConstraintRelaxer()- constraint = TypedConstraint("TEMPORAL")-- result = relaxer._get_constraint_type(constraint)-- assert result == "TEMPORAL"-- def test_infers_name_pattern_from_text(self):- """Test inferring NAME_PATTERN type from text."""- from local_deep_research.advanced_search_system.constraint_checking.intelligent_constraint_relaxer import (- IntelligentConstraintRelaxer,- )-- relaxer = IntelligentConstraintRelaxer()-- result = relaxer._get_constraint_type("entity is called something")-- assert result == "NAME_PATTERN"-- def test_infers_location_from_text(self):- """Test inferring LOCATION type from text."""- from local_deep_research.advanced_search_system.constraint_checking.intelligent_constraint_relaxer import (- IntelligentConstraintRelaxer,- )-- relaxer = IntelligentConstraintRelaxer()-- result = relaxer._get_constraint_type("located in a country")-- assert result == "LOCATION"-- def test_infers_temporal_from_text(self):- """Test inferring TEMPORAL type from text."""- from local_deep_research.advanced_search_system.constraint_checking.intelligent_constraint_relaxer import (- IntelligentConstraintRelaxer,- )-- relaxer = IntelligentConstraintRelaxer()-- result = relaxer._get_constraint_type("in the year 2000")-- assert result == "TEMPORAL"-- def test_infers_statistic_from_text(self):- """Test inferring STATISTIC type from text."""- from local_deep_research.advanced_search_system.constraint_checking.intelligent_constraint_relaxer import (- IntelligentConstraintRelaxer,- )-- relaxer = IntelligentConstraintRelaxer()-- result = relaxer._get_constraint_type("has a number of items")-- assert result == "STATISTIC"-- def test_infers_event_from_text(self):- """Test inferring EVENT type from text."""- from local_deep_research.advanced_search_system.constraint_checking.intelligent_constraint_relaxer import (- IntelligentConstraintRelaxer,- )-- relaxer = IntelligentConstraintRelaxer()-- result = relaxer._get_constraint_type("an event occurred")-- assert result == "EVENT"-- def test_infers_comparison_from_text(self):- """Test inferring COMPARISON type from text."""- from local_deep_research.advanced_search_system.constraint_checking.intelligent_constraint_relaxer import (- IntelligentConstraintRelaxer,- )-- relaxer = IntelligentConstraintRelaxer()-- result = relaxer._get_constraint_type("more than average")-- assert result == "COMPARISON"-- def test_defaults_to_property(self):- """Test defaulting to PROPERTY when type can't be inferred."""- from local_deep_research.advanced_search_system.constraint_checking.intelligent_constraint_relaxer import (- IntelligentConstraintRelaxer,- )-- relaxer = IntelligentConstraintRelaxer()-- result = relaxer._get_constraint_type("some generic constraint")-- assert result == "PROPERTY"---class TestAnalyzeRelaxationImpact:- """Tests for analyze_relaxation_impact method."""-- def test_returns_analysis_dict(self):- """Test that analysis dict is returned."""- from local_deep_research.advanced_search_system.constraint_checking.intelligent_constraint_relaxer import (- IntelligentConstraintRelaxer,- )-- relaxer = IntelligentConstraintRelaxer()- original = [MockConstraint("c1", MockConstraintType.PROPERTY, "value")]- relaxed = []-- result = relaxer.analyze_relaxation_impact(original, relaxed)-- assert "original_count" in result- assert "relaxed_count" in result- assert "priority_impact" in result-- def test_counts_original_and_relaxed(self):- """Test counting original and relaxed constraints."""- from local_deep_research.advanced_search_system.constraint_checking.intelligent_constraint_relaxer import (- IntelligentConstraintRelaxer,- )-- relaxer = IntelligentConstraintRelaxer()- original = [- MockConstraint("c1", MockConstraintType.PROPERTY, "value1"),- MockConstraint("c2", MockConstraintType.PROPERTY, "value2"),- ]- relaxed = [MockConstraint("c1", MockConstraintType.PROPERTY, "value1")]-- result = relaxer.analyze_relaxation_impact(original, relaxed)-- assert result["original_count"] == 2- assert result["relaxed_count"] == 1- assert result["constraints_removed"] == 1-- def test_identifies_high_impact_removal(self):- """Test identifying high impact when NAME_PATTERN removed."""- from local_deep_research.advanced_search_system.constraint_checking.intelligent_constraint_relaxer import (- IntelligentConstraintRelaxer,- )-- relaxer = IntelligentConstraintRelaxer()- original = [- MockConstraint("c1", MockConstraintType.NAME_PATTERN, "name"),- MockConstraint("c2", MockConstraintType.PROPERTY, "prop"),- ]- relaxed = [MockConstraint("c2", MockConstraintType.PROPERTY, "prop")]-- result = relaxer.analyze_relaxation_impact(original, relaxed)-- assert result["priority_impact"] == "high"-- def test_identifies_medium_impact_removal(self):- """Test identifying medium impact when TEMPORAL removed."""- from local_deep_research.advanced_search_system.constraint_checking.intelligent_constraint_relaxer import (- IntelligentConstraintRelaxer,- )-- relaxer = IntelligentConstraintRelaxer()- original = [- MockConstraint("c1", MockConstraintType.TEMPORAL, "date"),- MockConstraint("c2", MockConstraintType.COMPARISON, "compare"),- ]- relaxed = [- MockConstraint("c2", MockConstraintType.COMPARISON, "compare")- ]-- result = relaxer.analyze_relaxation_impact(original, relaxed)-- assert result["priority_impact"] == "medium"-- def test_identifies_low_impact_removal(self):- """Test identifying low impact when only COMPARISON removed."""- from local_deep_research.advanced_search_system.constraint_checking.intelligent_constraint_relaxer import (- IntelligentConstraintRelaxer,- )-- relaxer = IntelligentConstraintRelaxer()- original = [- MockConstraint("c1", MockConstraintType.COMPARISON, "compare"),- MockConstraint("c2", MockConstraintType.STATISTIC, "stat"),- ]- relaxed = [MockConstraint("c2", MockConstraintType.STATISTIC, "stat")]-- result = relaxer.analyze_relaxation_impact(original, relaxed)-- assert result["priority_impact"] == "low"-- def test_includes_recommendation(self):- """Test that recommendation is included."""- from local_deep_research.advanced_search_system.constraint_checking.intelligent_constraint_relaxer import (- IntelligentConstraintRelaxer,- )-- relaxer = IntelligentConstraintRelaxer()- original = [MockConstraint("c1", MockConstraintType.PROPERTY, "value")]- relaxed = []-- result = relaxer.analyze_relaxation_impact(original, relaxed)-- assert "recommendation" in result- assert len(result["recommendation"]) > 0-- def test_tracks_removed_constraint_types(self):- """Test tracking removed constraint types."""- from local_deep_research.advanced_search_system.constraint_checking.intelligent_constraint_relaxer import (- IntelligentConstraintRelaxer,- )-- relaxer = IntelligentConstraintRelaxer()- original = [- MockConstraint("c1", MockConstraintType.COMPARISON, "compare"),- MockConstraint("c2", MockConstraintType.PROPERTY, "prop"),- ]- relaxed = [MockConstraint("c2", MockConstraintType.PROPERTY, "prop")]-- result = relaxer.analyze_relaxation_impact(original, relaxed)-- assert "removed_constraint_types" in result---class TestEdgeCases:- """Tests for edge cases."""-- def test_handles_empty_constraint_list(self):- """Test handling empty constraint list."""- from local_deep_research.advanced_search_system.constraint_checking.intelligent_constraint_relaxer import (- IntelligentConstraintRelaxer,- )-- relaxer = IntelligentConstraintRelaxer()-- result = relaxer.relax_constraints_progressively([], [])-- # Empty constraint list returns empty list (no relaxation strategies)- assert result == []-- def test_handles_single_constraint(self):- """Test handling single constraint."""- from local_deep_research.advanced_search_system.constraint_checking.intelligent_constraint_relaxer import (- IntelligentConstraintRelaxer,- )-- relaxer = IntelligentConstraintRelaxer()- relaxer.min_constraints = 1- constraints = [- MockConstraint("c1", MockConstraintType.PROPERTY, "value")- ]-- result = relaxer.relax_constraints_progressively(constraints, [])-- # Single constraint generates no progressive relaxation (nothing to remove)- # The implementation's for loop is range(1, min(1, 4)) = range(1, 1) = empty- assert isinstance(result, list)-- def test_handles_constraint_without_type(self):- """Test handling constraint without type attribute."""- from local_deep_research.advanced_search_system.constraint_checking.intelligent_constraint_relaxer import (- IntelligentConstraintRelaxer,- )-- relaxer = IntelligentConstraintRelaxer()-- result = relaxer._get_constraint_type("plain string constraint")-- assert result == "PROPERTY" # Default-- def test_relaxation_with_all_high_priority(self):- """Test relaxation when all constraints are high priority."""- from local_deep_research.advanced_search_system.constraint_checking.intelligent_constraint_relaxer import (- IntelligentConstraintRelaxer,- )-- relaxer = IntelligentConstraintRelaxer()- constraints = [- MockConstraint("c1", MockConstraintType.NAME_PATTERN, "name"),- MockConstraint("c2", MockConstraintType.EXISTENCE, "exists"),- MockConstraint("c3", MockConstraintType.LOCATION, "location"),- ]-- result = relaxer.relax_constraints_progressively(constraints, [])-- # Should still generate some strategies- assert len(result) >= 1-- def test_analyze_with_no_constraints_removed(self):- """Test analysis when no constraints removed."""- from local_deep_research.advanced_search_system.constraint_checking.intelligent_constraint_relaxer import (- IntelligentConstraintRelaxer,- )-- relaxer = IntelligentConstraintRelaxer()- constraints = [- MockConstraint("c1", MockConstraintType.PROPERTY, "value")- ]-- result = relaxer.analyze_relaxation_impact(constraints, constraints)-- assert result["constraints_removed"] == 0- assert result["priority_impact"] == "low"diff --git a/tests/advanced_search_system/constraint_checking/test_intelligent_constraint_relaxer_high_value.py b/tests/advanced_search_system/constraint_checking/test_intelligent_constraint_relaxer_high_value.pydeleted file mode 100644index a1f7cc959f..0000000000--- a/tests/advanced_search_system/constraint_checking/test_intelligent_constraint_relaxer_high_value.py+++ /dev/null@@ -1,437 +0,0 @@-"""-High-value pure logic tests for IntelligentConstraintRelaxer.--Tests cover constraint priorities, type inference, relaxation strategies-for statistical/comparison/temporal/property constraints, impact analysis,-and progressive relaxation logic.-"""--from unittest.mock import MagicMock---from local_deep_research.advanced_search_system.constraint_checking.intelligent_constraint_relaxer import (- IntelligentConstraintRelaxer,-)---class SimpleConstraint:- """A plain constraint object with a text value and str representation.-- Uses .value attribute so _create_relaxed_constraint updates it,- and __str__ returns .value so relaxed text is visible via str().- """-- def __init__(self, text):- self.value = text-- def __str__(self):- return self.value-- def __repr__(self):- return f"SimpleConstraint({self.value!r})"---def _make_constraint(text, ctype=None, constraint_type_attr=None):- """Helper to create a mock constraint with optional type attributes."""- obj = MagicMock()- obj.__str__ = lambda self: text- if ctype is not None:- obj.type = ctype- else:- del obj.type- if constraint_type_attr is not None:- obj.constraint_type = constraint_type_attr- else:- del obj.constraint_type- return obj---def _make_simple_constraint(text):- """Create a plain constraint with no type/constraint_type attrs.-- Uses SimpleConstraint so deepcopy and .value assignment work- correctly inside _create_relaxed_constraint.- """- return SimpleConstraint(text)---class TestConstraintPriorities:- """Tests for the constraint_priorities dictionary."""-- def test_name_pattern_has_highest_priority(self):- relaxer = IntelligentConstraintRelaxer()- assert relaxer.constraint_priorities["NAME_PATTERN"] == 10-- def test_comparison_has_lowest_priority(self):- relaxer = IntelligentConstraintRelaxer()- assert relaxer.constraint_priorities["COMPARISON"] == 1-- def test_statistic_lower_than_temporal(self):- relaxer = IntelligentConstraintRelaxer()- assert (- relaxer.constraint_priorities["STATISTIC"]- < relaxer.constraint_priorities["TEMPORAL"]- )-- def test_all_expected_types_present(self):- relaxer = IntelligentConstraintRelaxer()- expected = {- "NAME_PATTERN",- "EXISTENCE",- "LOCATION",- "TEMPORAL",- "PROPERTY",- "EVENT",- "STATISTIC",- "COMPARISON",- "RELATIONSHIP",- }- assert set(relaxer.constraint_priorities.keys()) == expected-- def test_min_constraints_default(self):- relaxer = IntelligentConstraintRelaxer()- assert relaxer.min_constraints == 2---class TestGetConstraintType:- """Tests for _get_constraint_type type inference."""-- def test_type_attribute_with_value(self):- relaxer = IntelligentConstraintRelaxer()- constraint = MagicMock()- constraint.type.value = "TEMPORAL"- assert relaxer._get_constraint_type(constraint) == "TEMPORAL"-- def test_type_attribute_without_value(self):- relaxer = IntelligentConstraintRelaxer()- constraint = MagicMock()- constraint.type = "LOCATION"- assert relaxer._get_constraint_type(constraint) == "LOCATION"-- def test_constraint_type_attribute(self):- relaxer = IntelligentConstraintRelaxer()- constraint = MagicMock()- del constraint.type- constraint.constraint_type = "EVENT"- assert relaxer._get_constraint_type(constraint) == "EVENT"-- def test_infer_name_pattern_from_text(self):- relaxer = IntelligentConstraintRelaxer()- constraint = _make_simple_constraint("entity called FooBar")- assert relaxer._get_constraint_type(constraint) == "NAME_PATTERN"-- def test_infer_location_from_text(self):- relaxer = IntelligentConstraintRelaxer()- constraint = _make_simple_constraint("located in country X")- assert relaxer._get_constraint_type(constraint) == "LOCATION"-- def test_infer_temporal_from_text(self):- relaxer = IntelligentConstraintRelaxer()- constraint = _make_simple_constraint("founded in year 1990")- assert relaxer._get_constraint_type(constraint) == "TEMPORAL"-- def test_infer_statistic_from_text(self):- relaxer = IntelligentConstraintRelaxer()- constraint = _make_simple_constraint("has a number of 500 employees")- assert relaxer._get_constraint_type(constraint) == "STATISTIC"-- def test_infer_event_from_text(self):- relaxer = IntelligentConstraintRelaxer()- constraint = _make_simple_constraint("this event happened recently")- assert relaxer._get_constraint_type(constraint) == "EVENT"-- def test_infer_comparison_from_text(self):- relaxer = IntelligentConstraintRelaxer()- constraint = _make_simple_constraint("bigger than the average")- assert relaxer._get_constraint_type(constraint) == "COMPARISON"-- def test_infer_property_fallback(self):- relaxer = IntelligentConstraintRelaxer()- constraint = _make_simple_constraint("is a multinational conglomerate")- assert relaxer._get_constraint_type(constraint) == "PROPERTY"---class TestRelaxStatisticalConstraint:- """Tests for _relax_statistical_constraint."""-- def test_number_gets_range_variations(self):- relaxer = IntelligentConstraintRelaxer()- constraint = _make_simple_constraint("has 100 employees")- variations = relaxer._relax_statistical_constraint(constraint)- assert len(variations) > 0- # Should contain range text- assert any("between" in str(v) for v in variations)-- def test_approximately_variation_created_when_fits_in_limit(self):- relaxer = IntelligentConstraintRelaxer()- # With a single number, 3 range + 1 approx = 4 total, but limit is 3- # So "approximately" may be cut off. Verify the approx version is generated- # before truncation by temporarily checking internal logic.- constraint = _make_simple_constraint("revenue of 500 million")- # The method creates 3 range + 1 approx per number, then truncates to 3.- # With 1 number: variations before truncation = 4, so approx is the 4th.- # Verify at least the range variations are correct.- variations = relaxer._relax_statistical_constraint(constraint)- assert len(variations) == 3- assert all("between" in str(v) for v in variations)-- def test_limited_to_three_variations(self):- relaxer = IntelligentConstraintRelaxer()- constraint = _make_simple_constraint("has 100 employees and 50 offices")- variations = relaxer._relax_statistical_constraint(constraint)- assert len(variations) <= 3-- def test_no_numbers_returns_empty(self):- relaxer = IntelligentConstraintRelaxer()- constraint = _make_simple_constraint("has many employees")- variations = relaxer._relax_statistical_constraint(constraint)- assert variations == []-- def test_range_boundaries_for_ten_percent(self):- relaxer = IntelligentConstraintRelaxer()- constraint = _make_simple_constraint("population is 1000")- variations = relaxer._relax_statistical_constraint(constraint)- # First variation should use 10% tolerance: between 900 and 1100- first_text = str(variations[0])- assert "900" in first_text- assert "1100" in first_text---class TestRelaxComparisonConstraint:- """Tests for _relax_comparison_constraint."""-- def test_largest_relaxed(self):- relaxer = IntelligentConstraintRelaxer()- constraint = _make_simple_constraint("the largest company")- variations = relaxer._relax_comparison_constraint(constraint)- assert any("one of the largest" in str(v) for v in variations)-- def test_exactly_relaxed_to_approximately(self):- relaxer = IntelligentConstraintRelaxer()- constraint = _make_simple_constraint("exactly 5 times bigger")- variations = relaxer._relax_comparison_constraint(constraint)- assert any("approximately" in str(v) for v in variations)-- def test_more_than_indicator_splits(self):- relaxer = IntelligentConstraintRelaxer()- constraint = _make_simple_constraint("revenue more than the competitor")- variations = relaxer._relax_comparison_constraint(constraint)- # Should have a variation with just the part before "more than"- assert any(- "revenue" in str(v) and "competitor" not in str(v)- for v in variations- )-- def test_no_comparison_terms_returns_empty(self):- relaxer = IntelligentConstraintRelaxer()- constraint = _make_simple_constraint("a blue widget")- variations = relaxer._relax_comparison_constraint(constraint)- assert variations == []-- def test_limited_to_three(self):- relaxer = IntelligentConstraintRelaxer()- # Contains many comparison terms- constraint = _make_simple_constraint(- "exactly the largest and highest and lowest compared to others"- )- variations = relaxer._relax_comparison_constraint(constraint)- assert len(variations) <= 3---class TestRelaxTemporalConstraint:- """Tests for _relax_temporal_constraint."""-- def test_year_expanded_to_decade(self):- relaxer = IntelligentConstraintRelaxer()- constraint = _make_simple_constraint("founded in 1985")- variations = relaxer._relax_temporal_constraint(constraint)- assert any("1980s" in str(v) for v in variations)-- def test_year_range_created(self):- relaxer = IntelligentConstraintRelaxer()- constraint = _make_simple_constraint("established in 2003")- variations = relaxer._relax_temporal_constraint(constraint)- assert any("between" in str(v) for v in variations)-- def test_founded_in_relaxed_to_around(self):- relaxer = IntelligentConstraintRelaxer()- # "founded in" without a year so only temporal_relaxations apply- constraint = _make_simple_constraint("founded in the early era")- variations = relaxer._relax_temporal_constraint(constraint)- assert any("around" in str(v) for v in variations)-- def test_no_year_no_temporal_terms_returns_empty(self):- relaxer = IntelligentConstraintRelaxer()- constraint = _make_simple_constraint("a big red ball")- variations = relaxer._relax_temporal_constraint(constraint)- assert variations == []-- def test_limited_to_three(self):- relaxer = IntelligentConstraintRelaxer()- constraint = _make_simple_constraint(- "founded in 1995 and established in 2000"- )- variations = relaxer._relax_temporal_constraint(constraint)- assert len(variations) <= 3---class TestRelaxPropertyConstraint:- """Tests for _relax_property_constraint."""-- def test_multinational_generalized(self):- relaxer = IntelligentConstraintRelaxer()- constraint = _make_simple_constraint("a multinational corporation")- variations = relaxer._relax_property_constraint(constraint)- assert any("international" in str(v) for v in variations)-- def test_corporation_to_company(self):- relaxer = IntelligentConstraintRelaxer()- constraint = _make_simple_constraint("a large corporation")- variations = relaxer._relax_property_constraint(constraint)- assert any("company" in str(v) for v in variations)-- def test_adjectives_removed(self):- relaxer = IntelligentConstraintRelaxer()- constraint = _make_simple_constraint("extremely large building")- variations = relaxer._relax_property_constraint(constraint)- assert any("large building" in str(v) for v in variations)-- def test_limited_to_two(self):- relaxer = IntelligentConstraintRelaxer()- constraint = _make_simple_constraint(- "a very specialized multinational conglomerate with headquarters"- )- variations = relaxer._relax_property_constraint(constraint)- assert len(variations) <= 2-- def test_no_matching_terms_returns_empty(self):- relaxer = IntelligentConstraintRelaxer()- constraint = _make_simple_constraint("a blue widget")- variations = relaxer._relax_property_constraint(constraint)- assert variations == []---class TestAnalyzeRelaxationImpact:- """Tests for analyze_relaxation_impact."""-- def test_counts_correct(self):- relaxer = IntelligentConstraintRelaxer()- orig = [_make_simple_constraint("x")] * 5- relaxed = [_make_simple_constraint("x")] * 3- result = relaxer.analyze_relaxation_impact(orig, relaxed)- assert result["original_count"] == 5- assert result["relaxed_count"] == 3- assert result["constraints_removed"] == 2-- def test_high_impact_when_name_removed(self):- relaxer = IntelligentConstraintRelaxer()- orig = [- _make_simple_constraint("entity called Foo"),- _make_simple_constraint("some prop"),- ]- relaxed = [_make_simple_constraint("some prop")]- result = relaxer.analyze_relaxation_impact(orig, relaxed)- assert result["priority_impact"] == "high"-- def test_medium_impact_when_temporal_removed(self):- relaxer = IntelligentConstraintRelaxer()- orig = [- _make_simple_constraint("founded in year 2000"),- _make_simple_constraint("is a widget"),- ]- # Only keep the property constraint- relaxed = [_make_simple_constraint("is a widget")]- result = relaxer.analyze_relaxation_impact(orig, relaxed)- assert result["priority_impact"] == "medium"-- def test_low_impact_when_only_comparison_removed(self):- relaxer = IntelligentConstraintRelaxer()- orig = [- _make_simple_constraint("bigger than average"),- _make_simple_constraint("is a widget"),- ]- # Both still present in relaxed (same types)- relaxed = [_make_simple_constraint("is a widget")]- result = relaxer.analyze_relaxation_impact(orig, relaxed)- # COMPARISON removed, which is low impact- assert result["priority_impact"] == "low"-- def test_empty_inputs(self):- relaxer = IntelligentConstraintRelaxer()- result = relaxer.analyze_relaxation_impact([], [])- assert result["original_count"] == 0- assert result["constraints_removed"] == 0- assert result["priority_impact"] == "low"---class TestRelaxConstraintsProgressively:- """Tests for relax_constraints_progressively."""-- def test_sufficient_candidates_returns_original(self):- relaxer = IntelligentConstraintRelaxer()- constraints = [- _make_simple_constraint("a"),- _make_simple_constraint("b"),- ]- candidates = [MagicMock() for _ in range(5)]- result = relaxer.relax_constraints_progressively(- constraints, candidates, target_candidates=5- )- assert result == [constraints]-- def test_insufficient_candidates_returns_relaxed_sets(self):- relaxer = IntelligentConstraintRelaxer()- constraints = [- _make_simple_constraint("entity called Foo"),- _make_simple_constraint("located in country X"),- _make_simple_constraint("bigger than average"),- _make_simple_constraint("has 100 employees"),- ]- result = relaxer.relax_constraints_progressively(- constraints, [], target_candidates=5- )- assert len(result) > 0-- def test_single_constraint_below_min_no_removal(self):- relaxer = IntelligentConstraintRelaxer()- constraints = [_make_simple_constraint("a widget")]- result = relaxer.relax_constraints_progressively(- constraints, [], target_candidates=5- )- # With only 1 constraint, removal would go below min_constraints=2- # So progressive removal sets should not include sets below min- for constraint_set in result:- # All sets should have at least 1 element (the original or variation)- assert len(constraint_set) >= 1-- def test_deduplication_of_relaxed_sets(self):- relaxer = IntelligentConstraintRelaxer()- constraints = [- _make_simple_constraint("entity called Foo"),- _make_simple_constraint("located in country X"),- _make_simple_constraint("is a widget"),- ]- result = relaxer.relax_constraints_progressively(- constraints, [], target_candidates=5- )- # Check no duplicate sets- signatures = [tuple(sorted(str(c) for c in cs)) for cs in result]- assert len(signatures) == len(set(signatures))-- def test_high_priority_only_set_included(self):- relaxer = IntelligentConstraintRelaxer()- # Create constraints with priority >= 7 and < 7- constraints = [- _make_simple_constraint("entity called Foo"), # NAME_PATTERN=10- _make_simple_constraint("located in country X"), # LOCATION=8- _make_simple_constraint("founded in year 2000"), # TEMPORAL=7- _make_simple_constraint("bigger than average"), # COMPARISON=1- ]- result = relaxer.relax_constraints_progressively(- constraints, [], target_candidates=5- )- # At least one set should have exactly the high-priority constraints- set_sizes = [len(cs) for cs in result]- assert (- 3 in set_sizes- ) # 3 high-priority constraints (NAME, LOCATION, TEMPORAL)diff --git a/tests/advanced_search_system/evidence/test_requirements.py b/tests/advanced_search_system/evidence/test_requirements.pydeleted file mode 100644index c0b2bb7f14..0000000000--- a/tests/advanced_search_system/evidence/test_requirements.py+++ /dev/null@@ -1,321 +0,0 @@-"""-Tests for advanced_search_system/evidence/requirements.py--Tests cover:-- EvidenceRequirements.get_requirements method-- EvidenceRequirements.get_minimum_confidence method-- Different constraint types-"""---class TestGetRequirements:- """Tests for EvidenceRequirements.get_requirements method."""-- def test_property_constraint_requirements(self):- """Test requirements for PROPERTY constraint."""- from local_deep_research.advanced_search_system.evidence.requirements import (- EvidenceRequirements,- )- from local_deep_research.advanced_search_system.constraints.base_constraint import (- ConstraintType,- )-- reqs = EvidenceRequirements.get_requirements(ConstraintType.PROPERTY)-- assert "preferred" in reqs- assert "acceptable" in reqs- assert "sources" in reqs- assert "direct_statement" in reqs["preferred"]- assert "official_record" in reqs["preferred"]-- def test_name_pattern_constraint_requirements(self):- """Test requirements for NAME_PATTERN constraint."""- from local_deep_research.advanced_search_system.evidence.requirements import (- EvidenceRequirements,- )- from local_deep_research.advanced_search_system.constraints.base_constraint import (- ConstraintType,- )-- reqs = EvidenceRequirements.get_requirements(- ConstraintType.NAME_PATTERN- )-- assert "etymology sources" in reqs["sources"]- assert "naming databases" in reqs["sources"]-- def test_event_constraint_requirements(self):- """Test requirements for EVENT constraint."""- from local_deep_research.advanced_search_system.evidence.requirements import (- EvidenceRequirements,- )- from local_deep_research.advanced_search_system.constraints.base_constraint import (- ConstraintType,- )-- reqs = EvidenceRequirements.get_requirements(ConstraintType.EVENT)-- assert "news_report" in reqs["preferred"]- assert "official_record" in reqs["preferred"]- assert "news archives" in reqs["sources"]-- def test_statistic_constraint_requirements(self):- """Test requirements for STATISTIC constraint."""- from local_deep_research.advanced_search_system.evidence.requirements import (- EvidenceRequirements,- )- from local_deep_research.advanced_search_system.constraints.base_constraint import (- ConstraintType,- )-- reqs = EvidenceRequirements.get_requirements(ConstraintType.STATISTIC)-- assert "statistical_data" in reqs["preferred"]- assert "government databases" in reqs["sources"]-- def test_temporal_constraint_requirements(self):- """Test requirements for TEMPORAL constraint."""- from local_deep_research.advanced_search_system.evidence.requirements import (- EvidenceRequirements,- )- from local_deep_research.advanced_search_system.constraints.base_constraint import (- ConstraintType,- )-- reqs = EvidenceRequirements.get_requirements(ConstraintType.TEMPORAL)-- assert "official_record" in reqs["preferred"]- assert "archives" in reqs["sources"]-- def test_location_constraint_requirements(self):- """Test requirements for LOCATION constraint."""- from local_deep_research.advanced_search_system.evidence.requirements import (- EvidenceRequirements,- )- from local_deep_research.advanced_search_system.constraints.base_constraint import (- ConstraintType,- )-- reqs = EvidenceRequirements.get_requirements(ConstraintType.LOCATION)-- assert "geographical_data" in reqs["preferred"]- assert "maps" in reqs["sources"]-- def test_comparison_constraint_requirements(self):- """Test requirements for COMPARISON constraint."""- from local_deep_research.advanced_search_system.evidence.requirements import (- EvidenceRequirements,- )- from local_deep_research.advanced_search_system.constraints.base_constraint import (- ConstraintType,- )-- reqs = EvidenceRequirements.get_requirements(ConstraintType.COMPARISON)-- assert "research_finding" in reqs["preferred"]- assert "comparative studies" in reqs["sources"]-- def test_existence_constraint_requirements(self):- """Test requirements for EXISTENCE constraint."""- from local_deep_research.advanced_search_system.evidence.requirements import (- EvidenceRequirements,- )- from local_deep_research.advanced_search_system.constraints.base_constraint import (- ConstraintType,- )-- reqs = EvidenceRequirements.get_requirements(ConstraintType.EXISTENCE)-- assert "direct_statement" in reqs["preferred"]- assert "official registries" in reqs["sources"]-- def test_unknown_constraint_returns_default(self):- """Test that unknown constraint returns default requirements."""- from local_deep_research.advanced_search_system.evidence.requirements import (- EvidenceRequirements,- )- from local_deep_research.advanced_search_system.constraints.base_constraint import (- ConstraintType,- )-- # Use a constraint type that might not have specific requirements- # Since all defined types are covered, test with CUSTOM if it exists- # or verify the default fallback structure- reqs = EvidenceRequirements.get_requirements(ConstraintType.PROPERTY)-- # Verify structure- assert isinstance(reqs, dict)- assert "preferred" in reqs- assert "acceptable" in reqs- assert "sources" in reqs---class TestGetMinimumConfidence:- """Tests for EvidenceRequirements.get_minimum_confidence method."""-- def test_statistic_requires_high_confidence(self):- """Test STATISTIC requires highest confidence."""- from local_deep_research.advanced_search_system.evidence.requirements import (- EvidenceRequirements,- )- from local_deep_research.advanced_search_system.constraints.base_constraint import (- ConstraintType,- )-- confidence = EvidenceRequirements.get_minimum_confidence(- ConstraintType.STATISTIC- )-- assert confidence == 0.8-- def test_event_requires_moderate_confidence(self):- """Test EVENT requires moderate confidence."""- from local_deep_research.advanced_search_system.evidence.requirements import (- EvidenceRequirements,- )- from local_deep_research.advanced_search_system.constraints.base_constraint import (- ConstraintType,- )-- confidence = EvidenceRequirements.get_minimum_confidence(- ConstraintType.EVENT- )-- assert confidence == 0.7-- def test_property_requires_some_flexibility(self):- """Test PROPERTY has some flexibility."""- from local_deep_research.advanced_search_system.evidence.requirements import (- EvidenceRequirements,- )- from local_deep_research.advanced_search_system.constraints.base_constraint import (- ConstraintType,- )-- confidence = EvidenceRequirements.get_minimum_confidence(- ConstraintType.PROPERTY- )-- assert confidence == 0.6-- def test_name_pattern_is_interpretive(self):- """Test NAME_PATTERN allows interpretation."""- from local_deep_research.advanced_search_system.evidence.requirements import (- EvidenceRequirements,- )- from local_deep_research.advanced_search_system.constraints.base_constraint import (- ConstraintType,- )-- confidence = EvidenceRequirements.get_minimum_confidence(- ConstraintType.NAME_PATTERN- )-- assert confidence == 0.5-- def test_unknown_constraint_returns_default(self):- """Test unknown constraint returns default confidence."""- from local_deep_research.advanced_search_system.evidence.requirements import (- EvidenceRequirements,- )- from local_deep_research.advanced_search_system.constraints.base_constraint import (- ConstraintType,- )-- # For constraints not in the thresholds dict- confidence = EvidenceRequirements.get_minimum_confidence(- ConstraintType.TEMPORAL- )-- assert confidence == 0.6 # Default-- def test_confidence_ordering(self):- """Test that confidence requirements are logically ordered."""- from local_deep_research.advanced_search_system.evidence.requirements import (- EvidenceRequirements,- )- from local_deep_research.advanced_search_system.constraints.base_constraint import (- ConstraintType,- )-- statistic = EvidenceRequirements.get_minimum_confidence(- ConstraintType.STATISTIC- )- event = EvidenceRequirements.get_minimum_confidence(- ConstraintType.EVENT- )- property_conf = EvidenceRequirements.get_minimum_confidence(- ConstraintType.PROPERTY- )- name_pattern = EvidenceRequirements.get_minimum_confidence(- ConstraintType.NAME_PATTERN- )-- # Statistics need highest accuracy- assert statistic > event- assert event > property_conf- assert property_conf > name_pattern---class TestRequirementsStructure:- """Tests for the structure of requirements."""-- def test_all_requirements_have_three_keys(self):- """Test all requirements have preferred, acceptable, sources."""- from local_deep_research.advanced_search_system.evidence.requirements import (- EvidenceRequirements,- )- from local_deep_research.advanced_search_system.constraints.base_constraint import (- ConstraintType,- )-- constraint_types = [- ConstraintType.PROPERTY,- ConstraintType.NAME_PATTERN,- ConstraintType.EVENT,- ConstraintType.STATISTIC,- ConstraintType.TEMPORAL,- ConstraintType.LOCATION,- ConstraintType.COMPARISON,- ConstraintType.EXISTENCE,- ]-- for ct in constraint_types:- reqs = EvidenceRequirements.get_requirements(ct)- assert "preferred" in reqs, f"Missing 'preferred' for {ct}"- assert "acceptable" in reqs, f"Missing 'acceptable' for {ct}"- assert "sources" in reqs, f"Missing 'sources' for {ct}"-- def test_preferred_and_acceptable_are_lists(self):- """Test that preferred and acceptable are lists."""- from local_deep_research.advanced_search_system.evidence.requirements import (- EvidenceRequirements,- )- from local_deep_research.advanced_search_system.constraints.base_constraint import (- ConstraintType,- )-- reqs = EvidenceRequirements.get_requirements(ConstraintType.PROPERTY)-- assert isinstance(reqs["preferred"], list)- assert isinstance(reqs["acceptable"], list)- assert isinstance(reqs["sources"], list)-- def test_sources_are_non_empty(self):- """Test that sources lists are non-empty."""- from local_deep_research.advanced_search_system.evidence.requirements import (- EvidenceRequirements,- )- from local_deep_research.advanced_search_system.constraints.base_constraint import (- ConstraintType,- )-- constraint_types = [- ConstraintType.PROPERTY,- ConstraintType.EVENT,- ConstraintType.STATISTIC,- ]-- for ct in constraint_types:- reqs = EvidenceRequirements.get_requirements(ct)- assert len(reqs["sources"]) > 0, f"Empty sources for {ct}"diff --git a/tests/advanced_search_system/evidence/test_requirements_high_value.py b/tests/advanced_search_system/evidence/test_requirements_high_value.pydeleted file mode 100644index 117287821d..0000000000--- a/tests/advanced_search_system/evidence/test_requirements_high_value.py+++ /dev/null@@ -1,187 +0,0 @@-"""-High-value tests for EvidenceRequirements - pure logic, no mocking needed.--Tests get_requirements() and get_minimum_confidence() static methods-across all ConstraintType values and edge cases.-"""--import pytest--from local_deep_research.advanced_search_system.constraints.base_constraint import (- ConstraintType,-)-from local_deep_research.advanced_search_system.evidence.requirements import (- EvidenceRequirements,-)--REQUIRED_KEYS = {"preferred", "acceptable", "sources"}-ALL_CONSTRAINT_TYPES = list(ConstraintType)---# ----------------------------------------------------------------------------# get_requirements: structural tests for all 8 constraint types-# ------------------------------------------------------------------------------class TestGetRequirementsStructure:- """Every ConstraintType should return a dict with the correct keys and non-empty lists."""-- @pytest.mark.parametrize("ctype", ALL_CONSTRAINT_TYPES)- def test_returns_dict_with_required_keys(self, ctype: ConstraintType):- result = EvidenceRequirements.get_requirements(ctype)- assert isinstance(result, dict)- assert set(result.keys()) == REQUIRED_KEYS-- @pytest.mark.parametrize("ctype", ALL_CONSTRAINT_TYPES)- def test_preferred_is_non_empty_list(self, ctype: ConstraintType):- result = EvidenceRequirements.get_requirements(ctype)- assert isinstance(result["preferred"], list)- assert len(result["preferred"]) > 0-- @pytest.mark.parametrize("ctype", ALL_CONSTRAINT_TYPES)- def test_acceptable_is_non_empty_list(self, ctype: ConstraintType):- result = EvidenceRequirements.get_requirements(ctype)- assert isinstance(result["acceptable"], list)- assert len(result["acceptable"]) > 0-- @pytest.mark.parametrize("ctype", ALL_CONSTRAINT_TYPES)- def test_sources_is_non_empty_list(self, ctype: ConstraintType):- result = EvidenceRequirements.get_requirements(ctype)- assert isinstance(result["sources"], list)- assert len(result["sources"]) > 0---# ----------------------------------------------------------------------------# get_requirements: specific preferred evidence per type-# ------------------------------------------------------------------------------class TestGetRequirementsPreferred:- """Verify the expected preferred evidence types for key constraint types."""-- def test_property_has_direct_statement_preferred(self):- result = EvidenceRequirements.get_requirements(ConstraintType.PROPERTY)- assert "direct_statement" in result["preferred"]-- def test_property_has_official_record_preferred(self):- result = EvidenceRequirements.get_requirements(ConstraintType.PROPERTY)- assert "official_record" in result["preferred"]-- def test_name_pattern_has_linguistic_analysis_preferred(self):- result = EvidenceRequirements.get_requirements(- ConstraintType.NAME_PATTERN- )- assert "linguistic_analysis" in result["preferred"]-- def test_event_has_news_report_preferred(self):- result = EvidenceRequirements.get_requirements(ConstraintType.EVENT)- assert "news_report" in result["preferred"]-- def test_statistic_has_statistical_data_preferred(self):- result = EvidenceRequirements.get_requirements(ConstraintType.STATISTIC)- assert "statistical_data" in result["preferred"]-- def test_temporal_has_official_record_preferred(self):- result = EvidenceRequirements.get_requirements(ConstraintType.TEMPORAL)- assert "official_record" in result["preferred"]-- def test_location_has_geographical_data_preferred(self):- result = EvidenceRequirements.get_requirements(ConstraintType.LOCATION)- assert "geographical_data" in result["preferred"]-- def test_comparison_has_statistical_comparison_preferred(self):- result = EvidenceRequirements.get_requirements(- ConstraintType.COMPARISON- )- assert "statistical_comparison" in result["preferred"]-- def test_existence_has_direct_statement_preferred(self):- result = EvidenceRequirements.get_requirements(ConstraintType.EXISTENCE)- assert "direct_statement" in result["preferred"]---# ----------------------------------------------------------------------------# get_requirements: default / unknown type fallback-# ------------------------------------------------------------------------------class TestGetRequirementsDefault:- """An unrecognized constraint type should fall back to a safe default."""-- def test_unknown_type_returns_dict_with_required_keys(self):- fake_type = "not_a_real_type"- result = EvidenceRequirements.get_requirements(fake_type)- assert set(result.keys()) == REQUIRED_KEYS-- def test_unknown_type_preferred_is_direct_statement(self):- fake_type = "not_a_real_type"- result = EvidenceRequirements.get_requirements(fake_type)- assert result["preferred"] == ["direct_statement"]-- def test_unknown_type_acceptable_is_inference(self):- fake_type = "not_a_real_type"- result = EvidenceRequirements.get_requirements(fake_type)- assert result["acceptable"] == ["inference"]-- def test_unknown_type_sources_is_general(self):- fake_type = "not_a_real_type"- result = EvidenceRequirements.get_requirements(fake_type)- assert result["sources"] == ["general sources"]---# ----------------------------------------------------------------------------# get_minimum_confidence: explicit thresholds-# ------------------------------------------------------------------------------class TestGetMinimumConfidence:- """Verify the explicit confidence thresholds for mapped types."""-- def test_statistic_confidence_is_0_8(self):- assert (- EvidenceRequirements.get_minimum_confidence(- ConstraintType.STATISTIC- )- == 0.8- )-- def test_event_confidence_is_0_7(self):- assert (- EvidenceRequirements.get_minimum_confidence(ConstraintType.EVENT)- == 0.7- )-- def test_property_confidence_is_0_6(self):- assert (- EvidenceRequirements.get_minimum_confidence(ConstraintType.PROPERTY)- == 0.6- )-- def test_name_pattern_confidence_is_0_5(self):- assert (- EvidenceRequirements.get_minimum_confidence(- ConstraintType.NAME_PATTERN- )- == 0.5- )---# ----------------------------------------------------------------------------# get_minimum_confidence: default threshold for unmapped types-# ------------------------------------------------------------------------------class TestGetMinimumConfidenceDefault:- """Types not in the explicit threshold map should return the default 0.6."""-- @pytest.mark.parametrize(- "ctype",- [- ConstraintType.TEMPORAL,- ConstraintType.LOCATION,- ConstraintType.COMPARISON,- ConstraintType.EXISTENCE,- ],- )- def test_unmapped_type_returns_default_0_6(self, ctype: ConstraintType):- assert EvidenceRequirements.get_minimum_confidence(ctype) == 0.6diff --git a/tests/advanced_search_system/query_generation/test_adaptive_query_gen_edge_cases.py b/tests/advanced_search_system/query_generation/test_adaptive_query_gen_edge_cases.pydeleted file mode 100644index 5a136120a6..0000000000--- a/tests/advanced_search_system/query_generation/test_adaptive_query_gen_edge_cases.py+++ /dev/null@@ -1,241 +0,0 @@-"""High-value edge case tests for query_generation/adaptive_query_generator.py.--Tests pattern initialization, constraint-to-template mapping, expansion logic,-pattern extraction, and fallback query generation.-"""--from unittest.mock import MagicMock--from local_deep_research.advanced_search_system.query_generation.adaptive_query_generator import (- AdaptiveQueryGenerator,- QueryPattern,-)-from local_deep_research.advanced_search_system.constraints.base_constraint import (- Constraint,- ConstraintType,-)---def _make_constraint(- ctype, value="test", desc="test desc", weight=1.0, cid=None-):- return Constraint(- id=cid or f"{ctype.value}_{value}",- type=ctype,- value=value,- description=desc,- weight=weight,- )---def _make_generator():- mock_model = MagicMock()- mock_model.invoke.return_value = MagicMock(content="mock response")- return AdaptiveQueryGenerator(mock_model)---class TestQueryPatternDataclass:- """Test QueryPattern dataclass behavior."""-- def test_discovered_entities_independent_per_instance(self):- """Each instance has its own discovered_entities set."""- p1 = QueryPattern(- template="t",- constraint_types=[],- success_rate=0.5,- example_queries=[],- discovered_entities=set(),- )- p2 = QueryPattern(- template="t",- constraint_types=[],- success_rate=0.5,- example_queries=[],- discovered_entities=set(),- )- p1.discovered_entities.add("entity1")- assert "entity1" not in p2.discovered_entities---class TestInitializeDefaultPatterns:- """Test default pattern initialization."""-- def test_three_default_patterns(self):- """Generator starts with exactly 3 default patterns."""- gen = _make_generator()- assert len(gen.successful_patterns) == 3-- def test_default_pattern_success_rates(self):- """Default patterns have documented success rates."""- gen = _make_generator()- rates = [p.success_rate for p in gen.successful_patterns]- assert 0.7 in rates- assert 0.6 in rates- assert 0.65 in rates-- def test_default_pattern_constraint_types(self):- """Default patterns have expected constraint types."""- gen = _make_generator()- first_types = gen.successful_patterns[0].constraint_types- assert ConstraintType.NAME_PATTERN in first_types---class TestGenerateFromPatterns:- """Test _generate_from_patterns."""-- def test_no_matching_pattern_returns_none(self):- """Returns None when no pattern matches constraints."""- gen = _make_generator()- constraints = [_make_constraint(ConstraintType.EXISTENCE, "test")]- assert gen._generate_from_patterns(constraints) is None-- def test_name_pattern_fills_entity_alias(self):- """NAME_PATTERN constraint fills both 'name_pattern' and 'entity'."""- gen = _make_generator()- constraints = [- _make_constraint(ConstraintType.NAME_PATTERN, "mountain"),- _make_constraint(ConstraintType.PROPERTY, "formed"),- _make_constraint(ConstraintType.LOCATION, "Colorado"),- ]- result = gen._generate_from_patterns(constraints)- assert result is not None- assert "mountain" in result-- def test_comparison_fills_both_vars(self):- """COMPARISON constraint fills both 'comparison' and 'value'."""- gen = _make_generator()- constraints = [- _make_constraint(ConstraintType.NAME_PATTERN, "body part"),- _make_constraint(ConstraintType.COMPARISON, "84.5 times"),- ]- result = gen._generate_from_patterns(constraints)- assert result is not None- assert "84.5 times" in result---class TestGenerateWithExpansion:- """Test _generate_with_expansion."""-- def test_single_constraint_no_expansion_quoted(self):- """Single constraint with no expansions returns quoted value."""- gen = _make_generator()- gen.semantic_expansions["test_val"] = []- constraints = [- _make_constraint(ConstraintType.NAME_PATTERN, "test_val")- ]- result = gen._generate_with_expansion(constraints)- assert result == '"test_val"'-- def test_expansion_limited_to_two(self):- """Only first 2 expansions are used in the OR clause."""- gen = _make_generator()- gen.semantic_expansions["val"] = ['"alt1"', '"alt2"', '"alt3"']- constraints = [_make_constraint(ConstraintType.NAME_PATTERN, "val")]- result = gen._generate_with_expansion(constraints)- assert '"alt1"' in result- assert '"alt2"' in result- assert '"alt3"' not in result---class TestUpdatePatterns:- """Test update_patterns."""-- def test_failed_query_added_to_failed_set(self):- """Failed query is added to failed_queries."""- gen = _make_generator()- constraints = [_make_constraint(ConstraintType.NAME_PATTERN, "test")]- gen.update_patterns(- "failed query", constraints, success=False, entities_found=[]- )- assert "failed query" in gen.failed_queries-- def test_successful_update_adds_to_combinations(self):- """Successful update records constraint combination."""- gen = _make_generator()- c1 = _make_constraint(ConstraintType.LOCATION, "place")- gen.update_patterns('"place" results', [c1], True, ["entity1"])- # Should have at least one entry in constraint_combinations- assert len(gen.constraint_combinations) >= 1---class TestExtractPattern:- """Test _extract_pattern."""-- def test_new_pattern_has_success_rate_one(self):- """Extracted patterns start with success_rate=1.0."""- gen = _make_generator()- constraints = [_make_constraint(ConstraintType.NAME_PATTERN, "test")]- pattern = gen._extract_pattern('"test" results', constraints)- assert pattern is not None- assert pattern.success_rate == 1.0-- def test_returns_none_when_no_placeholders(self):- """Returns None when constraint value not found in query."""- gen = _make_generator()- constraints = [- _make_constraint(ConstraintType.NAME_PATTERN, "not_in_query")- ]- pattern = gen._extract_pattern("completely different text", constraints)- assert pattern is None---class TestFormatConstraints:- """Test _format_constraints."""-- def test_empty_list_returns_empty_string(self):- gen = _make_generator()- assert gen._format_constraints([]) == ""-- def test_formats_each_constraint(self):- gen = _make_generator()- constraints = [- _make_constraint(ConstraintType.NAME_PATTERN, "val1", "desc1"),- _make_constraint(ConstraintType.LOCATION, "val2", "desc2"),- ]- result = gen._format_constraints(constraints)- lines = result.strip().split("\n")- assert len(lines) == 2- assert "val1" in lines[0]- assert "val2" in lines[1]---class TestGenerateSingleConstraintQuery:- """Test _generate_single_constraint_query for each ConstraintType."""-- def _gen(self):- return _make_generator()-- def test_name_pattern_template(self):- c = _make_constraint(ConstraintType.NAME_PATTERN, "mountain")- result = self._gen()._generate_single_constraint_query(c)- assert '"mountain"' in result-- def test_location_template(self):- c = _make_constraint(ConstraintType.LOCATION, "Colorado")- result = self._gen()._generate_single_constraint_query(c)- assert '"Colorado"' in result-- def test_property_template(self):- c = _make_constraint(ConstraintType.PROPERTY, "weight")- result = self._gen()._generate_single_constraint_query(c)- assert '"weight"' in result-- def test_statistic_template(self):- c = _make_constraint(ConstraintType.STATISTIC, "84.5x")- result = self._gen()._generate_single_constraint_query(c)- assert '"84.5x"' in result-- def test_comparison_template(self):- c = _make_constraint(ConstraintType.COMPARISON, "greater than")- result = self._gen()._generate_single_constraint_query(c)- assert '"greater than"' in result-- def test_existence_template(self):- c = _make_constraint(ConstraintType.EXISTENCE, "viewpoint")- result = self._gen()._generate_single_constraint_query(c)- assert '"viewpoint"' in result-- def test_temporal_template(self):- c = _make_constraint(ConstraintType.TEMPORAL, "2000-2021")- result = self._gen()._generate_single_constraint_query(c)- assert "2000-2021" in resultdiff --git a/tests/advanced_search_system/query_generation/test_adaptive_query_generator_extended.py b/tests/advanced_search_system/query_generation/test_adaptive_query_generator_extended.pydeleted file mode 100644index c7178aba6f..0000000000--- a/tests/advanced_search_system/query_generation/test_adaptive_query_generator_extended.py+++ /dev/null@@ -1,1446 +0,0 @@-"""-Extended tests for AdaptiveQueryGenerator - Adaptive query generation system.--Tests cover:-- QueryPattern dataclass-- AdaptiveQueryGenerator initialization-- Default pattern initialization-- Pattern-based query generation-- Semantic expansion-- LLM-based query generation-- Pattern updates-- Fallback query generation-- Constraint combination optimization--These tests import and test the ACTUAL AdaptiveQueryGenerator class with mocked LLM.-"""--from collections import defaultdict-from unittest.mock import MagicMock---from local_deep_research.advanced_search_system.query_generation.adaptive_query_generator import (- AdaptiveQueryGenerator,- QueryPattern,-)-from local_deep_research.advanced_search_system.constraints.base_constraint import (- Constraint,- ConstraintType,-)---class TestQueryPatternDataclass:- """Tests for QueryPattern dataclass."""-- def test_query_pattern_has_template(self):- """QueryPattern should have template field."""- pattern = QueryPattern(- template='"{entity}" {property}',- constraint_types=[- ConstraintType.NAME_PATTERN,- ConstraintType.PROPERTY,- ],- success_rate=0.7,- example_queries=["test query"],- discovered_entities=set(),- )- assert pattern.template == '"{entity}" {property}'-- def test_query_pattern_has_constraint_types(self):- """QueryPattern should have constraint_types field."""- pattern = QueryPattern(- template="template",- constraint_types=[- ConstraintType.NAME_PATTERN,- ConstraintType.PROPERTY,- ],- success_rate=0.6,- example_queries=[],- discovered_entities=set(),- )- assert len(pattern.constraint_types) == 2- assert ConstraintType.NAME_PATTERN in pattern.constraint_types-- def test_query_pattern_has_success_rate(self):- """QueryPattern should have success_rate field."""- pattern = QueryPattern(- template="template",- constraint_types=[],- success_rate=0.75,- example_queries=[],- discovered_entities=set(),- )- assert pattern.success_rate == 0.75-- def test_query_pattern_has_example_queries(self):- """QueryPattern should have example_queries field."""- pattern = QueryPattern(- template="template",- constraint_types=[],- success_rate=0.5,- example_queries=["query1", "query2"],- discovered_entities=set(),- )- assert len(pattern.example_queries) == 2-- def test_query_pattern_has_discovered_entities(self):- """QueryPattern should have discovered_entities field."""- pattern = QueryPattern(- template="template",- constraint_types=[],- success_rate=0.5,- example_queries=[],- discovered_entities={"entity1", "entity2"},- )- assert len(pattern.discovered_entities) == 2---class TestAdaptiveQueryGeneratorInitialization:- """Tests for AdaptiveQueryGenerator initialization."""-- def test_model_assignment(self):- """Should assign model on initialization."""- mock_model = MagicMock()- generator = AdaptiveQueryGenerator(model=mock_model)- assert generator.model == mock_model-- def test_successful_patterns_initialized(self):- """successful_patterns should be initialized as list with defaults."""- mock_model = MagicMock()- generator = AdaptiveQueryGenerator(model=mock_model)- assert isinstance(generator.successful_patterns, list)- assert len(generator.successful_patterns) > 0 # Has default patterns-- def test_failed_queries_initialized(self):- """failed_queries should be initialized as set."""- mock_model = MagicMock()- generator = AdaptiveQueryGenerator(model=mock_model)- assert isinstance(generator.failed_queries, set)- assert len(generator.failed_queries) == 0-- def test_semantic_expansions_initialized(self):- """semantic_expansions should be initialized as dict."""- mock_model = MagicMock()- generator = AdaptiveQueryGenerator(model=mock_model)- assert isinstance(generator.semantic_expansions, dict)- assert len(generator.semantic_expansions) == 0-- def test_constraint_combinations_initialized(self):- """constraint_combinations should be initialized as defaultdict."""- mock_model = MagicMock()- generator = AdaptiveQueryGenerator(model=mock_model)- assert isinstance(generator.constraint_combinations, defaultdict)---class TestDefaultPatternInitialization:- """Tests for _initialize_default_patterns method."""-- def test_creates_default_patterns(self):- """Should create default patterns."""- mock_model = MagicMock()- generator = AdaptiveQueryGenerator(model=mock_model)-- assert len(generator.successful_patterns) >= 3-- def test_entity_location_pattern(self):- """Should have entity-location pattern."""- mock_model = MagicMock()- generator = AdaptiveQueryGenerator(model=mock_model)-- templates = [p.template for p in generator.successful_patterns]- has_entity_pattern = any("entity" in t for t in templates)- assert has_entity_pattern-- def test_event_temporal_pattern(self):- """Should have event-temporal pattern."""- mock_model = MagicMock()- generator = AdaptiveQueryGenerator(model=mock_model)-- templates = [p.template for p in generator.successful_patterns]- has_event_pattern = any("event" in t for t in templates)- assert has_event_pattern-- def test_name_comparison_pattern(self):- """Should have name-comparison pattern."""- mock_model = MagicMock()- generator = AdaptiveQueryGenerator(model=mock_model)-- templates = [p.template for p in generator.successful_patterns]- has_and_pattern = any("AND" in t for t in templates)- assert has_and_pattern---class TestGenerateQuery:- """Tests for generate_query method."""-- def test_tries_pattern_first(self):- """Should try pattern-based generation first."""- mock_model = MagicMock()- mock_response = MagicMock()- mock_response.content = "fallback query"- mock_model.invoke = MagicMock(return_value=mock_response)-- generator = AdaptiveQueryGenerator(model=mock_model)-- constraints = [- Constraint(- id="c1",- type=ConstraintType.NAME_PATTERN,- description="Pattern",- value="mountain",- ),- Constraint(- id="c2",- type=ConstraintType.PROPERTY,- description="Property",- value="height",- ),- Constraint(- id="c3",- type=ConstraintType.LOCATION,- description="Location",- value="Colorado",- ),- ]-- query = generator.generate_query(constraints)-- # Should generate from pattern, not invoke LLM- assert isinstance(query, str)- assert len(query) > 0-- def test_falls_back_to_expansion(self):- """Should try semantic expansion when pattern fails."""- mock_model = MagicMock()- mock_response = MagicMock()- mock_response.content = "synonym1\nsynonym2\nsynonym3"- mock_model.invoke = MagicMock(return_value=mock_response)-- generator = AdaptiveQueryGenerator(model=mock_model)-- # Use constraint types that don't match default patterns- constraints = [- Constraint(- id="c1",- type=ConstraintType.EXISTENCE,- description="Exists",- value="feature",- ),- ]-- query = generator.generate_query(constraints)-- assert isinstance(query, str)-- def test_falls_back_to_llm(self):- """Should fall back to LLM generation."""- mock_model = MagicMock()- mock_response = MagicMock()- mock_response.content = "LLM generated query"- mock_model.invoke = MagicMock(return_value=mock_response)-- generator = AdaptiveQueryGenerator(model=mock_model)- generator.failed_queries.add(- '"feature" places locations'- ) # Block expansion result-- constraints = [- Constraint(- id="c1",- type=ConstraintType.EXISTENCE,- description="Exists",- value="feature",- ),- ]-- _query = generator.generate_query(constraints)-- # Should invoke LLM- mock_model.invoke.assert_called()-- def test_skips_failed_queries(self):- """Should skip queries in failed_queries set."""- mock_model = MagicMock()- mock_response = MagicMock()- mock_response.content = "new query"- mock_model.invoke = MagicMock(return_value=mock_response)-- generator = AdaptiveQueryGenerator(model=mock_model)-- # Add pattern result to failed queries- constraints = [- Constraint(- id="c1",- type=ConstraintType.NAME_PATTERN,- description="Pattern",- value="mountain",- ),- Constraint(- id="c2",- type=ConstraintType.PROPERTY,- description="Property",- value="formed ice age",- ),- Constraint(- id="c3",- type=ConstraintType.LOCATION,- description="Location",- value="Colorado",- ),- ]-- # First get what the pattern would generate- first_query = generator._generate_from_patterns(constraints)- if first_query:- generator.failed_queries.add(first_query)-- # Now generate should try next option- query = generator.generate_query(constraints)-- assert query != first_query or query is None---class TestGenerateFromPatterns:- """Tests for _generate_from_patterns method."""-- def test_returns_none_for_no_match(self):- """Should return None when no patterns match."""- mock_model = MagicMock()- generator = AdaptiveQueryGenerator(model=mock_model)-- # Clear patterns- generator.successful_patterns = []-- constraints = [- Constraint(- id="c1",- type=ConstraintType.PROPERTY,- description="Test",- value="value",- ),- ]-- result = generator._generate_from_patterns(constraints)-- assert result is None-- def test_selects_highest_success_rate(self):- """Should select pattern with highest success rate."""- mock_model = MagicMock()- generator = AdaptiveQueryGenerator(model=mock_model)-- # Add custom patterns with same constraint types but different rates- generator.successful_patterns = [- QueryPattern(- template='low: "{entity}"',- constraint_types=[ConstraintType.NAME_PATTERN],- success_rate=0.5,- example_queries=[],- discovered_entities=set(),- ),- QueryPattern(- template='high: "{entity}"',- constraint_types=[ConstraintType.NAME_PATTERN],- success_rate=0.9,- example_queries=[],- discovered_entities=set(),- ),- ]-- constraints = [- Constraint(- id="c1",- type=ConstraintType.NAME_PATTERN,- description="Test",- value="test",- ),- ]-- result = generator._generate_from_patterns(constraints)-- assert result is not None- assert "high:" in result-- def test_fills_template_vars(self):- """Should fill template variables."""- mock_model = MagicMock()- generator = AdaptiveQueryGenerator(model=mock_model)-- generator.successful_patterns = [- QueryPattern(- template='"{entity}" {property}',- constraint_types=[- ConstraintType.NAME_PATTERN,- ConstraintType.PROPERTY,- ],- success_rate=0.8,- example_queries=[],- discovered_entities=set(),- ),- ]-- constraints = [- Constraint(- id="c1",- type=ConstraintType.NAME_PATTERN,- description="Pattern",- value="mountain",- ),- Constraint(- id="c2",- type=ConstraintType.PROPERTY,- description="Property",- value="height",- ),- ]-- result = generator._generate_from_patterns(constraints)-- assert result == '"mountain" height'-- def test_handles_missing_vars(self):- """Should handle missing template variables gracefully."""- mock_model = MagicMock()- generator = AdaptiveQueryGenerator(model=mock_model)-- generator.successful_patterns = [- QueryPattern(- template="{entity} {missing_var}",- constraint_types=[ConstraintType.NAME_PATTERN],- success_rate=0.8,- example_queries=[],- discovered_entities=set(),- ),- ]-- constraints = [- Constraint(- id="c1",- type=ConstraintType.NAME_PATTERN,- description="Test",- value="test",- ),- ]-- result = generator._generate_from_patterns(constraints)-- # Should return None on KeyError- assert result is None-- def test_maps_constraint_types_to_vars(self):- """Should map constraint types to template variables."""- mock_model = MagicMock()- generator = AdaptiveQueryGenerator(model=mock_model)-- # Test each constraint type mapping- generator.successful_patterns = [- QueryPattern(- template='"{name_pattern}" {property} {location}',- constraint_types=[- ConstraintType.NAME_PATTERN,- ConstraintType.PROPERTY,- ConstraintType.LOCATION,- ],- success_rate=0.8,- example_queries=[],- discovered_entities=set(),- ),- ]-- constraints = [- Constraint(- id="c1",- type=ConstraintType.NAME_PATTERN,- description="Pattern",- value="mountain",- ),- Constraint(- id="c2",- type=ConstraintType.PROPERTY,- description="Property",- value="tall",- ),- Constraint(- id="c3",- type=ConstraintType.LOCATION,- description="Location",- value="Colorado",- ),- ]-- result = generator._generate_from_patterns(constraints)-- assert result == '"mountain" tall Colorado'---class TestGenerateWithExpansion:- """Tests for _generate_with_expansion method."""-- def test_creates_or_clause(self):- """Should create OR clause with expansions."""- mock_model = MagicMock()- mock_response = MagicMock()- mock_response.content = "peak\nsummit\nhill"- mock_model.invoke = MagicMock(return_value=mock_response)-- generator = AdaptiveQueryGenerator(model=mock_model)-- constraints = [- Constraint(- id="c1",- type=ConstraintType.NAME_PATTERN,- description="Pattern",- value="mountain",- ),- ]-- result = generator._generate_with_expansion(constraints)-- assert "OR" in result- assert "mountain" in result-- def test_uses_quotes_without_expansion(self):- """Should use quotes when no expansion available."""- mock_model = MagicMock()- mock_response = MagicMock()- mock_response.content = "" # No expansions- mock_model.invoke = MagicMock(return_value=mock_response)-- generator = AdaptiveQueryGenerator(model=mock_model)-- constraints = [- Constraint(- id="c1",- type=ConstraintType.NAME_PATTERN,- description="Pattern",- value="specific_term",- ),- ]-- result = generator._generate_with_expansion(constraints)-- # Should still produce a query- assert isinstance(result, str)-- def test_joins_terms_with_and(self):- """Should join terms with AND."""- mock_model = MagicMock()- mock_response = MagicMock()- mock_response.content = ""- mock_model.invoke = MagicMock(return_value=mock_response)-- generator = AdaptiveQueryGenerator(model=mock_model)-- constraints = [- Constraint(- id="c1",- type=ConstraintType.NAME_PATTERN,- description="Pattern",- value="term1",- ),- Constraint(- id="c2",- type=ConstraintType.PROPERTY,- description="Property",- value="term2",- ),- ]-- result = generator._generate_with_expansion(constraints)-- assert "AND" in result-- def test_caches_semantic_expansions(self):- """Should cache semantic expansions."""- mock_model = MagicMock()- mock_response = MagicMock()- mock_response.content = "synonym\nrelated"- mock_model.invoke = MagicMock(return_value=mock_response)-- generator = AdaptiveQueryGenerator(model=mock_model)-- constraints = [- Constraint(- id="c1",- type=ConstraintType.NAME_PATTERN,- description="Pattern",- value="test",- ),- ]-- # First call- generator._generate_with_expansion(constraints)-- # Should be cached- assert "test" in generator.semantic_expansions-- # Second call should use cache- call_count_before = mock_model.invoke.call_count- generator._generate_with_expansion(constraints)- call_count_after = mock_model.invoke.call_count-- # Should not call LLM again for same term- assert call_count_after == call_count_before---class TestGetSemanticExpansions:- """Tests for _get_semantic_expansions method."""-- def test_returns_quoted_expansions(self):- """Should return quoted expansions."""- mock_model = MagicMock()- mock_response = MagicMock()- mock_response.content = "synonym\nrelated\nalternative"- mock_model.invoke = MagicMock(return_value=mock_response)-- generator = AdaptiveQueryGenerator(model=mock_model)-- expansions = generator._get_semantic_expansions(- "test", ConstraintType.NAME_PATTERN- )-- assert all(e.startswith('"') and e.endswith('"') for e in expansions)-- def test_limits_to_three_expansions(self):- """Should limit to 3 expansions."""- mock_model = MagicMock()- mock_response = MagicMock()- mock_response.content = "a\nb\nc\nd\ne" # 5 expansions- mock_model.invoke = MagicMock(return_value=mock_response)-- generator = AdaptiveQueryGenerator(model=mock_model)-- expansions = generator._get_semantic_expansions(- "test", ConstraintType.NAME_PATTERN- )-- assert len(expansions) <= 3---class TestGenerateWithLLM:- """Tests for _generate_with_llm method."""-- def test_formats_constraints(self):- """Should format constraints for prompt."""- mock_model = MagicMock()- mock_response = MagicMock()- mock_response.content = "generated query"- mock_model.invoke = MagicMock(return_value=mock_response)-- generator = AdaptiveQueryGenerator(model=mock_model)-- constraints = [- Constraint(- id="c1",- type=ConstraintType.NAME_PATTERN,- description="Pattern description",- value="test",- ),- ]-- generator._generate_with_llm(constraints)-- # Check prompt contains constraint info- call_args = mock_model.invoke.call_args[0][0]- assert "name_pattern" in call_args- assert "test" in call_args-- def test_includes_failed_queries_context(self):- """Should include failed queries in context."""- mock_model = MagicMock()- mock_response = MagicMock()- mock_response.content = "generated query"- mock_model.invoke = MagicMock(return_value=mock_response)-- generator = AdaptiveQueryGenerator(model=mock_model)-- constraints = [- Constraint(- id="c1",- type=ConstraintType.NAME_PATTERN,- description="Test",- value="value",- ),- ]- context = {"failed_queries": ["query1", "query2"]}-- generator._generate_with_llm(constraints, context)-- call_args = mock_model.invoke.call_args[0][0]- assert "query1" in call_args-- def test_includes_successful_queries_context(self):- """Should include successful queries in context."""- mock_model = MagicMock()- mock_response = MagicMock()- mock_response.content = "generated query"- mock_model.invoke = MagicMock(return_value=mock_response)-- generator = AdaptiveQueryGenerator(model=mock_model)-- constraints = [- Constraint(- id="c1",- type=ConstraintType.NAME_PATTERN,- description="Test",- value="value",- ),- ]- context = {"successful_queries": ["good1", "good2"]}-- generator._generate_with_llm(constraints, context)-- call_args = mock_model.invoke.call_args[0][0]- assert "good1" in call_args---class TestUpdatePatterns:- """Tests for update_patterns method."""-- def test_adds_to_failed_on_failure(self):- """Should add to failed_queries on failure."""- mock_model = MagicMock()- generator = AdaptiveQueryGenerator(model=mock_model)-- generator.update_patterns(- query="failed query",- constraints=[],- success=False,- entities_found=[],- )-- assert "failed query" in generator.failed_queries-- def test_updates_existing_pattern_success_rate(self):- """Should update existing pattern success rate when query matches template."""- mock_model = MagicMock()- generator = AdaptiveQueryGenerator(model=mock_model)-- # Add a pattern with a template that can be extracted from the query- generator.successful_patterns = [- QueryPattern(- template="{name_pattern} search",- constraint_types=[ConstraintType.NAME_PATTERN],- success_rate=0.6,- example_queries=["old query"],- discovered_entities=set(),- ),- ]-- constraints = [- Constraint(- id="c1",- type=ConstraintType.NAME_PATTERN,- description="Test",- value="test",- ),- ]-- # Query with the constraint value in it - should extract pattern- generator.update_patterns(- query="test search", # Contains "test" which matches constraint- constraints=constraints,- success=True,- entities_found=["entity1"],- )-- # Check that a new pattern was added with success_rate 1.0- # Or the existing one was updated if template matched- assert len(generator.successful_patterns) >= 1-- def test_adds_failed_query_on_failure_without_entities(self):- """Should add query to failed_queries when success=False."""- mock_model = MagicMock()- generator = AdaptiveQueryGenerator(model=mock_model)-- constraints = [- Constraint(- id="c1",- type=ConstraintType.NAME_PATTERN,- description="Test",- value="test",- ),- ]-- generator.update_patterns(- query="test query",- constraints=constraints,- success=False,- entities_found=[],- )-- assert "test query" in generator.failed_queries-- def test_does_not_add_pattern_without_entities(self):- """Should not add pattern when no entities found even if success=True."""- mock_model = MagicMock()- generator = AdaptiveQueryGenerator(model=mock_model)-- initial_count = len(generator.successful_patterns)-- constraints = [- Constraint(- id="c1",- type=ConstraintType.NAME_PATTERN,- description="Test",- value="test",- ),- ]-- generator.update_patterns(- query="test query",- constraints=constraints,- success=True,- entities_found=[], # Empty!- )-- # Should not have added new patterns- assert len(generator.successful_patterns) == initial_count-- def test_extracts_pattern_from_successful_query(self):- """Should extract and add pattern from successful query with entities."""- mock_model = MagicMock()- generator = AdaptiveQueryGenerator(model=mock_model)-- initial_count = len(generator.successful_patterns)-- constraints = [- Constraint(- id="c1",- type=ConstraintType.NAME_PATTERN,- description="Test",- value="mountain",- ),- ]-- # Query contains the constraint value, so pattern can be extracted- generator.update_patterns(- query='"mountain" tall peaks',- constraints=constraints,- success=True,- entities_found=["Mt. Everest"],- )-- # Should have added a new pattern or updated existing- new_count = len(generator.successful_patterns)- assert new_count >= initial_count # Pattern added or same-- def test_updates_constraint_combinations_correctly(self):- """Should record constraint combinations on success with entities."""- mock_model = MagicMock()- generator = AdaptiveQueryGenerator(model=mock_model)-- constraints = [- Constraint(- id="c1",- type=ConstraintType.NAME_PATTERN,- description="Test",- value="mountain",- ),- ]-- generator.update_patterns(- query='"mountain" search', # Contains constraint value- constraints=constraints,- success=True,- entities_found=["entity"],- )-- # Check that some combination was recorded- # The exact key depends on sorting behavior of ConstraintType- assert (- len(generator.constraint_combinations) > 0- or len(generator.failed_queries) == 0- )---class TestExtractPattern:- """Tests for _extract_pattern method."""-- def test_replaces_values_with_placeholders(self):- """Should replace values with placeholders."""- mock_model = MagicMock()- generator = AdaptiveQueryGenerator(model=mock_model)-- constraints = [- Constraint(- id="c1",- type=ConstraintType.NAME_PATTERN,- description="Test",- value="mountain",- ),- ]-- pattern = generator._extract_pattern(- '"mountain" in Colorado', constraints- )-- assert pattern is not None- assert "{name_pattern}" in pattern.template-- def test_returns_none_without_placeholders(self):- """Should return None if no placeholders created."""- mock_model = MagicMock()- generator = AdaptiveQueryGenerator(model=mock_model)-- constraints = [- Constraint(- id="c1",- type=ConstraintType.NAME_PATTERN,- description="Test",- value="notinquery",- ),- ]-- pattern = generator._extract_pattern("simple query", constraints)-- assert pattern is None-- def test_creates_pattern_with_placeholders(self):- """Should create pattern when placeholders exist."""- mock_model = MagicMock()- generator = AdaptiveQueryGenerator(model=mock_model)-- constraints = [- Constraint(- id="c1",- type=ConstraintType.NAME_PATTERN,- description="Test",- value="mountain",- ),- Constraint(- id="c2",- type=ConstraintType.LOCATION,- description="Location",- value="Colorado",- ),- ]-- pattern = generator._extract_pattern(- '"mountain" in Colorado', constraints- )-- assert pattern is not None- assert pattern.success_rate == 1.0- assert len(pattern.constraint_types) == 2---class TestFormatConstraints:- """Tests for _format_constraints method."""-- def test_formats_single_constraint(self):- """Should format single constraint."""- mock_model = MagicMock()- generator = AdaptiveQueryGenerator(model=mock_model)-- constraints = [- Constraint(- id="c1",- type=ConstraintType.NAME_PATTERN,- description="A pattern",- value="test",- ),- ]-- formatted = generator._format_constraints(constraints)-- assert "name_pattern" in formatted- assert "A pattern" in formatted- assert "test" in formatted-- def test_formats_multiple_constraints(self):- """Should format multiple constraints."""- mock_model = MagicMock()- generator = AdaptiveQueryGenerator(model=mock_model)-- constraints = [- Constraint(- id="c1",- type=ConstraintType.NAME_PATTERN,- description="D1",- value="v1",- ),- Constraint(- id="c2",- type=ConstraintType.LOCATION,- description="D2",- value="v2",- ),- ]-- formatted = generator._format_constraints(constraints)-- assert "name_pattern" in formatted- assert "location" in formatted---class TestGenerateFallbackQueries:- """Tests for generate_fallback_queries method."""-- def test_generates_simplified_query(self):- """Should generate simplified query with fewer constraints."""- mock_model = MagicMock()- mock_response = MagicMock()- mock_response.content = "alt query 1\nalt query 2"- mock_model.invoke = MagicMock(return_value=mock_response)-- generator = AdaptiveQueryGenerator(model=mock_model)-- constraints = [- Constraint(- id="c1",- type=ConstraintType.NAME_PATTERN,- description="Pattern",- value="a",- weight=1.0,- ),- Constraint(- id="c2",- type=ConstraintType.PROPERTY,- description="Property",- value="b",- weight=0.8,- ),- Constraint(- id="c3",- type=ConstraintType.LOCATION,- description="Location",- value="c",- weight=0.5,- ),- ]-- fallbacks = generator.generate_fallback_queries(- "original query", constraints- )-- assert isinstance(fallbacks, list)- assert len(fallbacks) > 0-- def test_generates_broadened_query(self):- """Should generate broadened query with OR."""- mock_model = MagicMock()- mock_response = MagicMock()- mock_response.content = ""- mock_model.invoke = MagicMock(return_value=mock_response)-- generator = AdaptiveQueryGenerator(model=mock_model)-- constraints = [- Constraint(- id="c1",- type=ConstraintType.NAME_PATTERN,- description="Pattern",- value="a",- ),- Constraint(- id="c2",- type=ConstraintType.PROPERTY,- description="Property",- value="b",- ),- ]-- fallbacks = generator.generate_fallback_queries("original", constraints)-- # Should have OR query- has_or = any("OR" in q for q in fallbacks)- assert has_or-- def test_generates_single_constraint_queries(self):- """Should generate queries for single constraints."""- mock_model = MagicMock()- mock_response = MagicMock()- mock_response.content = ""- mock_model.invoke = MagicMock(return_value=mock_response)-- generator = AdaptiveQueryGenerator(model=mock_model)-- constraints = [- Constraint(- id="c1",- type=ConstraintType.NAME_PATTERN,- description="Pattern",- value="test1",- ),- Constraint(- id="c2",- type=ConstraintType.LOCATION,- description="Location",- value="test2",- ),- ]-- fallbacks = generator.generate_fallback_queries("original", constraints)-- # Should have single-constraint queries- assert len(fallbacks) > 0-- def test_removes_duplicates(self):- """Should remove duplicate fallback queries."""- mock_model = MagicMock()- mock_response = MagicMock()- mock_response.content = (- '"test1" names list\n"test1" names list' # Duplicates- )- mock_model.invoke = MagicMock(return_value=mock_response)-- generator = AdaptiveQueryGenerator(model=mock_model)-- constraints = [- Constraint(- id="c1",- type=ConstraintType.NAME_PATTERN,- description="Pattern",- value="test1",- ),- ]-- fallbacks = generator.generate_fallback_queries("original", constraints)-- # Should not have duplicates- assert len(fallbacks) == len(set(fallbacks))-- def test_removes_failed_queries(self):- """Should remove queries in failed set."""- mock_model = MagicMock()- mock_response = MagicMock()- mock_response.content = ""- mock_model.invoke = MagicMock(return_value=mock_response)-- generator = AdaptiveQueryGenerator(model=mock_model)- generator.failed_queries.add('"test1" names list')-- constraints = [- Constraint(- id="c1",- type=ConstraintType.NAME_PATTERN,- description="Pattern",- value="test1",- ),- ]-- fallbacks = generator.generate_fallback_queries("original", constraints)-- # Should not contain failed query- assert '"test1" names list' not in fallbacks-- def test_limits_to_five(self):- """Should limit to 5 fallback queries."""- mock_model = MagicMock()- mock_response = MagicMock()- mock_response.content = "q1\nq2\nq3\nq4\nq5\nq6\nq7"- mock_model.invoke = MagicMock(return_value=mock_response)-- generator = AdaptiveQueryGenerator(model=mock_model)-- constraints = [- Constraint(- id="c1",- type=ConstraintType.NAME_PATTERN,- description="Pattern",- value="test",- weight=1.0,- ),- Constraint(- id="c2",- type=ConstraintType.PROPERTY,- description="Property",- value="prop",- weight=0.8,- ),- Constraint(- id="c3",- type=ConstraintType.LOCATION,- description="Location",- value="loc",- weight=0.6,- ),- ]-- fallbacks = generator.generate_fallback_queries("original", constraints)-- assert len(fallbacks) <= 5---class TestGenerateSingleConstraintQuery:- """Tests for _generate_single_constraint_query method."""-- def test_name_pattern_template(self):- """Should use name pattern template."""- mock_model = MagicMock()- generator = AdaptiveQueryGenerator(model=mock_model)-- constraint = Constraint(- id="c1",- type=ConstraintType.NAME_PATTERN,- description="Pattern",- value="mountain",- )-- query = generator._generate_single_constraint_query(constraint)-- assert '"mountain"' in query- assert "names list" in query-- def test_location_template(self):- """Should use location template."""- mock_model = MagicMock()- generator = AdaptiveQueryGenerator(model=mock_model)-- constraint = Constraint(- id="c1",- type=ConstraintType.LOCATION,- description="Location",- value="Colorado",- )-- query = generator._generate_single_constraint_query(constraint)-- assert '"Colorado"' in query- assert "places locations" in query-- def test_event_template(self):- """Should use event template."""- mock_model = MagicMock()- generator = AdaptiveQueryGenerator(model=mock_model)-- constraint = Constraint(- id="c1",- type=ConstraintType.EVENT,- description="Event",- value="earthquake",- )-- query = generator._generate_single_constraint_query(constraint)-- assert '"earthquake"' in query- assert "incidents accidents" in query-- def test_temporal_template(self):- """Should use temporal template."""- mock_model = MagicMock()- generator = AdaptiveQueryGenerator(model=mock_model)-- constraint = Constraint(- id="c1",- type=ConstraintType.TEMPORAL,- description="Temporal",- value="2020",- )-- query = generator._generate_single_constraint_query(constraint)-- assert "2020" in query- assert "events in" in query-- def test_default_template(self):- """Should use default template for unknown types."""- mock_model = MagicMock()- generator = AdaptiveQueryGenerator(model=mock_model)-- constraint = Constraint(- id="c1",- type=ConstraintType.EXISTENCE,- description="Existence",- value="feature",- )-- query = generator._generate_single_constraint_query(constraint)-- assert "feature" in query---class TestOptimizeConstraintCombinations:- """Tests for optimize_constraint_combinations method."""-- def test_sorts_by_success(self):- """Should sort combinations by success."""- mock_model = MagicMock()- generator = AdaptiveQueryGenerator(model=mock_model)-- # Add some combinations with different success rates- generator.constraint_combinations[- (ConstraintType.NAME_PATTERN, ConstraintType.PROPERTY)- ] = 5- generator.constraint_combinations[- (ConstraintType.LOCATION, ConstraintType.EVENT)- ] = 10- generator.constraint_combinations[(ConstraintType.TEMPORAL,)] = 3-- constraints = [- Constraint(- id="c1",- type=ConstraintType.NAME_PATTERN,- description="Pattern",- value="v1",- ),- Constraint(- id="c2",- type=ConstraintType.PROPERTY,- description="Property",- value="v2",- ),- Constraint(- id="c3",- type=ConstraintType.LOCATION,- description="Location",- value="v3",- ),- Constraint(- id="c4",- type=ConstraintType.EVENT,- description="Event",- value="v4",- ),- ]-- combinations = generator.optimize_constraint_combinations(constraints)-- # Should return list of constraint lists- assert isinstance(combinations, list)- assert len(combinations) > 0-- def test_adds_individual_constraints(self):- """Should add individual constraints."""- mock_model = MagicMock()- generator = AdaptiveQueryGenerator(model=mock_model)-- constraints = [- Constraint(- id="c1",- type=ConstraintType.NAME_PATTERN,- description="Pattern",- value="v1",- ),- Constraint(- id="c2",- type=ConstraintType.PROPERTY,- description="Property",- value="v2",- ),- ]-- combinations = generator.optimize_constraint_combinations(constraints)-- # Should have individual constraints- singles = [c for c in combinations if len(c) == 1]- assert len(singles) >= 2-- def test_adds_pairs(self):- """Should add constraint pairs."""- mock_model = MagicMock()- generator = AdaptiveQueryGenerator(model=mock_model)-- constraints = [- Constraint(- id="c1",- type=ConstraintType.NAME_PATTERN,- description="Pattern",- value="a",- ),- Constraint(- id="c2",- type=ConstraintType.PROPERTY,- description="Property",- value="b",- ),- Constraint(- id="c3",- type=ConstraintType.LOCATION,- description="Location",- value="c",- ),- ]-- combinations = generator.optimize_constraint_combinations(constraints)-- # Should have pairs- pairs = [c for c in combinations if len(c) == 2]- assert len(pairs) >= 1-- def test_limits_to_ten(self):- """Should limit to 10 combinations."""- mock_model = MagicMock()- generator = AdaptiveQueryGenerator(model=mock_model)-- constraints = [- Constraint(- id=f"c{i}",- type=ConstraintType.PROPERTY,- description=f"Prop {i}",- value=f"v{i}",- )- for i in range(10)- ]-- combinations = generator.optimize_constraint_combinations(constraints)-- assert len(combinations) <= 10---class TestEdgeCases:- """Tests for edge cases."""-- def test_empty_constraints(self):- """Should handle empty constraints."""- mock_model = MagicMock()- mock_response = MagicMock()- mock_response.content = "query"- mock_model.invoke = MagicMock(return_value=mock_response)-- generator = AdaptiveQueryGenerator(model=mock_model)-- query = generator.generate_query([])-- # Should fall back to LLM- assert isinstance(query, str)-- def test_special_characters_in_value(self):- """Should handle special characters in value."""- mock_model = MagicMock()- generator = AdaptiveQueryGenerator(model=mock_model)-- constraint = Constraint(- id="c1",- type=ConstraintType.NAME_PATTERN,- description="Pattern",- value="test (with) special [chars]",- )-- query = generator._generate_single_constraint_query(constraint)-- assert "test" in query- assert "(" in query-- def test_unicode_in_value(self):- """Should handle unicode in value."""- mock_model = MagicMock()- generator = AdaptiveQueryGenerator(model=mock_model)-- constraint = Constraint(- id="c1",- type=ConstraintType.NAME_PATTERN,- description="Pattern",- value="\u5bcc\u58eb\u5c71", # Mt. Fuji in Japanese- )-- query = generator._generate_single_constraint_query(constraint)-- assert "\u5bcc\u58eb\u5c71" in query-- def test_very_long_value(self):- """Should handle very long value."""- mock_model = MagicMock()- generator = AdaptiveQueryGenerator(model=mock_model)-- constraint = Constraint(- id="c1",- type=ConstraintType.NAME_PATTERN,- description="Pattern",- value="x" * 1000,- )-- query = generator._generate_single_constraint_query(constraint)-- assert len(query) > 0diff --git a/tests/advanced_search_system/search_optimization/test_cross_constraint_branches_coverage.py b/tests/advanced_search_system/search_optimization/test_cross_constraint_branches_coverage.pydeleted file mode 100644index 45748a80c8..0000000000--- a/tests/advanced_search_system/search_optimization/test_cross_constraint_branches_coverage.py+++ /dev/null@@ -1,771 +0,0 @@-"""-Branch-coverage tests for-advanced_search_system/search_optimization/cross_constraint_manager.py.--Targets the remaining 41 missing lines, focusing on branches not yet-exercised by test_cross_constraint_coverage.py,-test_cross_constraint_edge_cases.py, or test_cross_constraint_pure_logic.py:--1. create_constraint_clusters – type_based grouping (only groups with >1)-2. _create_relationship_clusters – BFS connected components-3. _create_semantic_clusters – LLM response parsing (CLUSTER_ blocks)-4. generate_cross_constraint_queries – all four sub-generators called-5. validate_candidate_across_constraints – cluster-based + pairwise-6. _deduplicate_clusters – duplicate removal-7. _calculate_cluster_coherence – no pairs → 0.5 default-8. optimize_search_order – sorting by coherence * size-"""--import pytest-from unittest.mock import MagicMock, patch--from local_deep_research.advanced_search_system.constraints.base_constraint import (- Constraint,- ConstraintType,-)-from local_deep_research.advanced_search_system.candidates.base_candidate import (- Candidate,-)-from local_deep_research.advanced_search_system.search_optimization.cross_constraint_manager import (- ConstraintCluster,- ConstraintRelationship,- CrossConstraintManager,-)--MODULE = (- "local_deep_research.advanced_search_system"- ".search_optimization.cross_constraint_manager"-)---# ----------------------------------------------------------------------------# Helpers-# ------------------------------------------------------------------------------def _c(cid, ctype=ConstraintType.PROPERTY, weight=1.0, desc=None):- """Build a Constraint quickly."""- return Constraint(- id=cid,- type=ctype,- description=desc or f"desc for {cid}",- value=cid,- weight=weight,- )---def _manager(model=None):- """Return a CrossConstraintManager with a fresh MagicMock model."""- if model is None:- model = MagicMock()- return CrossConstraintManager(model=model), model---def _cluster(constraints, ctype="type_based", coherence=0.5, queries=None):- cl = ConstraintCluster(- constraints=constraints,- cluster_type=ctype,- coherence_score=coherence,- )- if queries is not None:- cl.search_queries = queries- return cl---# ----------------------------------------------------------------------------# 1. test_create_constraint_clusters_type_based-# ------------------------------------------------------------------------------class TestCreateConstraintClustersTypeBased:- """create_constraint_clusters groups same-type constraints (>1) together."""-- def test_two_temporal_form_one_type_cluster(self):- """Two TEMPORAL constraints produce exactly one type_based cluster."""- mgr, model = _manager()- # Weak LLM responses so no relationship clusters are formed- model.invoke.return_value = MagicMock(- content="Type: none\nStrength: 0.0\nEvidence: n/a\n"- "CLUSTER_1:\nConstraints: []\nTheme: t\nCoherence: 0.5"- )-- c1 = _c("c1", ConstraintType.TEMPORAL)- c2 = _c("c2", ConstraintType.TEMPORAL)- c3 = _c("c3", ConstraintType.LOCATION) # lone location – no cluster-- clusters = mgr.create_constraint_clusters([c1, c2, c3])-- type_based = [cl for cl in clusters if cl.cluster_type == "type_based"]- assert len(type_based) == 1- ids = {con.id for con in type_based[0].constraints}- assert ids == {"c1", "c2"}-- def test_singleton_type_not_clustered(self):- """A type represented by only one constraint must not produce a cluster."""- mgr, model = _manager()- model.invoke.return_value = MagicMock(- content="Type: none\nStrength: 0.0\nEvidence: n/a"- )-- c1 = _c("c1", ConstraintType.TEMPORAL)- c2 = _c("c2", ConstraintType.LOCATION) # unique type-- clusters = mgr.create_constraint_clusters([c1, c2])-- # No type_based clusters because both types have only one member- type_based = [cl for cl in clusters if cl.cluster_type == "type_based"]- assert len(type_based) == 0-- def test_multiple_types_each_with_two_members(self):- """Two distinct types each with two constraints produce two type-based clusters."""- mgr, model = _manager()- model.invoke.return_value = MagicMock(- content="Type: none\nStrength: 0.0\nEvidence: n/a"- )-- constraints = [- _c("t1", ConstraintType.TEMPORAL),- _c("t2", ConstraintType.TEMPORAL),- _c("l1", ConstraintType.LOCATION),- _c("l2", ConstraintType.LOCATION),- ]-- clusters = mgr.create_constraint_clusters(constraints)-- type_based = [cl for cl in clusters if cl.cluster_type == "type_based"]- assert len(type_based) == 2-- def test_type_based_cluster_coherence_score(self):- """Type-based clusters have coherence_score == 0.7 (hard-coded in source)."""- mgr, model = _manager()- model.invoke.return_value = MagicMock(- content="Type: none\nStrength: 0.0\nEvidence: n/a"- )-- c1 = _c("c1", ConstraintType.PROPERTY)- c2 = _c("c2", ConstraintType.PROPERTY)-- clusters = mgr.create_constraint_clusters([c1, c2])-- type_based = [cl for cl in clusters if cl.cluster_type == "type_based"]- assert len(type_based) == 1- assert type_based[0].coherence_score == pytest.approx(0.7)-- def test_clusters_stored_on_manager(self):- """create_constraint_clusters stores result in self.clusters."""- mgr, model = _manager()- model.invoke.return_value = MagicMock(- content="Type: none\nStrength: 0.0\nEvidence: n/a"- )-- c1 = _c("c1", ConstraintType.TEMPORAL)- c2 = _c("c2", ConstraintType.TEMPORAL)-- result = mgr.create_constraint_clusters([c1, c2])- assert mgr.clusters is result---# ----------------------------------------------------------------------------# 2. test_create_relationship_clusters_bfs-# ------------------------------------------------------------------------------class TestCreateRelationshipClustersBfs:- """_create_relationship_clusters uses BFS to find connected components."""-- def test_linear_chain_forms_one_cluster(self):- """c1-c2 and c2-c3 connected via BFS → single cluster {c1, c2, c3}."""- mgr, _ = _manager()- c1, c2, c3 = _c("c1"), _c("c2"), _c("c3")-- rels = [- ConstraintRelationship("c1", "c2", "complementary", 0.8),- ConstraintRelationship("c2", "c3", "complementary", 0.7),- ]-- result = mgr._create_relationship_clusters([c1, c2, c3], rels)-- assert len(result) == 1- ids = {con.id for con in result[0].constraints}- assert ids == {"c1", "c2", "c3"}-- def test_two_separate_components(self):- """c1-c2 and c3-c4 are disconnected → two clusters."""- mgr, _ = _manager()- c1, c2, c3, c4 = _c("c1"), _c("c2"), _c("c3"), _c("c4")-- rels = [- ConstraintRelationship("c1", "c2", "complementary", 0.9),- ConstraintRelationship("c3", "c4", "dependent", 0.8),- ]-- result = mgr._create_relationship_clusters([c1, c2, c3, c4], rels)-- assert len(result) == 2- cluster_sets = [- frozenset(con.id for con in cl.constraints) for cl in result- ]- assert frozenset({"c1", "c2"}) in cluster_sets- assert frozenset({"c3", "c4"}) in cluster_sets-- def test_isolated_node_not_clustered(self):- """A node with no relationships is not added to any cluster."""- mgr, _ = _manager()- c1, c2, c3 = _c("c1"), _c("c2"), _c("c3")-- rels = [ConstraintRelationship("c1", "c2", "complementary", 0.9)]-- result = mgr._create_relationship_clusters([c1, c2, c3], rels)-- # c3 is isolated; only {c1, c2} cluster should exist- all_ids = {con.id for cl in result for con in cl.constraints}- assert "c3" not in all_ids-- def test_empty_relationships_no_clusters(self):- """No relationships → no clusters."""- mgr, _ = _manager()- constraints = [_c(f"c{i}") for i in range(4)]-- result = mgr._create_relationship_clusters(constraints, [])-- assert result == []-- def test_each_node_processed_at_most_once(self):- """BFS marks processed nodes; no duplicates in output clusters."""- mgr, _ = _manager()- c1, c2, c3 = _c("c1"), _c("c2"), _c("c3")-- rels = [- ConstraintRelationship("c1", "c2", "complementary", 0.8),- ConstraintRelationship("c1", "c3", "complementary", 0.7),- ]-- result = mgr._create_relationship_clusters([c1, c2, c3], rels)-- # All three should be in one cluster; no duplicates- assert len(result) == 1- ids = [con.id for con in result[0].constraints]- assert len(ids) == len(set(ids))-- def test_cluster_type_is_relationship_based(self):- """Clusters created here always have cluster_type 'relationship_based'."""- mgr, _ = _manager()- c1, c2 = _c("c1"), _c("c2")-- rels = [ConstraintRelationship("c1", "c2", "complementary", 0.9)]-- result = mgr._create_relationship_clusters([c1, c2], rels)-- assert result[0].cluster_type == "relationship_based"---# ----------------------------------------------------------------------------# 3. test_create_semantic_clusters_parsing-# ------------------------------------------------------------------------------class TestCreateSemanticClustersParsing:- """_create_semantic_clusters parses CLUSTER_N blocks from LLM response."""-- def _make_response(self, text):- r = MagicMock()- r.content = text- return r-- def test_single_cluster_block_parsed(self):- """A single CLUSTER_1 block with two valid IDs produces one cluster."""- mgr, model = _manager()- c1, c2 = _c("c1"), _c("c2")-- llm_text = (- "CLUSTER_1:\n"- "Constraints: [c1, c2]\n"- "Theme: temporal overlap\n"- "Coherence: 0.8\n"- )- with patch(f"{MODULE}.remove_think_tags", return_value=llm_text):- model.invoke.return_value = self._make_response(llm_text)- result = mgr._create_semantic_clusters([c1, c2])-- assert len(result) == 1- ids = {con.id for con in result[0].constraints}- assert ids == {"c1", "c2"}- assert result[0].coherence_score == pytest.approx(0.8)- assert result[0].cluster_type == "semantic"-- def test_two_cluster_blocks_parsed(self):- """Two CLUSTER_ blocks each with two IDs produce two semantic clusters."""- mgr, model = _manager()- c1, c2, c3, c4 = _c("c1"), _c("c2"), _c("c3"), _c("c4")-- llm_text = (- "CLUSTER_1:\n"- "Constraints: [c1, c2]\n"- "Theme: time\n"- "Coherence: 0.7\n"- "CLUSTER_2:\n"- "Constraints: [c3, c4]\n"- "Theme: space\n"- "Coherence: 0.6\n"- )- with patch(f"{MODULE}.remove_think_tags", return_value=llm_text):- model.invoke.return_value = self._make_response(llm_text)- result = mgr._create_semantic_clusters([c1, c2, c3, c4])-- assert len(result) == 2-- def test_invalid_coherence_defaults_to_half(self):- """Non-numeric Coherence value defaults to 0.5."""- mgr, model = _manager()- c1, c2 = _c("c1"), _c("c2")-- llm_text = (- "CLUSTER_1:\nConstraints: [c1, c2]\nTheme: mixed\nCoherence: high\n"- )- with patch(f"{MODULE}.remove_think_tags", return_value=llm_text):- model.invoke.return_value = self._make_response(llm_text)- result = mgr._create_semantic_clusters([c1, c2])-- if result:- assert result[0].coherence_score == pytest.approx(0.5)-- def test_singleton_cluster_not_added(self):- """A block referencing only one valid constraint ID is skipped."""- mgr, model = _manager()- c1, c2 = _c("c1"), _c("c2")-- # Only c1 matches a real constraint- llm_text = (- "CLUSTER_1:\n"- "Constraints: [c1, c_nonexistent]\n"- "Theme: lonely\n"- "Coherence: 0.9\n"- )- with patch(f"{MODULE}.remove_think_tags", return_value=llm_text):- model.invoke.return_value = self._make_response(llm_text)- result = mgr._create_semantic_clusters([c1, c2])-- # c_nonexistent is not in the constraint list so only c1 matches → skipped- assert all(len(cl.constraints) > 1 for cl in result)-- def test_last_cluster_block_also_parsed(self):- """The final CLUSTER_ block (after loop end) must not be lost."""- mgr, model = _manager()- c1, c2, c3, c4 = _c("c1"), _c("c2"), _c("c3"), _c("c4")-- llm_text = (- "CLUSTER_1:\n"- "Constraints: [c1, c2]\n"- "Theme: A\n"- "Coherence: 0.7\n"- "CLUSTER_2:\n"- "Constraints: [c3, c4]\n"- "Theme: B\n"- "Coherence: 0.6\n"- )- with patch(f"{MODULE}.remove_think_tags", return_value=llm_text):- model.invoke.return_value = self._make_response(llm_text)- result = mgr._create_semantic_clusters([c1, c2, c3, c4])-- # Both blocks parsed – second one (c3, c4) must appear- all_ids = {con.id for cl in result for con in cl.constraints}- assert "c3" in all_ids- assert "c4" in all_ids---# ----------------------------------------------------------------------------# 4. test_generate_cross_constraint_queries-# ------------------------------------------------------------------------------class TestGenerateCrossConstraintQueries:- """generate_cross_constraint_queries calls all four sub-generators."""-- def test_all_query_types_invoked(self):- """Combined, progressive, intersection, and validation queries are built."""- mgr, _ = _manager()- c1, c2, c3 = (- _c("c1", weight=0.9),- _c("c2", weight=0.7),- _c("c3", weight=0.5),- )- cluster = _cluster([c1, c2, c3])-- combined_q = "combined query"- prog_q = "progressive query"- inter_q = "intersection query"- val_q = "validation query"-- with (- patch.object(- mgr, "_generate_combined_query", return_value=combined_q- ) as mock_comb,- patch.object(- mgr, "_generate_progressive_queries", return_value=[prog_q]- ) as mock_prog,- patch.object(- mgr, "_generate_intersection_query", return_value=inter_q- ) as mock_inter,- patch.object(- mgr, "_generate_validation_queries", return_value=[val_q]- ) as mock_val,- ):- result = mgr.generate_cross_constraint_queries(cluster)-- mock_comb.assert_called_once_with([c1, c2, c3])- mock_prog.assert_called_once_with([c1, c2, c3])- mock_inter.assert_called_once_with([c1, c2, c3])- mock_val.assert_called_once_with([c1, c2, c3])-- assert combined_q in result- assert prog_q in result- assert inter_q in result- assert val_q in result-- def test_none_intersection_not_appended(self):- """If _generate_intersection_query returns None it is excluded."""- mgr, _ = _manager()- c1, c2 = _c("c1"), _c("c2")- cluster = _cluster([c1, c2])-- with (- patch.object(mgr, "_generate_combined_query", return_value="cq"),- patch.object(mgr, "_generate_progressive_queries", return_value=[]),- patch.object(- mgr, "_generate_intersection_query", return_value=None- ),- patch.object(mgr, "_generate_validation_queries", return_value=[]),- ):- result = mgr.generate_cross_constraint_queries(cluster)-- # Only the combined query; intersection (None) was not added- assert None not in result- assert "cq" in result-- def test_queries_stored_in_cluster(self):- """Results are written back to cluster.search_queries."""- mgr, _ = _manager()- c1, c2 = _c("c1"), _c("c2")- cluster = _cluster([c1, c2])-- with (- patch.object(mgr, "_generate_combined_query", return_value="q1"),- patch.object(- mgr, "_generate_progressive_queries", return_value=["q2"]- ),- patch.object(- mgr, "_generate_intersection_query", return_value=None- ),- patch.object(mgr, "_generate_validation_queries", return_value=[]),- ):- result = mgr.generate_cross_constraint_queries(cluster)-- assert cluster.search_queries == result-- def test_progressive_queries_use_sorted_weights(self):- """_generate_progressive_queries receives constraints sorted by weight desc."""- mgr, _ = _manager()- # Assign weights in ascending order; sorted call should reverse them- c_low = _c("c_low", weight=0.2)- c_mid = _c("c_mid", weight=0.5)- c_high = _c("c_high", weight=0.9)- cluster = _cluster([c_low, c_mid, c_high])-- captured = {}-- def _fake_progressive(constraints):- captured["order"] = [c.id for c in constraints]- return []-- with (- patch.object(mgr, "_generate_combined_query", return_value="cq"),- patch.object(- mgr,- "_generate_progressive_queries",- side_effect=_fake_progressive,- ),- patch.object(- mgr, "_generate_intersection_query", return_value=None- ),- patch.object(mgr, "_generate_validation_queries", return_value=[]),- ):- mgr.generate_cross_constraint_queries(cluster)-- # generate_cross_constraint_queries passes all constraints as-is to sub-generators- # (sorting happens inside _generate_progressive_queries)- assert (- "order" not in captured or captured["order"] is not None- ) # sanity---# ----------------------------------------------------------------------------# 5. test_validate_candidate_across_constraints-# ------------------------------------------------------------------------------class TestValidateCandidateAcrossConstraints:- """validate_candidate_across_constraints: cluster-based + pairwise validation."""-- def test_no_clusters_gives_empty_scores(self):- """With no clusters in manager, result is empty."""- mgr, _ = _manager()- candidate = Candidate(name="X")- result = mgr.validate_candidate_across_constraints(- candidate, [_c("c1")]- )- assert result == {}-- def test_relevant_cluster_score_propagated(self):- """Cluster whose constraints overlap with the input get scored."""- mgr, model = _manager()- c1 = _c("c1")- c2 = _c("c2")-- cluster = _cluster([c1, c2], queries=["find both"])- mgr.clusters = [cluster]-- with patch.object(- mgr, "_validate_with_cluster", return_value=0.72- ) as mock_vc:- result = mgr.validate_candidate_across_constraints(- Candidate(name="Alice"), [c1, c2]- )-- mock_vc.assert_called_once_with(Candidate(name="Alice"), cluster)- assert result.get("c1") == pytest.approx(0.72)- assert result.get("c2") == pytest.approx(0.72)-- def test_complementary_pair_calls_validate_pair(self):- """Registered complementary c1-c2 triggers _validate_pair."""- mgr, _ = _manager()- c1, c2 = _c("c1"), _c("c2")-- mgr.relationships[("c1", "c2")] = ConstraintRelationship(- "c1", "c2", "complementary", 0.9- )-- candidate = Candidate(name="Bob")- with patch.object(mgr, "_validate_pair", return_value=0.88) as mock_vp:- result = mgr.validate_candidate_across_constraints(- candidate, [c1, c2]- )-- mock_vp.assert_called_once_with(candidate, c1, c2)- assert result["c1"] == pytest.approx(0.88)- assert result["c2"] == pytest.approx(0.88)-- def test_non_complementary_pair_does_not_call_validate_pair(self):- """A 'dependent' relationship does not trigger _validate_pair."""- mgr, _ = _manager()- c1, c2 = _c("c1"), _c("c2")-- mgr.relationships[("c1", "c2")] = ConstraintRelationship(- "c1", "c2", "dependent", 0.9- )-- with patch.object(mgr, "_validate_pair") as mock_vp:- mgr.validate_candidate_across_constraints(- Candidate(name="Bob"), [c1, c2]- )-- mock_vp.assert_not_called()-- def test_max_score_preserved(self):- """If both cluster and pairwise validation produce scores, max is kept."""- mgr, _ = _manager()- c1, c2 = _c("c1"), _c("c2")-- cluster = _cluster([c1, c2], queries=["q"])- mgr.clusters = [cluster]- mgr.relationships[("c1", "c2")] = ConstraintRelationship(- "c1", "c2", "complementary", 0.9- )-- with (- patch.object(mgr, "_validate_with_cluster", return_value=0.5),- patch.object(mgr, "_validate_pair", return_value=0.9),- ):- result = mgr.validate_candidate_across_constraints(- Candidate(name="Eve"), [c1, c2]- )-- assert result["c1"] == pytest.approx(0.9)- assert result["c2"] == pytest.approx(0.9)---# ----------------------------------------------------------------------------# 6. test_deduplicate_clusters-# ------------------------------------------------------------------------------class TestDeduplicateClusters:- """_deduplicate_clusters removes clusters with identical constraint-id sets."""-- def test_identical_sets_first_kept(self):- """When two clusters share the same IDs, only the first is kept."""- mgr, _ = _manager()- c1, c2 = _c("c1"), _c("c2")-- cl_a = _cluster([c1, c2], ctype="type_based")- cl_b = _cluster([c2, c1], ctype="semantic") # same IDs, different order-- result = mgr._deduplicate_clusters([cl_a, cl_b])-- assert len(result) == 1- assert result[0].cluster_type == "type_based"-- def test_different_sets_both_kept(self):- """Clusters with different ID sets are both retained."""- mgr, _ = _manager()- c1, c2, c3 = _c("c1"), _c("c2"), _c("c3")-- result = mgr._deduplicate_clusters(- [- _cluster([c1, c2]),- _cluster([c2, c3]),- ]- )-- assert len(result) == 2-- def test_three_clusters_two_duplicates(self):- """Three clusters where two are duplicates leaves two unique ones."""- mgr, _ = _manager()- c1, c2, c3 = _c("c1"), _c("c2"), _c("c3")-- result = mgr._deduplicate_clusters(- [- _cluster([c1, c2], ctype="A"),- _cluster([c1, c2], ctype="B"), # dup- _cluster([c2, c3], ctype="C"),- ]- )-- assert len(result) == 2- types = {cl.cluster_type for cl in result}- assert "A" in types- assert "C" in types-- def test_empty_input_returns_empty(self):- mgr, _ = _manager()- assert mgr._deduplicate_clusters([]) == []-- def test_single_cluster_returned_unchanged(self):- mgr, _ = _manager()- cl = _cluster([_c("c1"), _c("c2")])- result = mgr._deduplicate_clusters([cl])- assert result == [cl]---# ----------------------------------------------------------------------------# 7. test_calculate_cluster_coherence_no_pairs-# ------------------------------------------------------------------------------class TestCalculateClusterCoherenceNoPairs:- """_calculate_cluster_coherence returns 0.5 when no pair has a relationship."""-- def test_two_constraints_no_relationships_returns_half(self):- mgr, _ = _manager()- # Empty relationships dict — no entry for (c1, c2)- result = mgr._calculate_cluster_coherence([_c("c1"), _c("c2")])- assert result == pytest.approx(0.5)-- def test_three_constraints_no_relationships_returns_half(self):- mgr, _ = _manager()- result = mgr._calculate_cluster_coherence(- [_c("c1"), _c("c2"), _c("c3")]- )- assert result == pytest.approx(0.5)-- def test_single_constraint_returns_zero(self):- """Source guard: < 2 constraints always returns 0.0."""- mgr, _ = _manager()- assert mgr._calculate_cluster_coherence([_c("c1")]) == 0.0-- def test_empty_constraints_returns_zero(self):- mgr, _ = _manager()- assert mgr._calculate_cluster_coherence([]) == 0.0-- def test_with_one_relationship_above_half(self):- """A strong relationship pushes coherence above the 0.5 default."""- mgr, _ = _manager()- mgr.relationships[("c1", "c2")] = ConstraintRelationship(- "c1", "c2", "complementary", 1.0- )- result = mgr._calculate_cluster_coherence([_c("c1"), _c("c2")])- # avg_strength=1.0, size_factor=min(2/5,1)=0.4 → 1.0*(0.7+0.3*0.4)=0.82- assert result > 0.5-- def test_coherence_formula_two_constraints(self):- """Exact formula check for two constraints with one relationship."""- mgr, _ = _manager()- mgr.relationships[("c1", "c2")] = ConstraintRelationship(- "c1", "c2", "complementary", 0.8- )- result = mgr._calculate_cluster_coherence([_c("c1"), _c("c2")])- # avg_strength=0.8, size_factor=min(2/5, 1.0)=0.4- # → 0.8 * (0.7 + 0.3 * 0.4) = 0.8 * 0.82 = 0.656- assert result == pytest.approx(0.8 * (0.7 + 0.3 * (2 / 5.0)))---# ----------------------------------------------------------------------------# 8. test_optimize_search_order-# ------------------------------------------------------------------------------class TestOptimizeSearchOrder:- """optimize_search_order sorts clusters by coherence * number of constraints."""-- def test_higher_product_comes_first(self):- """Cluster with larger coherence*size product is sorted earlier."""- mgr, _ = _manager()-- # score = 0.5 * 2 = 1.0- cl_low = _cluster([_c("c1"), _c("c2")], coherence=0.5)- # score = 0.8 * 3 = 2.4- cl_high = _cluster([_c("c3"), _c("c4"), _c("c5")], coherence=0.8)-- result = mgr.optimize_search_order([cl_low, cl_high])-- assert result[0] is cl_high- assert result[1] is cl_low-- def test_three_clusters_descending_order(self):- """Three clusters are sorted descending by coherence*size."""- mgr, _ = _manager()-- # scores: 0.9, 1.2, 0.9*1=0.9 — ensure strict ordering- cl_a = _cluster([_c("a1")], coherence=0.9) # 0.9- cl_b = _cluster([_c("b1"), _c("b2")], coherence=0.6) # 1.2- cl_c = _cluster([_c("c1"), _c("c2"), _c("c3")], coherence=0.3) # 0.9-- result = mgr.optimize_search_order([cl_a, cl_b, cl_c])-- scores = [cl.coherence_score * len(cl.constraints) for cl in result]- assert scores == sorted(scores, reverse=True)- assert result[0] is cl_b-- def test_empty_list_returns_empty(self):- mgr, _ = _manager()- assert mgr.optimize_search_order([]) == []-- def test_single_cluster_returned(self):- mgr, _ = _manager()- cl = _cluster([_c("c1"), _c("c2")], coherence=0.7)- result = mgr.optimize_search_order([cl])- assert result == [cl]-- def test_equal_products_all_returned(self):- """When products are equal, all clusters still appear in result."""- mgr, _ = _manager()- # Both have coherence*size = 1.0- cl_a = _cluster([_c("a1")], coherence=1.0)- cl_b = _cluster([_c("b1")], coherence=1.0)-- result = mgr.optimize_search_order([cl_a, cl_b])-- assert len(result) == 2- # ConstraintCluster is a mutable dataclass (not hashable); use identity checks- assert any(r is cl_a for r in result)- assert any(r is cl_b for r in result)diff --git a/tests/advanced_search_system/search_optimization/test_cross_constraint_coverage.py b/tests/advanced_search_system/search_optimization/test_cross_constraint_coverage.pydeleted file mode 100644index f9f3392348..0000000000--- a/tests/advanced_search_system/search_optimization/test_cross_constraint_coverage.py+++ /dev/null@@ -1,514 +0,0 @@-"""-Coverage tests for CrossConstraintManager.--Tests cover missing branches in:-- _analyze_pair: parsing Type/Strength/Evidence lines, invalid strength-- analyze_constraint_relationships: strength threshold filtering, graph update-- _calculate_cluster_coherence: no pairs, single constraint, size factor-- _deduplicate_clusters: exact duplicates removed, unique kept-- _format_constraints_for_clustering / _format_constraints_for_query-- optimize_search_order: sorted by coherence * size descending-- generate_cross_constraint_queries: calls sub-generators, stores in cluster-- _generate_intersection_query: NONE response returns None-- _generate_validation_queries: limited to 2 queries-- validate_candidate_across_constraints: complementary relationship boost-- _validate_with_cluster: no queries triggers generation-- create_constraint_clusters: pre-existing relationships skipped-"""--from unittest.mock import MagicMock, patch--from local_deep_research.advanced_search_system.constraints.base_constraint import (- Constraint,- ConstraintType,-)-from local_deep_research.advanced_search_system.candidates.base_candidate import (- Candidate,-)-from local_deep_research.advanced_search_system.search_optimization.cross_constraint_manager import (- ConstraintCluster,- ConstraintRelationship,- CrossConstraintManager,-)--MODULE = "local_deep_research.advanced_search_system.search_optimization.cross_constraint_manager"---# ----------------------------------------------------------------------------# Helpers-# ------------------------------------------------------------------------------def _make_manager():- """Create a CrossConstraintManager with a mocked model."""- model = MagicMock()- return CrossConstraintManager(model=model), model---def _constraint(- cid, description="desc", ctype=ConstraintType.PROPERTY, weight=1.0-):- return Constraint(- id=cid,- type=ctype,- description=description,- value=description,- weight=weight,- )---def _cluster(- constraints, cluster_type="type_based", coherence=0.5, queries=None-):- c = ConstraintCluster(- constraints=constraints,- cluster_type=cluster_type,- coherence_score=coherence,- )- if queries is not None:- c.search_queries = queries- return c---# ----------------------------------------------------------------------------# _analyze_pair tests-# ------------------------------------------------------------------------------class TestAnalyzePair:- """Tests for _analyze_pair LLM response parsing."""-- def test_parses_type_strength_evidence(self):- """Valid response lines are parsed into relationship fields."""- manager, model = _make_manager()- model.invoke.return_value = MagicMock(- content="Type: complementary\nStrength: 0.8\nEvidence: they overlap"- )- c1 = _constraint("c1")- c2 = _constraint("c2")-- rel = manager._analyze_pair(c1, c2)-- assert rel.relationship_type == "complementary"- assert rel.strength == 0.8- assert rel.evidence == ["they overlap"]- assert rel.constraint1_id == "c1"- assert rel.constraint2_id == "c2"-- def test_invalid_strength_defaults_to_zero(self):- """Non-numeric strength value is caught and defaults to 0.0."""- manager, model = _make_manager()- model.invoke.return_value = MagicMock(- content="Type: dependent\nStrength: high\nEvidence: some reason"- )- c1 = _constraint("c1")- c2 = _constraint("c2")-- rel = manager._analyze_pair(c1, c2)-- assert rel.strength == 0.0-- def test_no_matching_lines_gives_defaults(self):- """Response with no matching prefixes yields none/0.0 defaults."""- manager, model = _make_manager()- model.invoke.return_value = MagicMock(content="Nothing useful here")- c1 = _constraint("c1")- c2 = _constraint("c2")-- rel = manager._analyze_pair(c1, c2)-- assert rel.relationship_type == "none"- assert rel.strength == 0.0- assert rel.evidence == []-- def test_remove_think_tags_called(self):- """remove_think_tags is applied to the model response content."""- manager, model = _make_manager()- model.invoke.return_value = MagicMock(- content="<think>hidden</think>Type: exclusive\nStrength: 0.5"- )- with patch(- f"{MODULE}.remove_think_tags",- return_value="Type: exclusive\nStrength: 0.5",- ) as mock_rtt:- c1 = _constraint("c1")- c2 = _constraint("c2")- manager._analyze_pair(c1, c2)- mock_rtt.assert_called_once()---# ----------------------------------------------------------------------------# analyze_constraint_relationships tests-# ------------------------------------------------------------------------------class TestAnalyzeConstraintRelationships:- """Tests for analyze_constraint_relationships filtering and graph update."""-- def test_low_strength_relationship_excluded(self):- """Relationships with strength <= 0.3 are not stored."""- manager, model = _make_manager()- model.invoke.return_value = MagicMock(- content="Type: none\nStrength: 0.2\nEvidence: weak"- )- constraints = [_constraint("c1"), _constraint("c2")]-- result = manager.analyze_constraint_relationships(constraints)-- assert len(result) == 0- assert not manager.constraint_graph-- def test_high_strength_relationship_stored(self):- """Relationships with strength > 0.3 are stored and graph updated."""- manager, model = _make_manager()- model.invoke.return_value = MagicMock(- content="Type: complementary\nStrength: 0.9\nEvidence: strong"- )- constraints = [_constraint("c1"), _constraint("c2")]-- result = manager.analyze_constraint_relationships(constraints)-- assert ("c1", "c2") in result- assert "c2" in manager.constraint_graph["c1"]- assert "c1" in manager.constraint_graph["c2"]-- def test_three_constraints_all_pairs_analyzed(self):- """For 3 constraints, itertools.combinations produces 3 pairs."""- manager, model = _make_manager()- model.invoke.return_value = MagicMock(- content="Type: complementary\nStrength: 0.8"- )- constraints = [_constraint(f"c{i}") for i in range(3)]-- manager.analyze_constraint_relationships(constraints)-- assert model.invoke.call_count == 3---# ----------------------------------------------------------------------------# _calculate_cluster_coherence tests-# ------------------------------------------------------------------------------class TestCalculateClusterCoherence:- """Tests for _calculate_cluster_coherence."""-- def test_single_constraint_returns_zero(self):- """Fewer than 2 constraints returns 0.0."""- manager, _ = _make_manager()- result = manager._calculate_cluster_coherence([_constraint("c1")])- assert result == 0.0-- def test_no_relationships_returns_default(self):- """No relationships in self.relationships returns 0.5 default."""- manager, _ = _make_manager()- # Empty relationships dict - no entries for any pair- result = manager._calculate_cluster_coherence(- [_constraint("c1"), _constraint("c2")]- )- assert result == 0.5-- def test_with_relationships_uses_average_strength(self):- """When relationships exist, coherence is based on average strength."""- manager, _ = _make_manager()- manager.relationships[("c1", "c2")] = ConstraintRelationship(- constraint1_id="c1",- constraint2_id="c2",- relationship_type="complementary",- strength=0.8,- )- c1 = _constraint("c1")- c2 = _constraint("c2")-- result = manager._calculate_cluster_coherence([c1, c2])-- # avg_strength=0.8, size_factor = min(2/5.0, 1.0)=0.4 -> 0.8*(0.7+0.3*0.4)=0.8*0.82=0.656- assert 0.5 < result < 1.0-- def test_five_constraints_size_factor_capped(self):- """size_factor is capped at 1.0 for 5 or more constraints."""- manager, _ = _make_manager()- constraints = [_constraint(f"c{i}") for i in range(5)]- # Add relationship for first pair- manager.relationships[("c0", "c1")] = ConstraintRelationship(- constraint1_id="c0",- constraint2_id="c1",- relationship_type="complementary",- strength=1.0,- )-- result = manager._calculate_cluster_coherence(constraints)-- # avg_strength over 10 pairs: only c0-c1 exists so 1.0/1 = 1.0- # size_factor = min(5/5.0, 1.0) = 1.0 -> 1.0 * (0.7 + 0.3*1.0) = 1.0- assert result == 1.0---# ----------------------------------------------------------------------------# _deduplicate_clusters tests-# ------------------------------------------------------------------------------class TestDeduplicateClusters:- """Tests for _deduplicate_clusters."""-- def test_exact_duplicate_removed(self):- """Two clusters with the same constraint IDs: only first kept."""- manager, _ = _make_manager()- c1, c2 = _constraint("c1"), _constraint("c2")- clusters = [- _cluster([c1, c2], cluster_type="type_based"),- _cluster([c2, c1], cluster_type="semantic"), # same set- ]-- result = manager._deduplicate_clusters(clusters)-- assert len(result) == 1- assert result[0].cluster_type == "type_based"-- def test_unique_clusters_both_kept(self):- """Two clusters with different sets: both kept."""- manager, _ = _make_manager()- c1, c2, c3 = _constraint("c1"), _constraint("c2"), _constraint("c3")- clusters = [- _cluster([c1, c2]),- _cluster([c2, c3]),- ]-- result = manager._deduplicate_clusters(clusters)-- assert len(result) == 2-- def test_empty_list_returns_empty(self):- """Empty input returns empty output."""- manager, _ = _make_manager()- assert manager._deduplicate_clusters([]) == []---# ----------------------------------------------------------------------------# optimize_search_order tests-# ------------------------------------------------------------------------------class TestOptimizeSearchOrder:- """Tests for optimize_search_order."""-- def test_sorted_by_coherence_times_size_descending(self):- """Clusters with highest coherence * num_constraints come first."""- manager, _ = _make_manager()- c1, c2, c3 = _constraint("c1"), _constraint("c2"), _constraint("c3")- clusters = [- _cluster([c1], coherence=0.9), # score = 0.9 * 1 = 0.9- _cluster([c2, c3], coherence=0.6), # score = 0.6 * 2 = 1.2- ]-- result = manager.optimize_search_order(clusters)-- assert result[0].coherence_score == 0.6 # higher product comes first-- def test_empty_list_returns_empty(self):- """Empty input produces empty output."""- manager, _ = _make_manager()- assert manager.optimize_search_order([]) == []---# ----------------------------------------------------------------------------# _generate_intersection_query tests-# ------------------------------------------------------------------------------class TestGenerateIntersectionQuery:- """Tests for _generate_intersection_query."""-- def test_single_constraint_returns_none(self):- """Less than 2 constraints short-circuits to None without LLM call."""- manager, model = _make_manager()- result = manager._generate_intersection_query([_constraint("c1")])- assert result is None- model.invoke.assert_not_called()-- def test_none_response_returns_none(self):- """When LLM returns 'NONE', method returns None."""- manager, model = _make_manager()- model.invoke.return_value = MagicMock(content="NONE")- with patch(f"{MODULE}.remove_think_tags", return_value="NONE"):- result = manager._generate_intersection_query(- [_constraint("c1"), _constraint("c2")]- )- assert result is None-- def test_valid_response_returned(self):- """Non-NONE LLM response is returned as query string."""- manager, model = _make_manager()- model.invoke.return_value = MagicMock(content="climate AND temperature")- with patch(- f"{MODULE}.remove_think_tags",- return_value="climate AND temperature",- ):- result = manager._generate_intersection_query(- [_constraint("c1"), _constraint("c2")]- )- assert result == "climate AND temperature"---# ----------------------------------------------------------------------------# _generate_validation_queries tests-# ------------------------------------------------------------------------------class TestGenerateValidationQueries:- """Tests for _generate_validation_queries."""-- def test_limited_to_two_queries(self):- """At most 2 queries returned even for 3 constraints (3 pairs)."""- manager, model = _make_manager()- model.invoke.return_value = MagicMock(content="search query")- with patch(f"{MODULE}.remove_think_tags", return_value="search query"):- constraints = [_constraint(f"c{i}") for i in range(3)]- result = manager._generate_validation_queries(constraints)- assert len(result) == 2-- def test_one_or_two_constraints_yields_one_query(self):- """With 2 constraints there is exactly 1 pair -> 1 query (capped at 2)."""- manager, model = _make_manager()- model.invoke.return_value = MagicMock(content="pair query")- with patch(f"{MODULE}.remove_think_tags", return_value="pair query"):- result = manager._generate_validation_queries(- [_constraint("c1"), _constraint("c2")]- )- assert len(result) == 1---# ----------------------------------------------------------------------------# validate_candidate_across_constraints tests-# ------------------------------------------------------------------------------class TestValidateCandidateAcrossConstraints:- """Tests for validate_candidate_across_constraints."""-- def test_no_clusters_returns_empty(self):- """When no clusters exist scores dict is empty."""- manager, _ = _make_manager()- candidate = Candidate(name="Test")- result = manager.validate_candidate_across_constraints(- candidate, [_constraint("c1")]- )- assert result == {}-- def test_complementary_relationship_boosts_pair_scores(self):- """When c1-c2 is 'complementary', _validate_pair is called to boost."""- manager, model = _make_manager()- c1 = _constraint("c1")- c2 = _constraint("c2")-- # Register as complementary relationship- manager.relationships[("c1", "c2")] = ConstraintRelationship(- constraint1_id="c1",- constraint2_id="c2",- relationship_type="complementary",- strength=0.9,- )-- candidate = Candidate(name="MyCandidate")-- with patch.object(- manager, "_validate_pair", return_value=0.75- ) as mock_vp:- result = manager.validate_candidate_across_constraints(- candidate, [c1, c2]- )-- mock_vp.assert_called_once_with(candidate, c1, c2)- assert result.get("c1") == 0.75- assert result.get("c2") == 0.75---# ----------------------------------------------------------------------------# _validate_with_cluster tests-# ------------------------------------------------------------------------------class TestValidateWithCluster:- """Tests for _validate_with_cluster."""-- def test_no_queries_triggers_generation(self):- """If cluster has no search_queries, generate_cross_constraint_queries is called."""- manager, model = _make_manager()- c1 = _constraint("c1")- cluster = _cluster([c1], queries=[])-- with patch.object(- manager,- "generate_cross_constraint_queries",- return_value=["generated query"],- ) as mock_gen:- model.invoke.return_value = MagicMock(content="Score: 0.7")- with patch(- f"{MODULE}.remove_think_tags", return_value="Score: 0.7"- ):- manager._validate_with_cluster(Candidate(name="X"), cluster)- mock_gen.assert_called_once_with(cluster)-- def test_parses_score_from_response(self):- """Score line is correctly parsed from model response."""- manager, model = _make_manager()- c1 = _constraint("c1")- cluster = _cluster([c1], queries=["existing query"])- candidate = Candidate(name="MyEntity")-- model.invoke.return_value = MagicMock(- content="Score: 0.85\nExplanation: strong match"- )- with patch(- f"{MODULE}.remove_think_tags",- return_value="Score: 0.85\nExplanation: strong match",- ):- score = manager._validate_with_cluster(candidate, cluster)-- assert score == 0.85-- def test_invalid_score_defaults_to_zero(self):- """Non-numeric score value defaults to 0.0."""- manager, model = _make_manager()- c1 = _constraint("c1")- cluster = _cluster([c1], queries=["q"])-- model.invoke.return_value = MagicMock(content="Score: high")- with patch(f"{MODULE}.remove_think_tags", return_value="Score: high"):- score = manager._validate_with_cluster(Candidate(name="X"), cluster)-- assert score == 0.0---# ----------------------------------------------------------------------------# _format helpers tests-# ------------------------------------------------------------------------------class TestFormatHelpers:- """Tests for _format_constraints_for_clustering and _format_constraints_for_query."""-- def test_format_clustering_includes_id_and_type(self):- """Clustering format includes constraint id, description, type and weight."""- manager, _ = _make_manager()- c = _constraint(- "c1", "some description", ConstraintType.TEMPORAL, weight=0.5- )-- result = manager._format_constraints_for_clustering([c])-- assert "c1" in result- assert "some description" in result- assert "temporal" in result- assert "0.5" in result-- def test_format_query_includes_description_and_type(self):- """Query format includes constraint description and type."""- manager, _ = _make_manager()- c = _constraint("c1", "spatial filter", ConstraintType.LOCATION)-- result = manager._format_constraints_for_query([c])-- assert "spatial filter" in result- assert "location" in resultdiff --git a/tests/advanced_search_system/search_optimization/test_cross_constraint_edge_cases.py b/tests/advanced_search_system/search_optimization/test_cross_constraint_edge_cases.pydeleted file mode 100644index 9a0706f081..0000000000--- a/tests/advanced_search_system/search_optimization/test_cross_constraint_edge_cases.py+++ /dev/null@@ -1,173 +0,0 @@-"""High-value edge case tests for search_optimization/cross_constraint_manager.py.--Covers dataclass mutable defaults, relationship graph updates,-coherence formula boundaries, and deduplication edge cases.-"""--from unittest.mock import MagicMock--from local_deep_research.advanced_search_system.search_optimization.cross_constraint_manager import (- CrossConstraintManager,- ConstraintRelationship,- ConstraintCluster,-)-from local_deep_research.advanced_search_system.constraints.base_constraint import (- Constraint,- ConstraintType,-)---def _make_constraint(- ctype=ConstraintType.PROPERTY, value="test", desc="test", cid=None-):- return Constraint(- id=cid or f"{ctype.value}_{value}",- type=ctype,- value=value,- description=desc,- weight=1.0,- )---def _make_manager():- mock_model = MagicMock()- mock_model.invoke.return_value = MagicMock(- content="Relationship: complementary\nStrength: 0.8\nEvidence: test"- )- return CrossConstraintManager(mock_model)---class TestConstraintRelationshipMutableDefaults:- """Test ConstraintRelationship dataclass field independence."""-- def test_evidence_lists_independent_per_instance(self):- """Each instance has its own evidence list."""- r1 = ConstraintRelationship(- constraint1_id="a",- constraint2_id="b",- relationship_type="complementary",- strength=0.5,- )- r2 = ConstraintRelationship(- constraint1_id="c",- constraint2_id="d",- relationship_type="conflicting",- strength=0.3,- )- r1.evidence.append("test evidence")- assert len(r2.evidence) == 0-- def test_strength_boundary_values(self):- """Boundary values 0.0 and 1.0 are stored correctly."""- r_low = ConstraintRelationship(- constraint1_id="a",- constraint2_id="b",- relationship_type="weak",- strength=0.0,- )- r_high = ConstraintRelationship(- constraint1_id="a",- constraint2_id="b",- relationship_type="strong",- strength=1.0,- )- assert r_low.strength == 0.0- assert r_high.strength == 1.0---class TestConstraintClusterMutableDefaults:- """Test ConstraintCluster field independence."""-- def test_search_queries_independent_per_instance(self):- """Each cluster has its own search_queries list."""- c = _make_constraint()- c1 = ConstraintCluster(- constraints=[c],- cluster_type="type_based",- coherence_score=0.5,- )- c2 = ConstraintCluster(- constraints=[c],- cluster_type="type_based",- coherence_score=0.5,- )- c1.search_queries.append("query1")- assert len(c2.search_queries) == 0---class TestCalculateClusterCoherence:- """Test _calculate_cluster_coherence formula."""-- def test_no_relationships_returns_zero(self):- """With no relationships, coherence is 0.0."""- mgr = _make_manager()- constraints = [_make_constraint(value="c1")]- result = mgr._calculate_cluster_coherence(constraints)- assert result == 0.0---class TestDeduplicateClusters:- """Test _deduplicate_clusters edge cases."""-- def test_empty_input_returns_empty(self):- """Empty list returns empty list."""- mgr = _make_manager()- assert mgr._deduplicate_clusters([]) == []-- def test_first_occurrence_kept(self):- """First cluster with a given constraint set is kept."""- mgr = _make_manager()- c = _make_constraint()- cluster_a = ConstraintCluster(- constraints=[c],- cluster_type="type_a",- coherence_score=0.5,- )- cluster_b = ConstraintCluster(- constraints=[c],- cluster_type="type_b",- coherence_score=0.8,- )- result = mgr._deduplicate_clusters([cluster_a, cluster_b])- assert len(result) == 1- assert result[0].cluster_type == "type_a"---class TestManagerInit:- """Test CrossConstraintManager initialization."""-- def test_init_creates_empty_relationships(self):- """Manager starts with empty relationships."""- mgr = _make_manager()- assert len(mgr.relationships) == 0-- def test_init_creates_empty_clusters(self):- """Manager starts with empty clusters."""- mgr = _make_manager()- assert len(mgr.clusters) == 0---class TestFormatHelpers:- """Test _format_constraints_for_clustering and _format_constraints_for_query."""-- def test_clustering_format_each_on_own_line(self):- """Each constraint appears on its own line."""- mgr = _make_manager()- constraints = [- _make_constraint(value="v1", desc="d1"),- _make_constraint(value="v2", desc="d2"),- _make_constraint(value="v3", desc="d3"),- ]- result = mgr._format_constraints_for_clustering(constraints)- lines = [line for line in result.split("\n") if line.strip()]- assert len(lines) == 3-- def test_query_format_bullet_count(self):- """Each constraint gets a '- ' bullet prefix."""- mgr = _make_manager()- constraints = [- _make_constraint(value="v1", desc="d1"),- _make_constraint(value="v2", desc="d2"),- ]- result = mgr._format_constraints_for_query(constraints)- assert result.count("- ") == 2diff --git a/tests/advanced_search_system/search_optimization/test_cross_constraint_manager.py b/tests/advanced_search_system/search_optimization/test_cross_constraint_manager.pydeleted file mode 100644index ec82b0b7e1..0000000000--- a/tests/advanced_search_system/search_optimization/test_cross_constraint_manager.py+++ /dev/null@@ -1,780 +0,0 @@-"""-Tests for Cross Constraint Manager--Covers the CrossConstraintManager class and related dataclasses including-constraint relationship analysis, clustering, query generation, and validation.-"""--from collections import defaultdict-from dataclasses import fields-from unittest.mock import MagicMock--import pytest--from tests.test_utils import add_src_to_path--add_src_to_path()--from local_deep_research.advanced_search_system.constraints.base_constraint import ( # noqa: E402- Constraint,- ConstraintType,-)-from local_deep_research.advanced_search_system.search_optimization.cross_constraint_manager import ( # noqa: E402- ConstraintCluster,- ConstraintRelationship,- CrossConstraintManager,-)---# ============================================================================-# Test Fixtures-# ============================================================================---def mock_model():- """Create a mock LLM model."""- model = MagicMock()- return model---def sample_constraints():- """Create sample constraints for testing."""- return [- Constraint(- id="c1",- type=ConstraintType.TEMPORAL,- description="Happened in 2020",- value="2020",- weight=0.9,- ),- Constraint(- id="c2",- type=ConstraintType.LOCATION,- description="Located in Colorado",- value="Colorado",- weight=0.8,- ),- Constraint(- id="c3",- type=ConstraintType.PROPERTY,- description="Has mountain peak",- value="mountain peak",- weight=0.7,- ),- Constraint(- id="c4",- type=ConstraintType.TEMPORAL,- description="After 2015",- value="after 2015",- weight=0.6,- ),- ]---def manager(mock_model):- """Create a CrossConstraintManager instance."""- return CrossConstraintManager(mock_model)---# ============================================================================-# Tests for ConstraintRelationship Dataclass-# ============================================================================---class TestConstraintRelationship:- """Tests for ConstraintRelationship dataclass."""-- def test_creation_with_required_fields(self):- """Should create with required fields."""- rel = ConstraintRelationship(- constraint1_id="c1",- constraint2_id="c2",- relationship_type="complementary",- strength=0.8,- )-- assert rel.constraint1_id == "c1"- assert rel.constraint2_id == "c2"- assert rel.relationship_type == "complementary"- assert rel.strength == 0.8-- def test_default_evidence_list(self):- """Should have empty list as default evidence."""- rel = ConstraintRelationship(- constraint1_id="c1",- constraint2_id="c2",- relationship_type="dependent",- strength=0.5,- )-- assert rel.evidence == []- assert isinstance(rel.evidence, list)-- def test_creation_with_evidence(self):- """Should create with provided evidence."""- evidence = ["They share temporal context", "Both relate to events"]- rel = ConstraintRelationship(- constraint1_id="c1",- constraint2_id="c2",- relationship_type="complementary",- strength=0.9,- evidence=evidence,- )-- assert rel.evidence == evidence- assert len(rel.evidence) == 2-- def test_field_types(self):- """Should have correct field types."""- rel_fields = {f.name: f.type for f in fields(ConstraintRelationship)}-- assert rel_fields["constraint1_id"] is str- assert rel_fields["constraint2_id"] is str- assert rel_fields["relationship_type"] is str- assert rel_fields["strength"] is float---# ============================================================================-# Tests for ConstraintCluster Dataclass-# ============================================================================---class TestConstraintCluster:- """Tests for ConstraintCluster dataclass."""-- def test_creation_with_required_fields(self, sample_constraints):- """Should create with required fields."""- cluster = ConstraintCluster(- constraints=sample_constraints[:2],- cluster_type="temporal",- coherence_score=0.75,- )-- assert len(cluster.constraints) == 2- assert cluster.cluster_type == "temporal"- assert cluster.coherence_score == 0.75-- def test_default_search_queries(self, sample_constraints):- """Should have empty list as default search_queries."""- cluster = ConstraintCluster(- constraints=sample_constraints,- cluster_type="spatial",- coherence_score=0.6,- )-- assert cluster.search_queries == []- assert isinstance(cluster.search_queries, list)-- def test_creation_with_queries(self, sample_constraints):- """Should create with provided search queries."""- queries = ["query 1", "query 2"]- cluster = ConstraintCluster(- constraints=sample_constraints[:2],- cluster_type="causal",- coherence_score=0.8,- search_queries=queries,- )-- assert cluster.search_queries == queries- assert len(cluster.search_queries) == 2---# ============================================================================-# Tests for CrossConstraintManager Initialization-# ============================================================================---class TestCrossConstraintManagerInit:- """Tests for CrossConstraintManager initialization."""-- def test_initialization_with_model(self, mock_model):- """Should initialize with provided model."""- manager = CrossConstraintManager(mock_model)-- assert manager.model is mock_model-- def test_initial_relationships_empty(self, mock_model):- """Should have empty relationships dict on init."""- manager = CrossConstraintManager(mock_model)-- assert manager.relationships == {}- assert isinstance(manager.relationships, dict)-- def test_initial_clusters_empty(self, mock_model):- """Should have empty clusters list on init."""- manager = CrossConstraintManager(mock_model)-- assert manager.clusters == []- assert isinstance(manager.clusters, list)-- def test_initial_cross_validation_patterns(self, mock_model):- """Should have defaultdict for cross_validation_patterns."""- manager = CrossConstraintManager(mock_model)-- assert isinstance(manager.cross_validation_patterns, defaultdict)- # Accessing non-existent key should return empty list- assert manager.cross_validation_patterns["nonexistent"] == []-- def test_initial_constraint_graph(self, mock_model):- """Should have defaultdict for constraint_graph."""- manager = CrossConstraintManager(mock_model)-- assert isinstance(manager.constraint_graph, defaultdict)- # Accessing non-existent key should return empty set- assert manager.constraint_graph["nonexistent"] == set()---# ============================================================================-# Tests for analyze_constraint_relationships-# ============================================================================---class TestAnalyzeConstraintRelationships:- """Tests for analyze_constraint_relationships method."""-- def test_empty_list_returns_empty(self, manager):- """Should return empty dict for empty constraint list."""- result = manager.analyze_constraint_relationships([])-- assert result == {}-- def test_single_constraint_returns_empty(self, manager, sample_constraints):- """Should return empty dict for single constraint."""- result = manager.analyze_constraint_relationships(- [sample_constraints[0]]- )-- assert result == {}-- def test_calls_model_for_pairs(- self, manager, sample_constraints, mock_model- ):- """Should call model.invoke for each constraint pair."""- mock_response = MagicMock()- mock_response.content = (- "Type: complementary\nStrength: 0.8\nEvidence: Related"- )- mock_model.invoke.return_value = mock_response-- # Two constraints = 1 pair- manager.analyze_constraint_relationships(sample_constraints[:2])-- assert mock_model.invoke.call_count == 1-- def test_filters_by_strength_threshold(- self, manager, sample_constraints, mock_model- ):- """Should only keep relationships with strength > 0.3."""- # First pair: weak relationship- mock_response_weak = MagicMock()- mock_response_weak.content = (- "Type: none\nStrength: 0.1\nEvidence: Unrelated"- )-- # Second pair: strong relationship- mock_response_strong = MagicMock()- mock_response_strong.content = (- "Type: complementary\nStrength: 0.8\nEvidence: Related"- )-- mock_model.invoke.side_effect = [- mock_response_weak,- mock_response_strong,- ]-- # Three constraints = 3 pairs, but mock only 2 for simplicity- result = manager.analyze_constraint_relationships(- sample_constraints[:2]- )-- # Weak relationship should not be included- if result:- for rel in result.values():- assert rel.strength > 0.3-- def test_updates_constraint_graph(- self, manager, sample_constraints, mock_model- ):- """Should update constraint_graph for strong relationships."""- mock_response = MagicMock()- mock_response.content = (- "Type: complementary\nStrength: 0.8\nEvidence: Related"- )- mock_model.invoke.return_value = mock_response-- manager.analyze_constraint_relationships(sample_constraints[:2])-- # Both constraints should have each other in their graph- c1_neighbors = manager.constraint_graph["c1"]- c2_neighbors = manager.constraint_graph["c2"]-- assert "c2" in c1_neighbors or len(manager.relationships) == 0- assert "c1" in c2_neighbors or len(manager.relationships) == 0---# ============================================================================-# Tests for _analyze_pair-# ============================================================================---class TestAnalyzePair:- """Tests for _analyze_pair method."""-- def test_parses_response_correctly(- self, manager, sample_constraints, mock_model- ):- """Should parse model response correctly."""- mock_response = MagicMock()- mock_response.content = """Type: dependent-Strength: 0.75-Evidence: Temporal ordering required"""- mock_model.invoke.return_value = mock_response-- result = manager._analyze_pair(- sample_constraints[0], sample_constraints[1]- )-- assert result.relationship_type == "dependent"- assert result.strength == 0.75- assert "Temporal ordering required" in result.evidence-- def test_handles_malformed_response(- self, manager, sample_constraints, mock_model- ):- """Should handle malformed responses gracefully."""- mock_response = MagicMock()- mock_response.content = "This is not formatted correctly at all"- mock_model.invoke.return_value = mock_response-- result = manager._analyze_pair(- sample_constraints[0], sample_constraints[1]- )-- # Should return default values- assert result.relationship_type == "none"- assert result.strength == 0.0- assert result.constraint1_id == "c1"- assert result.constraint2_id == "c2"-- def test_handles_invalid_strength(- self, manager, sample_constraints, mock_model- ):- """Should handle invalid strength values."""- mock_response = MagicMock()- mock_response.content = (- "Type: complementary\nStrength: not_a_number\nEvidence: Test"- )- mock_model.invoke.return_value = mock_response-- result = manager._analyze_pair(- sample_constraints[0], sample_constraints[1]- )-- assert result.strength == 0.0-- def test_returns_constraint_ids(- self, manager, sample_constraints, mock_model- ):- """Should return correct constraint IDs."""- mock_response = MagicMock()- mock_response.content = (- "Type: none\nStrength: 0.0\nEvidence: No relation"- )- mock_model.invoke.return_value = mock_response-- result = manager._analyze_pair(- sample_constraints[0], sample_constraints[2]- )-- assert result.constraint1_id == "c1"- assert result.constraint2_id == "c3"---# ============================================================================-# Tests for create_constraint_clusters-# ============================================================================---class TestCreateConstraintClusters:- """Tests for create_constraint_clusters method."""-- def test_creates_type_based_clusters(- self, manager, sample_constraints, mock_model- ):- """Should create clusters based on constraint types."""- # Set up minimal mock responses- mock_response = MagicMock()- mock_response.content = "Type: none\nStrength: 0.1\nEvidence: None"- mock_model.invoke.return_value = mock_response-- result = manager.create_constraint_clusters(sample_constraints)-- # Should have at least type-based clusters for TEMPORAL (c1, c4)- type_based = [c for c in result if c.cluster_type == "type_based"]- assert len(type_based) >= 1-- def test_deduplicates_clusters(- self, manager, sample_constraints, mock_model- ):- """Should remove duplicate clusters."""- mock_response = MagicMock()- mock_response.content = "Type: none\nStrength: 0.1\nEvidence: None"- mock_model.invoke.return_value = mock_response-- result = manager.create_constraint_clusters(sample_constraints)-- # Check for uniqueness- seen_sets = []- for cluster in result:- constraint_set = frozenset(c.id for c in cluster.constraints)- assert constraint_set not in seen_sets- seen_sets.append(constraint_set)-- def test_stores_clusters_in_manager(- self, manager, sample_constraints, mock_model- ):- """Should store clusters in manager.clusters."""- mock_response = MagicMock()- mock_response.content = "Type: none\nStrength: 0.1\nEvidence: None"- mock_model.invoke.return_value = mock_response-- result = manager.create_constraint_clusters(sample_constraints)-- assert manager.clusters == result---# ============================================================================-# Tests for _create_relationship_clusters-# ============================================================================---class TestCreateRelationshipClusters:- """Tests for _create_relationship_clusters method."""-- def test_bfs_clustering(self, manager, sample_constraints):- """Should use BFS to find connected components."""- # Create relationships that form a connected component- relationships = [- ConstraintRelationship(- constraint1_id="c1",- constraint2_id="c2",- relationship_type="complementary",- strength=0.8,- ),- ConstraintRelationship(- constraint1_id="c2",- constraint2_id="c3",- relationship_type="complementary",- strength=0.7,- ),- ]-- result = manager._create_relationship_clusters(- sample_constraints[:3], relationships- )-- # c1, c2, c3 should be in same cluster- if result:- cluster_ids = {c.id for c in result[0].constraints}- assert "c1" in cluster_ids- assert "c2" in cluster_ids- assert "c3" in cluster_ids-- def test_isolated_constraints_not_clustered(- self, manager, sample_constraints- ):- """Should not create single-constraint clusters."""- # Only c1 and c2 are related- relationships = [- ConstraintRelationship(- constraint1_id="c1",- constraint2_id="c2",- relationship_type="complementary",- strength=0.8,- ),- ]-- result = manager._create_relationship_clusters(- sample_constraints, relationships- )-- # All clusters should have more than one constraint- for cluster in result:- assert len(cluster.constraints) > 1---# ============================================================================-# Tests for _deduplicate_clusters-# ============================================================================---class TestDeduplicateClusters:- """Tests for _deduplicate_clusters method."""-- def test_removes_exact_duplicates(self, manager, sample_constraints):- """Should remove exact duplicate clusters."""- cluster1 = ConstraintCluster(- constraints=sample_constraints[:2],- cluster_type="type_based",- coherence_score=0.7,- )- cluster2 = ConstraintCluster(- constraints=sample_constraints[:2], # Same constraints- cluster_type="semantic", # Different type- coherence_score=0.8, # Different score- )-- result = manager._deduplicate_clusters([cluster1, cluster2])-- assert len(result) == 1-- def test_keeps_different_sets(self, manager, sample_constraints):- """Should keep clusters with different constraint sets."""- cluster1 = ConstraintCluster(- constraints=sample_constraints[:2],- cluster_type="type_based",- coherence_score=0.7,- )- cluster2 = ConstraintCluster(- constraints=sample_constraints[2:4], # Different constraints- cluster_type="type_based",- coherence_score=0.7,- )-- result = manager._deduplicate_clusters([cluster1, cluster2])-- assert len(result) == 2---# ============================================================================-# Tests for generate_cross_constraint_queries-# ============================================================================---class TestGenerateCrossConstraintQueries:- """Tests for generate_cross_constraint_queries method."""-- def test_generates_multiple_query_types(- self, manager, sample_constraints, mock_model- ):- """Should generate multiple types of queries."""- cluster = ConstraintCluster(- constraints=sample_constraints[:3],- cluster_type="temporal",- coherence_score=0.8,- )-- mock_response = MagicMock()- mock_response.content = "test query"- mock_model.invoke.return_value = mock_response-- result = manager.generate_cross_constraint_queries(cluster)-- # Should have combined, progressive, and validation queries- assert len(result) >= 3-- def test_stores_queries_in_cluster(- self, manager, sample_constraints, mock_model- ):- """Should store queries in cluster.search_queries."""- cluster = ConstraintCluster(- constraints=sample_constraints[:2],- cluster_type="temporal",- coherence_score=0.8,- )-- mock_response = MagicMock()- mock_response.content = "test query"- mock_model.invoke.return_value = mock_response-- result = manager.generate_cross_constraint_queries(cluster)-- assert cluster.search_queries == result---# ============================================================================-# Tests for _generate_intersection_query-# ============================================================================---class TestGenerateIntersectionQuery:- """Tests for _generate_intersection_query method."""-- def test_returns_none_for_single_constraint(- self, manager, sample_constraints- ):- """Should return None for single constraint."""- result = manager._generate_intersection_query([sample_constraints[0]])-- assert result is None-- def test_handles_none_response(- self, manager, sample_constraints, mock_model- ):- """Should handle NONE response from model."""- mock_response = MagicMock()- mock_response.content = "NONE"- mock_model.invoke.return_value = mock_response-- result = manager._generate_intersection_query(sample_constraints[:2])-- assert result is None-- def test_returns_query_on_success(- self, manager, sample_constraints, mock_model- ):- """Should return query when model provides one."""- mock_response = MagicMock()- mock_response.content = "Colorado events in 2020"- mock_model.invoke.return_value = mock_response-- result = manager._generate_intersection_query(sample_constraints[:2])-- assert result == "Colorado events in 2020"---# ============================================================================-# Tests for validate_candidate_across_constraints-# ============================================================================---class TestValidateCandidateAcrossConstraints:- """Tests for validate_candidate_across_constraints method."""-- def test_with_relevant_clusters(- self, manager, sample_constraints, mock_model- ):- """Should validate using relevant clusters."""- from local_deep_research.advanced_search_system.candidates.base_candidate import (- Candidate,- )-- # Set up a cluster- cluster = ConstraintCluster(- constraints=sample_constraints[:2],- cluster_type="temporal",- coherence_score=0.8,- search_queries=["test query"],- )- manager.clusters = [cluster]-- # Mock validation response- mock_response = MagicMock()- mock_response.content = "Score: 0.85\nExplanation: Good match"- mock_model.invoke.return_value = mock_response-- candidate = Candidate(name="Test Candidate")-- result = manager.validate_candidate_across_constraints(- candidate, sample_constraints[:2]- )-- # Should have scores for constraints- assert isinstance(result, dict)---# ============================================================================-# Tests for _calculate_cluster_coherence-# ============================================================================---class TestCalculateClusterCoherence:- """Tests for _calculate_cluster_coherence method."""-- def test_single_constraint_returns_zero(self, manager, sample_constraints):- """Should return 0.0 for single constraint."""- result = manager._calculate_cluster_coherence([sample_constraints[0]])-- assert result == 0.0-- def test_no_relationships_returns_default(- self, manager, sample_constraints- ):- """Should return default 0.5 when no relationships found."""- result = manager._calculate_cluster_coherence(sample_constraints[:2])-- assert result == 0.5-- def test_uses_relationship_strengths(self, manager, sample_constraints):- """Should calculate based on relationship strengths."""- # Add a relationship- manager.relationships[("c1", "c2")] = ConstraintRelationship(- constraint1_id="c1",- constraint2_id="c2",- relationship_type="complementary",- strength=0.9,- )-- result = manager._calculate_cluster_coherence(sample_constraints[:2])-- # Should be > 0.5 (default) since we have strong relationship- assert result > 0.5---# ============================================================================-# Tests for optimize_search_order-# ============================================================================---class TestOptimizeSearchOrder:- """Tests for optimize_search_order method."""-- def test_sorts_by_coherence_times_size(self, manager, sample_constraints):- """Should sort by coherence * size in descending order."""- cluster1 = ConstraintCluster(- constraints=sample_constraints[:2], # size 2- cluster_type="type_based",- coherence_score=0.5, # score = 2 * 0.5 = 1.0- )- cluster2 = ConstraintCluster(- constraints=sample_constraints[:3], # size 3- cluster_type="semantic",- coherence_score=0.8, # score = 3 * 0.8 = 2.4- )- cluster3 = ConstraintCluster(- constraints=sample_constraints[:1], # size 1- cluster_type="relationship_based",- coherence_score=0.9, # score = 1 * 0.9 = 0.9- )-- result = manager.optimize_search_order([cluster1, cluster2, cluster3])-- # cluster2 should be first (highest score), then cluster1, then cluster3- assert result[0] == cluster2- assert result[1] == cluster1- assert result[2] == cluster3---# ============================================================================-# Tests for helper methods-# ============================================================================---class TestFormatConstraintsForClustering:- """Tests for _format_constraints_for_clustering method."""-- def test_formats_all_constraint_info(self, manager, sample_constraints):- """Should include id, description, type, and weight."""- result = manager._format_constraints_for_clustering(- sample_constraints[:1]- )-- assert "c1" in result- assert "Happened in 2020" in result- assert "temporal" in result.lower()- assert "0.9" in result---class TestFormatConstraintsForQuery:- """Tests for _format_constraints_for_query method."""-- def test_formats_description_and_type(self, manager, sample_constraints):- """Should include description and type."""- result = manager._format_constraints_for_query(sample_constraints[:1])-- assert "Happened in 2020" in result- assert "temporal" in result.lower()- assert "-" in result # Should have bullet pointdiff --git a/tests/advanced_search_system/search_optimization/test_cross_constraint_manager_high_value.py b/tests/advanced_search_system/search_optimization/test_cross_constraint_manager_high_value.pydeleted file mode 100644index 3ff34bde45..0000000000--- a/tests/advanced_search_system/search_optimization/test_cross_constraint_manager_high_value.py+++ /dev/null@@ -1,462 +0,0 @@-"""-High-value pure logic tests for CrossConstraintManager.--Focuses on algorithmic behavior: coherence formula math, BFS connected-components, deduplication set logic, search-order sorting, and formatting-helpers -- all without LLM calls.-"""--from unittest.mock import patch--import pytest--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,-)---# ----------------------------------------------------------------------------# Helpers-# ------------------------------------------------------------------------------def _constraint(cid, ctype=ConstraintType.PROPERTY, desc="desc", weight=1.0):- """Shortcut to build a Constraint with minimal boilerplate."""- return Constraint(- id=cid,- type=ctype,- description=desc,- value=cid,- weight=weight,- )---def _manager(**overrides):- """Build a CrossConstraintManager with __init__ bypassed."""- with patch.object(- CrossConstraintManager, "__init__", lambda self, *a, **kw: None- ):- mgr = CrossConstraintManager.__new__(CrossConstraintManager)- mgr.model = None- mgr.relationships = {}- mgr.clusters = []- mgr.cross_validation_patterns = {}- mgr.constraint_graph = {}- for key, val in overrides.items():- setattr(mgr, key, val)- return mgr---def _relationship(c1_id, c2_id, strength=0.8, rtype="complementary"):- return ConstraintRelationship(- constraint1_id=c1_id,- constraint2_id=c2_id,- relationship_type=rtype,- strength=strength,- )---# ===========================================================================-# ConstraintRelationship dataclass-# ===========================================================================---class TestConstraintRelationshipDataclass:- """Validate ConstraintRelationship field storage and defaults."""-- def test_all_relationship_types_stored(self):- """Arbitrary relationship_type strings are preserved."""- for rtype in (- "complementary",- "dependent",- "exclusive",- "none",- "custom",- ):- rel = _relationship("a", "b", rtype=rtype)- assert rel.relationship_type == rtype-- def test_negative_strength_stored(self):- """Dataclass does not clamp; negative strength is preserved."""- rel = _relationship("a", "b", strength=-0.5)- assert rel.strength == -0.5-- def test_evidence_mutation_does_not_leak(self):- """Appending to one instance's evidence does not affect another."""- rel1 = _relationship("a", "b")- rel2 = _relationship("c", "d")- rel1.evidence.append("item")- assert rel2.evidence == []---# ===========================================================================-# ConstraintCluster dataclass-# ===========================================================================---class TestConstraintClusterDataclass:- """Validate ConstraintCluster field storage and defaults."""-- def test_coherence_score_zero(self):- """Zero coherence is stored correctly."""- cluster = ConstraintCluster(- constraints=[],- cluster_type="t",- coherence_score=0.0,- )- assert cluster.coherence_score == 0.0-- def test_constraints_list_identity(self):- """The constraints list is the exact object passed in."""- items = [_constraint("c1")]- cluster = ConstraintCluster(- constraints=items,- cluster_type="t",- coherence_score=0.5,- )- assert cluster.constraints is items---# ===========================================================================-# _calculate_cluster_coherence-# ===========================================================================---class TestCalculateClusterCoherence:- """Test coherence formula: avg_strength * (0.7 + 0.3 * size_factor)."""-- def test_empty_list_returns_zero(self):- mgr = _manager()- assert mgr._calculate_cluster_coherence([]) == 0.0-- def test_single_constraint_returns_zero(self):- mgr = _manager()- assert mgr._calculate_cluster_coherence([_constraint("c1")]) == 0.0-- def test_two_constraints_no_relationship_returns_default(self):- """When no pair is found in relationships, return 0.5."""- mgr = _manager()- result = mgr._calculate_cluster_coherence(- [_constraint("c1"), _constraint("c2")]- )- assert result == 0.5-- def test_two_constraints_with_relationship_math(self):- """Verify exact formula for 2 constraints, 1 relationship."""- mgr = _manager(- relationships={- ("c1", "c2"): _relationship("c1", "c2", strength=0.9),- }- )- cons = [_constraint("c1"), _constraint("c2")]- # avg_strength = 0.9, size_factor = min(2/5, 1.0) = 0.4- # result = 0.9 * (0.7 + 0.3 * 0.4) = 0.9 * 0.82 = 0.738- result = mgr._calculate_cluster_coherence(cons)- assert result == pytest.approx(0.738)-- def test_three_constraints_partial_relationships(self):- """Only pairs present in relationships dict contribute."""- mgr = _manager(- relationships={- ("c1", "c2"): _relationship("c1", "c2", strength=0.6),- # ("c1", "c3") missing, ("c2", "c3") missing- }- )- cons = [_constraint("c1"), _constraint("c2"), _constraint("c3")]- # pair_count=1, avg_strength=0.6, size_factor=min(3/5,1)=0.6- # 0.6 * (0.7 + 0.3*0.6) = 0.6 * 0.88 = 0.528- result = mgr._calculate_cluster_coherence(cons)- assert result == pytest.approx(0.528)-- def test_five_constraints_size_factor_caps_at_one(self):- """size_factor = min(n/5, 1.0) caps at 1.0 for n>=5."""- rels = {}- ids = [f"c{i}" for i in range(5)]- # Add all 10 pairs with strength 1.0- import itertools-- for a, b in itertools.combinations(ids, 2):- rels[(a, b)] = _relationship(a, b, strength=1.0)- mgr = _manager(relationships=rels)- cons = [_constraint(cid) for cid in ids]- # avg=1.0, size_factor=1.0, result=1.0*(0.7+0.3*1.0)=1.0- assert mgr._calculate_cluster_coherence(cons) == pytest.approx(1.0)-- def test_six_constraints_size_factor_still_one(self):- """For n>5 the factor stays 1.0."""- rels = {}- ids = [f"c{i}" for i in range(6)]- import itertools-- for a, b in itertools.combinations(ids, 2):- rels[(a, b)] = _relationship(a, b, strength=0.5)- mgr = _manager(relationships=rels)- cons = [_constraint(cid) for cid in ids]- # avg=0.5, size_factor=min(6/5,1)=1.0, result=0.5*1.0=0.5- assert mgr._calculate_cluster_coherence(cons) == pytest.approx(0.5)-- def test_relationship_key_order_matters(self):- """Only (c1.id, c2.id) is checked, not (c2.id, c1.id)."""- mgr = _manager(- relationships={- ("c2", "c1"): _relationship("c2", "c1", strength=0.9),- }- )- cons = [_constraint("c1"), _constraint("c2")]- # itertools.combinations yields ("c1","c2") which is not in dict- # so pair_count=0 => returns default 0.5- assert mgr._calculate_cluster_coherence(cons) == 0.5---# ===========================================================================-# _deduplicate_clusters-# ===========================================================================---class TestDeduplicateClusters:- """Set-based deduplication logic."""-- def test_empty_returns_empty(self):- mgr = _manager()- assert mgr._deduplicate_clusters([]) == []-- def test_single_cluster_preserved(self):- mgr = _manager()- cluster = ConstraintCluster(- constraints=[_constraint("c1")],- cluster_type="t",- coherence_score=0.5,- )- result = mgr._deduplicate_clusters([cluster])- assert len(result) == 1- assert result[0] is cluster-- def test_same_ids_different_order_are_duplicates(self):- """Constraint sets {c1,c2} and {c2,c1} are the same."""- mgr = _manager()- ca, cb = _constraint("c1"), _constraint("c2")- cl1 = ConstraintCluster(- constraints=[ca, cb], cluster_type="a", coherence_score=0.5- )- cl2 = ConstraintCluster(- constraints=[cb, ca], cluster_type="b", coherence_score=0.9- )- result = mgr._deduplicate_clusters([cl1, cl2])- assert len(result) == 1-- def test_subset_is_not_duplicate(self):- """A strict subset is kept as a separate cluster."""- mgr = _manager()- ca, cb, cc = _constraint("c1"), _constraint("c2"), _constraint("c3")- cl1 = ConstraintCluster(- constraints=[ca, cb, cc], cluster_type="a", coherence_score=0.5- )- cl2 = ConstraintCluster(- constraints=[ca, cb], cluster_type="b", coherence_score=0.9- )- result = mgr._deduplicate_clusters([cl1, cl2])- assert len(result) == 2-- def test_three_duplicates_keeps_first(self):- """Out of three identical clusters, only the first survives."""- mgr = _manager()- con = _constraint("c1")- clusters = [- ConstraintCluster(- constraints=[con],- cluster_type=f"t{i}",- coherence_score=float(i),- )- for i in range(3)- ]- result = mgr._deduplicate_clusters(clusters)- assert len(result) == 1- assert result[0].cluster_type == "t0"---# ===========================================================================-# optimize_search_order-# ===========================================================================---class TestOptimizeSearchOrder:- """Sorting by coherence_score * len(constraints), descending."""-- def test_empty_list(self):- mgr = _manager()- assert mgr.optimize_search_order([]) == []-- def test_single_cluster(self):- mgr = _manager()- cluster = ConstraintCluster(- constraints=[_constraint("c1")],- cluster_type="t",- coherence_score=0.5,- )- assert mgr.optimize_search_order([cluster]) == [cluster]-- def test_ordering_prefers_higher_product(self):- mgr = _manager()- small_high = ConstraintCluster(- constraints=[_constraint("c1")],- cluster_type="a",- coherence_score=1.0, # product=1- )- big_low = ConstraintCluster(- constraints=[_constraint(f"c{i}") for i in range(4)],- cluster_type="b",- coherence_score=0.5, # product=2- )- result = mgr.optimize_search_order([small_high, big_low])- assert result[0] is big_low-- def test_equal_products_stable_order(self):- """Clusters with equal product keep their original relative order (stable sort)."""- mgr = _manager()- cl_a = ConstraintCluster(- constraints=[_constraint("c1"), _constraint("c2")],- cluster_type="a",- coherence_score=0.5, # product=1.0- )- cl_b = ConstraintCluster(- constraints=[_constraint("c3")],- cluster_type="b",- coherence_score=1.0, # product=1.0- )- result = mgr.optimize_search_order([cl_a, cl_b])- # Python sort is stable, so original order preserved for equal keys- assert result[0] is cl_a- assert result[1] is cl_b---# ===========================================================================-# _format_constraints_for_clustering-# ===========================================================================---class TestFormatConstraintsForClustering:- """String formatting: 'id: description (Type: type, Weight: weight)'."""-- def test_empty_list(self):- mgr = _manager()- assert mgr._format_constraints_for_clustering([]) == ""-- def test_single_constraint_format(self):- mgr = _manager()- con = _constraint(- "c1", ctype=ConstraintType.TEMPORAL, desc="In 2020", weight=0.9- )- result = mgr._format_constraints_for_clustering([con])- assert result == "c1: In 2020 (Type: temporal, Weight: 0.9)"-- def test_multiple_constraints_newline_separated(self):- mgr = _manager()- cons = [- _constraint("c1", desc="A"),- _constraint("c2", desc="B"),- ]- result = mgr._format_constraints_for_clustering(cons)- lines = result.split("\n")- assert len(lines) == 2- assert lines[0].startswith("c1:")- assert lines[1].startswith("c2:")---# ===========================================================================-# _format_constraints_for_query-# ===========================================================================---class TestFormatConstraintsForQuery:- """String formatting: '- description [type]'."""-- def test_empty_list(self):- mgr = _manager()- assert mgr._format_constraints_for_query([]) == ""-- def test_single_constraint_format(self):- mgr = _manager()- con = _constraint(- "c1", ctype=ConstraintType.LOCATION, desc="In Colorado"- )- result = mgr._format_constraints_for_query([con])- assert result == "- In Colorado [location]"-- def test_does_not_include_weight_or_id(self):- mgr = _manager()- con = _constraint("c99", desc="Test", weight=0.42)- result = mgr._format_constraints_for_query([con])- assert "c99" not in result- assert "0.42" not in result---# ===========================================================================-# _create_relationship_clusters (BFS connected components)-# ===========================================================================---class TestCreateRelationshipClusters:- """BFS connected-component logic with mocked relationships."""-- def test_no_relationships_no_clusters(self):- """No relationships means every node is isolated -> no multi-node clusters."""- mgr = _manager()- cons = [_constraint("c1"), _constraint("c2")]- result = mgr._create_relationship_clusters(cons, [])- assert result == []-- def test_single_edge_forms_one_cluster(self):- mgr = _manager()- cons = [_constraint("c1"), _constraint("c2"), _constraint("c3")]- rels = [_relationship("c1", "c2")]- result = mgr._create_relationship_clusters(cons, rels)- assert len(result) == 1- ids = {c.id for c in result[0].constraints}- assert ids == {"c1", "c2"}-- def test_chain_forms_single_component(self):- """c1-c2-c3 chain should yield one cluster of 3."""- mgr = _manager()- cons = [_constraint("c1"), _constraint("c2"), _constraint("c3")]- rels = [_relationship("c1", "c2"), _relationship("c2", "c3")]- result = mgr._create_relationship_clusters(cons, rels)- assert len(result) == 1- ids = {c.id for c in result[0].constraints}- assert ids == {"c1", "c2", "c3"}-- def test_two_disconnected_components(self):- """Two separate edges create two clusters."""- mgr = _manager()- cons = [_constraint(f"c{i}") for i in range(4)]- rels = [_relationship("c0", "c1"), _relationship("c2", "c3")]- result = mgr._create_relationship_clusters(cons, rels)- assert len(result) == 2- id_sets = [frozenset(c.id for c in cl.constraints) for cl in result]- assert frozenset({"c0", "c1"}) in id_sets- assert frozenset({"c2", "c3"}) in id_sets-- def test_cluster_type_is_relationship_based(self):- mgr = _manager()- cons = [_constraint("c1"), _constraint("c2")]- rels = [_relationship("c1", "c2")]- result = mgr._create_relationship_clusters(cons, rels)- assert result[0].cluster_type == "relationship_based"-- def test_constraint_not_in_list_ignored(self):- """A relationship referencing an unknown ID does not crash."""- mgr = _manager()- cons = [_constraint("c1"), _constraint("c2")]- # "c99" is not in cons- rels = [_relationship("c1", "c99"), _relationship("c1", "c2")]- result = mgr._create_relationship_clusters(cons, rels)- # c1 and c2 still form a cluster; c99 is silently skipped- assert len(result) == 1- ids = {c.id for c in result[0].constraints}- assert "c1" in ids- assert "c2" in idsdiff --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.pydeleted file mode 100644index cc9e70cb63..0000000000--- a/tests/advanced_search_system/search_optimization/test_cross_constraint_pure_logic.py+++ /dev/null@@ -1,196 +0,0 @@-"""-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) == 2diff --git a/tests/advanced_search_system/source_management/test_diversity_manager_behavior.py b/tests/advanced_search_system/source_management/test_diversity_manager_behavior.pydeleted file mode 100644index 7424f2ab37..0000000000--- a/tests/advanced_search_system/source_management/test_diversity_manager_behavior.py+++ /dev/null@@ -1,1287 +0,0 @@-"""-Behavioral tests for source_management/diversity_manager module.--Tests pure-logic methods: domain extraction, source type detection,-credibility calculation, temporal/geographic extraction, diversity metrics,-gap identification, source selection, and effectiveness tracking.-"""--from datetime import datetime-from unittest.mock import MagicMock--import pytest---def mock_model():- """Create a mock BaseChatModel."""- return MagicMock()---def manager(mock_model):- """Create a SourceDiversityManager instance."""- from local_deep_research.advanced_search_system.source_management.diversity_manager import (- SourceDiversityManager,- )-- return SourceDiversityManager(mock_model)---# =============================================================================-# SourceProfile Dataclass-# =============================================================================---class TestSourceProfile:- """Tests for SourceProfile dataclass."""-- def test_two_profiles_have_independent_specialty_lists(self):- """Mutable default factory must create separate lists per instance.-- A common Python dataclass bug: using `list` instead of- `field(default_factory=list)` shares one list across all instances.- """- from local_deep_research.advanced_search_system.source_management.diversity_manager import (- SourceProfile,- )-- p1 = SourceProfile(- url="u1", domain="d1", source_type="news", credibility_score=0.5- )- p2 = SourceProfile(- url="u2", domain="d2", source_type="news", credibility_score=0.5- )- p1.specialties.append("science")- assert "science" not in p2.specialties-- def test_credibility_score_not_clamped_on_construction(self):- """Float credibility must not be rounded or clamped at construction time.-- Clamping happens in calculate_credibility and track_effectiveness,- but the dataclass itself must store whatever value is passed.- """- from local_deep_research.advanced_search_system.source_management.diversity_manager import (- SourceProfile,- )-- p = SourceProfile(- url="u", domain="d", source_type="news", credibility_score=1.5- )- assert p.credibility_score == 1.5---# =============================================================================-# _extract_domain-# =============================================================================---class TestExtractDomain:- """Tests for _extract_domain() method.-- The regex is `r"https?://(?:www\\.)?([^/]+)"` — captures everything after- protocol+www up to the first `/`. This has known quirks with ports, auth- credentials, and query strings that these tests document.- """-- def test_strips_http_protocol(self, manager):- assert (- manager._extract_domain("http://example.com/page") == "example.com"- )-- def test_strips_https_protocol(self, manager):- assert (- manager._extract_domain("https://example.com/page") == "example.com"- )-- def test_strips_single_www_prefix(self, manager):- assert (- manager._extract_domain("https://www.example.com/page")- == "example.com"- )-- def test_double_www_only_strips_one(self, manager):- """The non-capturing group `(?:www\\.)?` matches at most one `www.`."""- assert (- manager._extract_domain("https://www.www.example.com/page")- == "www.example.com"- )-- def test_port_number_included_in_domain(self, manager):- """[^/]+ captures port as part of domain since `:` is not `/`."""- result = manager._extract_domain("https://example.com:8080/path")- assert result == "example.com:8080"-- def test_auth_credentials_captured_in_domain(self, manager):- """user:pass@ is captured because [^/]+ matches `@` and `:`."""- result = manager._extract_domain("https://user:[email protected]/path")- assert "user:pass@" in result-- def test_query_params_without_path_included(self, manager):- """URL with no `/` after domain: query string becomes part of domain."""- result = manager._extract_domain("https://example.com?q=test")- assert result == "example.com?q=test"-- def test_ftp_protocol_not_matched(self, manager):- """Only http/https match; ftp falls through to raw URL return."""- assert (- manager._extract_domain("ftp://files.example.com")- == "ftp://files.example.com"- )-- def test_non_www_subdomain_preserved(self, manager):- assert (- manager._extract_domain("https://blog.example.com/post")- == "blog.example.com"- )---# =============================================================================-# _determine_source_type-# =============================================================================---class TestDetermineSourceType:- """Tests for _determine_source_type() method."""-- def test_edu_domain_is_academic(self, manager):- assert (- manager._determine_source_type(- "https://stanford.edu", "stanford.edu", None- )- == "academic"- )-- def test_ac_domain_is_academic(self, manager):- assert (- manager._determine_source_type(- "https://oxford.ac.uk", "oxford.ac.uk", None- )- == "academic"- )-- def test_scholar_is_academic(self, manager):- assert (- manager._determine_source_type(- "https://scholar.google.com", "scholar.google.com", None- )- == "academic"- )-- def test_arxiv_is_academic(self, manager):- assert (- manager._determine_source_type(- "https://arxiv.org/abs/123", "arxiv.org", None- )- == "academic"- )-- def test_pubmed_is_academic(self, manager):- assert (- manager._determine_source_type(- "https://pubmed.ncbi.nlm.nih.gov",- "pubmed.ncbi.nlm.nih.gov",- None,- )- == "academic"- )-- def test_gov_domain_is_government(self, manager):- assert (- manager._determine_source_type("https://cdc.gov", "cdc.gov", None)- == "government"- )-- def test_mil_domain_is_government(self, manager):- assert (- manager._determine_source_type("https://army.mil", "army.mil", None)- == "government"- )-- def test_wikipedia_is_wiki(self, manager):- assert (- manager._determine_source_type(- "https://en.wikipedia.org", "en.wikipedia.org", None- )- == "wiki"- )-- def test_bbc_is_news(self, manager):- assert (- manager._determine_source_type(- "https://bbc.co.uk", "bbc.co.uk", None- )- == "news"- )-- def test_reuters_is_news(self, manager):- assert (- manager._determine_source_type(- "https://reuters.com", "reuters.com", None- )- == "news"- )-- def test_cnn_is_news(self, manager):- assert (- manager._determine_source_type("https://cnn.com", "cnn.com", None)- == "news"- )-- def test_unknown_domain_no_content_is_general(self, manager):- assert (- manager._determine_source_type(- "https://random-site.xyz", "random-site.xyz", None- )- == "general"- )-- def test_academic_in_url_not_domain(self, manager):- """Academic pattern in URL path should also match."""- result = manager._determine_source_type(- "https://example.com/scholar/paper", "example.com", None- )- assert result == "academic"-- def test_case_insensitive(self, manager):- assert (- manager._determine_source_type(- "https://Stanford.EDU/page", "Stanford.EDU", None- )- == "academic"- )-- def test_academic_takes_priority_over_government(self, manager):- """A .gov domain containing 'scholar' should be academic, not government.-- Academic patterns are checked first in the source code, so this verifies- the ordering matters for domains that match multiple categories.- """- assert (- manager._determine_source_type(- "https://scholar.gov.example.com",- "scholar.gov.example.com",- None,- )- == "academic"- )-- def test_government_only_checks_domain_not_url_path(self, manager):- """Government patterns only check `lower_domain`, not `lower_url`.-- A URL with `.gov` in the path but not domain should NOT be government.- This is different from academic which checks both domain AND url.- """- result = manager._determine_source_type(- "https://example.com/.gov/policy", "example.com", None- )- assert result != "government"-- def test_wiki_takes_priority_over_news(self, manager):- """'wikinews.org' contains both 'wiki' and 'news'; wiki checked first."""- assert (- manager._determine_source_type(- "https://wikinews.org", "wikinews.org", None- )- == "wiki"- )-- def test_content_fallback_invokes_model(self, manager, mock_model):- """When domain doesn't match any pattern, content triggers LLM call."""- mock_model.invoke.return_value = MagicMock(content="blog")- result = manager._determine_source_type(- "https://random-site.xyz", "random-site.xyz", "Some blog content"- )- assert result == "blog"- mock_model.invoke.assert_called_once()-- def test_content_fallback_unknown_response_becomes_general(- self, manager, mock_model- ):- """If LLM returns a type not in type_priorities, falls back to general."""- mock_model.invoke.return_value = MagicMock(content="podcast")- result = manager._determine_source_type(- "https://random.xyz", "random.xyz", "Some podcast transcript"- )- assert result == "general"---# =============================================================================-# _calculate_credibility-# =============================================================================---class TestCalculateCredibility:- """Tests for _calculate_credibility() method."""-- def test_academic_base_score(self, manager):- score = manager._calculate_credibility(- "http://example.com", "example.com", "academic", None- )- assert score == pytest.approx(0.9, abs=0.01)-- def test_government_base_score(self, manager):- score = manager._calculate_credibility(- "http://example.com", "example.com", "government", None- )- assert score == pytest.approx(0.85, abs=0.01)-- def test_blog_base_score(self, manager):- score = manager._calculate_credibility(- "http://example.com", "example.com", "blog", None- )- assert score == pytest.approx(0.5, abs=0.01)-- def test_unknown_type_gets_default(self, manager):- score = manager._calculate_credibility(- "http://example.com", "example.com", "unknown_type", None- )- assert score == pytest.approx(0.5, abs=0.01)-- def test_edu_domain_bonus(self, manager):- without_edu = manager._calculate_credibility(- "http://example.com", "example.com", "general", None- )- with_edu = manager._calculate_credibility(- "http://example.edu", "example.edu", "general", None- )- assert with_edu > without_edu-- def test_gov_domain_bonus(self, manager):- without_gov = manager._calculate_credibility(- "http://example.com", "example.com", "general", None- )- with_gov = manager._calculate_credibility(- "http://example.gov", "example.gov", "general", None- )- assert with_gov > without_gov-- def test_https_bonus(self, manager):- http_score = manager._calculate_credibility(- "http://example.com", "example.com", "general", None- )- https_score = manager._calculate_credibility(- "https://example.com", "example.com", "general", None- )- assert https_score > http_score-- def test_citations_in_content_bonus(self, manager):- without = manager._calculate_credibility(- "http://example.com", "example.com", "general", "plain text"- )- with_cit = manager._calculate_credibility(- "http://example.com",- "example.com",- "general",- "According to [1] the result (2024) is clear",- )- assert with_cit > without-- def test_author_in_content_bonus(self, manager):- without = manager._calculate_credibility(- "http://example.com", "example.com", "general", "plain text"- )- with_author = manager._calculate_credibility(- "http://example.com",- "example.com",- "general",- "By John Smith this paper",- )- assert with_author > without-- def test_score_capped_at_one(self, manager):- """Score should never exceed 1.0 even with all bonuses."""- score = manager._calculate_credibility(- "https://harvard.edu",- "harvard.edu",- "academic",- "By John Smith [1] reference (2024) Author: Jane Doe",- )- assert score <= 1.0-- def test_score_between_zero_and_one(self, manager):- score = manager._calculate_credibility(- "http://random.xyz", "random.xyz", "forum", None- )- assert 0.0 <= score <= 1.0---# =============================================================================-# _extract_temporal_coverage-# =============================================================================---class TestExtractTemporalCoverage:- """Tests for _extract_temporal_coverage() method.-- Regex is `r"\\b(19\\d{2}|20\\d{2})\\b"` — matches years 1900-2099 only,- with word boundaries to prevent matching inside larger numbers.- """-- def test_none_content_returns_none(self, manager):- assert manager._extract_temporal_coverage(None) is None-- def test_empty_string_returns_none(self, manager):- """Empty string (not None) still has no years."""- assert manager._extract_temporal_coverage("") is None-- def test_no_years_returns_none(self, manager):- assert manager._extract_temporal_coverage("no year data here") is None-- def test_single_year_gives_same_start_and_end(self, manager):- result = manager._extract_temporal_coverage("Data from 2020 shows")- assert result is not None- start, end = result- assert start.year == 2020- assert end.year == 2020-- def test_start_is_january_first(self, manager):- """Min year maps to January 1 of that year."""- result = manager._extract_temporal_coverage("In 2020")- start, _ = result- assert start.month == 1- assert start.day == 1-- def test_end_is_december_31(self, manager):- """Max year maps to December 31 of that year."""- result = manager._extract_temporal_coverage("In 2020")- _, end = result- assert end.month == 12- assert end.day == 31-- def test_year_embedded_in_word_not_matched(self, manager):- """Word boundary \\b prevents matching 2020 inside 'model2020v'."""- result = manager._extract_temporal_coverage("model2020version is out")- assert result is None-- def test_year_1899_outside_regex_range(self, manager):- """Regex only matches 19xx and 20xx, so 1899 is invisible."""- result = manager._extract_temporal_coverage("Founded in 1899")- assert result is None-- def test_year_2100_outside_regex_range(self, manager):- """Regex stops at 2099, so 2100 is invisible."""- result = manager._extract_temporal_coverage("By 2100 the world")- assert result is None-- def test_boundary_year_1900_matched(self, manager):- result = manager._extract_temporal_coverage("Since 1900 data exists")- assert result is not None- assert result[0].year == 1900-- def test_boundary_year_2099_matched(self, manager):- result = manager._extract_temporal_coverage("Projections for 2099")- assert result is not None- assert result[1].year == 2099-- def test_multiple_years_uses_min_and_max(self, manager):- result = manager._extract_temporal_coverage(- "Between 1990 and 2020 the climate changed"- )- start, end = result- assert start.year == 1990- assert end.year == 2020-- def test_year_after_colon_matched(self, manager):- """Colon is non-word char, so \\b fires between `:` and digit."""- result = manager._extract_temporal_coverage("year:2020 data")- assert result is not None- assert result[0].year == 2020---# =============================================================================-# _extract_geographic_focus-# =============================================================================---class TestExtractGeographicFocus:- """Tests for _extract_geographic_focus() method.-- URL check uses `f".{pattern}" in url` and `f"/{pattern}/" in url` — simple- substring matching that can produce false positives with longer TLDs.- Content check uses a regex with explicit location names.- """-- def test_uk_tld_in_url(self, manager):- result = manager._extract_geographic_focus(- "https://example.uk/page", None- )- assert result == "United Kingdom"-- def test_ca_tld_in_url(self, manager):- result = manager._extract_geographic_focus(- "https://example.ca/page", None- )- assert result == "Canada"-- def test_geo_path_segment_matched(self, manager):- """Pattern checks `/{code}/` in URL path, not just TLD."""- result = manager._extract_geographic_focus(- "https://example.com/eu/policy", None- )- assert result == "Europe"-- def test_false_positive_ca_substring_in_longer_tld(self, manager):- """`.ca` is a substring of `.caucasus.org`, triggering a false match.-- This documents a known limitation: the check is `f'.ca' in url`, not- a proper TLD parse, so any URL containing `.ca` anywhere matches.- """- result = manager._extract_geographic_focus(- "https://example.caucasus.org/data", None- )- assert result == "Canada" # False positive — documents current behavior-- def test_url_match_takes_priority_over_content(self, manager):- """URL geo is checked first; if it matches, content is never examined."""- result = manager._extract_geographic_focus(- "https://example.uk/page",- "United States mentioned many times. United States again.",- )- assert result == "United Kingdom"-- def test_no_geo_in_url_or_content_returns_none(self, manager):- result = manager._extract_geographic_focus(- "https://example.com/page", None- )- assert result is None-- def test_content_detects_asia_and_africa(self, manager):- """The content regex includes Asia and Africa, not just Western countries."""- for region in ["Asia", "Africa"]:- result = manager._extract_geographic_focus(- "https://example.com",- f"{region} is experiencing growth. {region} leads.",- )- assert result == region-- def test_content_case_insensitive(self, manager):- """re.IGNORECASE flag means 'UNITED STATES' matches."""- result = manager._extract_geographic_focus(- "https://example.com", "UNITED STATES policy is changing"- )- assert result is not None-- def test_most_frequent_content_location_wins(self, manager):- content = (- "Canada is great. Canada has lakes. Canada is cold. UK has rain."- )- result = manager._extract_geographic_focus(- "https://example.com", content- )- assert result == "Canada"-- def test_content_only_first_1000_chars_checked(self, manager):- """Content is sliced to [:1000], so locations past that are invisible."""- padding = "x" * 1000- content = padding + "United States mentioned here"- result = manager._extract_geographic_focus(- "https://example.com", content- )- assert result is None---# =============================================================================-# _calculate_temporal_diversity-# =============================================================================---class TestCalculateTemporalDiversity:- """Tests for _calculate_temporal_diversity() method."""-- def test_empty_ranges_returns_zero(self, manager):- assert manager._calculate_temporal_diversity([]) == 0.0-- def test_single_year_returns_zero(self, manager):- ranges = [(datetime(2020, 1, 1), datetime(2020, 12, 31))]- assert manager._calculate_temporal_diversity(ranges) == 0.0-- def test_two_year_span(self, manager):- ranges = [- (datetime(2018, 1, 1), datetime(2018, 12, 31)),- (datetime(2020, 1, 1), datetime(2020, 12, 31)),- ]- result = manager._calculate_temporal_diversity(ranges)- # Span = 2 years, normalized by 20 = 0.1- assert result == pytest.approx(0.1)-- def test_twenty_year_span_is_max(self, manager):- ranges = [- (datetime(2000, 1, 1), datetime(2000, 12, 31)),- (datetime(2020, 1, 1), datetime(2020, 12, 31)),- ]- result = manager._calculate_temporal_diversity(ranges)- assert result == pytest.approx(1.0)-- def test_over_twenty_years_capped_at_one(self, manager):- ranges = [- (datetime(1950, 1, 1), datetime(1950, 12, 31)),- (datetime(2020, 1, 1), datetime(2020, 12, 31)),- ]- result = manager._calculate_temporal_diversity(ranges)- assert result == 1.0-- def test_overlapping_ranges(self, manager):- ranges = [- (datetime(2010, 1, 1), datetime(2015, 12, 31)),- (datetime(2013, 1, 1), datetime(2020, 12, 31)),- ]- result = manager._calculate_temporal_diversity(ranges)- # Span = 10 years, normalized by 20 = 0.5- assert result == pytest.approx(0.5)---# =============================================================================-# _get_source_type_modifier-# =============================================================================---class TestGetSourceTypeModifier:- """Tests for _get_source_type_modifier() method.-- Tests focus on coverage gaps and how the modifier interacts with- recommend_additional_sources, not individual dict values.- """-- def test_forum_and_social_have_no_modifier(self, manager):- """Forum and social are in type_priorities but have no search modifier.-- This means if gap identification recommends adding forum/social sources,- the query_modifier in the recommendation will be empty string.- """- assert manager._get_source_type_modifier("forum") == ""- assert manager._get_source_type_modifier("social") == ""-- def test_all_desired_types_have_nonempty_modifiers(self, manager):- """The 4 'desired' types used in gap identification all have modifiers."""- desired = {"academic", "government", "news", "wiki"}- for source_type in desired:- assert manager._get_source_type_modifier(source_type) != "", (- f"{source_type} has no modifier but is a desired type for gap filling"- )-- def test_modifiers_are_valid_search_syntax(self, manager):- """Each modifier should contain site: or quoted terms for search engines."""- for source_type in ["academic", "government", "wiki"]:- modifier = manager._get_source_type_modifier(source_type)- assert "site:" in modifier or "OR" in modifier---# =============================================================================-# _get_region_domain-# =============================================================================---class TestGetRegionDomain:- """Tests for _get_region_domain() method."""-- def test_content_detected_regions_have_matching_domains(self, manager):- """Every region detectable in content regex should have a domain mapping.-- The content regex detects: United States, UK, Canada, Australia, Europe,- Asia, Africa, Americas. The domain map should cover the major ones.- """- content_regions = [- "United States",- "United Kingdom",- "Canada",- "Australia",- "Europe",- ]- for region in content_regions:- domain = manager._get_region_domain(region)- assert domain != ".com", (- f"Region '{region}' falls through to default .com"- )-- def test_unknown_region_defaults_to_com(self, manager):- """Regions not in the mapping (e.g. Asia, Africa) get .com fallback."""- assert manager._get_region_domain("Asia") == ".com"- assert manager._get_region_domain("Antarctica") == ".com"-- def test_europe_includes_multiple_country_tlds(self, manager):- """Europe maps to multiple TLDs since it's not a single country."""- result = manager._get_region_domain("Europe")- assert ".eu" in result- # Should include at least one specific country- assert ".de" in result or ".fr" in result---# =============================================================================-# _extract_specialties (URL-only, no content)-# =============================================================================---class TestExtractSpecialties:- """Tests for _extract_specialties() method (URL-only path).-- Regex is `r"/([a-z]+)/"` — matches lowercase-only path segments enclosed- by slashes. Non-overlapping: after matching `/science/`, the trailing `/`- is consumed, so the next segment needs its own leading `/`.- """-- def test_non_overlapping_regex_skips_alternating_segments(self, manager):- """After matching `/science/`, the trailing `/` is consumed.-- So `biology` has no leading `/` and is skipped. `research` has- a leading `/` from `biology/` and matches.- """- result = manager._extract_specialties(- "https://example.com/science/biology/research/paper", None- )- assert "science" in result- assert "research" in result- # biology is between two consumed slashes — documenting this quirk- assert "biology" not in result-- def test_exactly_three_char_keyword_filtered_out(self, manager):- """Filter is `len(kw) > 3`, so exactly 3 chars like 'web' are excluded.-- URL uses extra segment to work around non-overlapping regex:- after `/web/` consumes its trailing `/`, `xx` acts as spacer so- `/wiki/` still has a leading `/` to match.- """- result = manager._extract_specialties(- "https://example.com/web/xx/wiki/", None- )- assert "web" not in result- assert "wiki" in result-- def test_four_char_keyword_passes_filter(self, manager):- result = manager._extract_specialties(- "https://example.com/data/xx/docs/", None- )- assert "data" in result-- def test_uppercase_url_lowered_before_regex(self, manager):- """URL is `.lower()`'d before regex, so uppercase paths still match."""- result = manager._extract_specialties(- "https://example.com/SCIENCE/BIOLOGY/", None- )- assert "science" in result-- def test_hyphenated_segment_captures_partial_match(self, manager):- """Regex `[a-z]+` stops at hyphens, so 'data-science' yields 'data'."""- result = manager._extract_specialties(- "https://example.com/data-science/other/", None- )- # 'data' is captured (4 chars, passes filter), 'science' is after hyphen- assert "data" not in result or "data" in result # depends on regex- # The key point: 'data-science' is NOT captured as one keyword- assert "data-science" not in result-- def test_last_segment_without_trailing_slash_not_captured(self, manager):- """Regex requires trailing `/`, so final path segment is invisible."""- result = manager._extract_specialties(- "https://example.com/only_segment", None- )- assert result == []-- def test_url_keywords_limited_to_three(self, manager):- """[:3] limit on URL keywords before content-based extraction."""- result = manager._extract_specialties(- "https://example.com/alpha/x/bravo/x/charlie/x/delta/x/echo/x/",- None,- )- # At most 3 from URL (final limit is 5 after dedup with content)- assert len(result) <= 5-- def test_no_path_returns_empty(self, manager):- result = manager._extract_specialties("https://example.com", None)- assert result == []---# =============================================================================-# analyze_source (with mock model)-# =============================================================================---class TestAnalyzeSource:- """Tests for analyze_source() method."""-- def test_creates_profile_for_new_url(self, manager):- from local_deep_research.advanced_search_system.source_management.diversity_manager import (- SourceProfile,- )-- profile = manager.analyze_source("https://example.com/page")- assert isinstance(profile, SourceProfile)- assert profile.url == "https://example.com/page"-- def test_caches_profile(self, manager):- manager.analyze_source("https://example.com")- assert "https://example.com" in manager.source_profiles-- def test_returns_cached_profile_on_repeat(self, manager):- p1 = manager.analyze_source("https://example.com")- p2 = manager.analyze_source("https://example.com")- assert p1 is p2-- def test_increments_evidence_count_on_repeat(self, manager):- manager.analyze_source("https://example.com")- manager.analyze_source("https://example.com")- assert (- manager.source_profiles["https://example.com"].evidence_count == 2- )-- def test_sets_evidence_count_to_one_initially(self, manager):- profile = manager.analyze_source("https://example.com")- assert profile.evidence_count == 1-- def test_tracks_source_type(self, manager):- manager.analyze_source("https://stanford.edu/paper")- assert "https://stanford.edu/paper" in manager.source_types["academic"]-- def test_edu_url_detected_as_academic(self, manager):- profile = manager.analyze_source("https://mit.edu/research")- assert profile.source_type == "academic"-- def test_gov_url_detected_as_government(self, manager):- profile = manager.analyze_source("https://cdc.gov/data")- assert profile.source_type == "government"---# =============================================================================-# calculate_diversity_metrics-# =============================================================================---class TestCalculateDiversityMetrics:- """Tests for calculate_diversity_metrics() method."""-- def test_empty_sources_returns_zeros(self, manager):- metrics = manager.calculate_diversity_metrics([])- assert metrics.type_diversity == 0.0- assert metrics.temporal_diversity == 0.0- assert metrics.geographic_diversity == 0.0- assert metrics.overall_score == 0.0- assert metrics.credibility_distribution == {}- assert metrics.specialty_coverage == {}-- def test_single_source_type_diversity(self, manager):- manager.analyze_source("https://example.com")- metrics = manager.calculate_diversity_metrics(["https://example.com"])- # 1 unique type / 3 minimum = 0.333- assert metrics.type_diversity == pytest.approx(1 / 3, abs=0.01)-- def test_three_source_types_max_diversity(self, manager):- manager.analyze_source("https://stanford.edu") # academic- manager.analyze_source("https://cdc.gov") # government- manager.analyze_source("https://bbc.co.uk") # news- metrics = manager.calculate_diversity_metrics(- ["https://stanford.edu", "https://cdc.gov", "https://bbc.co.uk"]- )- assert metrics.type_diversity == pytest.approx(1.0)-- def test_credibility_distribution_populated(self, manager):- manager.analyze_source("https://stanford.edu")- metrics = manager.calculate_diversity_metrics(["https://stanford.edu"])- assert len(metrics.credibility_distribution) > 0-- def test_overall_score_between_zero_and_one(self, manager):- manager.analyze_source("https://example.com")- metrics = manager.calculate_diversity_metrics(["https://example.com"])- assert 0.0 <= metrics.overall_score <= 1.0---# =============================================================================-# _identify_diversity_gaps-# =============================================================================---class TestIdentifyDiversityGaps:- """Tests for _identify_diversity_gaps() method."""-- def test_low_type_diversity_reports_missing_types(self, manager):- from local_deep_research.advanced_search_system.source_management.diversity_manager import (- DiversityMetrics,- SourceProfile,- )-- # Only have news sources- manager.source_profiles["url1"] = SourceProfile(- url="url1", domain="d", source_type="news", credibility_score=0.7- )- metrics = DiversityMetrics(- type_diversity=0.3,- temporal_diversity=0.5,- geographic_diversity=0.5,- credibility_distribution={"medium": 1},- specialty_coverage={},- overall_score=0.4,- )- gaps = manager._identify_diversity_gaps(metrics, [])- assert "source_type" in gaps- assert isinstance(gaps["source_type"], list)-- def test_low_credibility_reports_gap(self, manager):- from local_deep_research.advanced_search_system.source_management.diversity_manager import (- DiversityMetrics,- )-- metrics = DiversityMetrics(- type_diversity=0.8,- temporal_diversity=0.5,- geographic_diversity=0.5,- credibility_distribution={"low": 10, "high": 0},- specialty_coverage={},- overall_score=0.3,- )- gaps = manager._identify_diversity_gaps(metrics, [])- assert "credibility" in gaps-- def test_good_metrics_no_gaps(self, manager):- from local_deep_research.advanced_search_system.source_management.diversity_manager import (- DiversityMetrics,- SourceProfile,- )-- # Register all desired source types- for stype in ["academic", "government", "news", "wiki"]:- manager.source_profiles[stype] = SourceProfile(- url=stype, domain="d", source_type=stype, credibility_score=0.9- )- metrics = DiversityMetrics(- type_diversity=1.0,- temporal_diversity=0.8,- geographic_diversity=0.8,- credibility_distribution={"high": 10},- specialty_coverage={},- overall_score=0.9,- )- gaps = manager._identify_diversity_gaps(metrics, [])- assert "source_type" not in gaps- assert "credibility" not in gaps-- def test_temporal_gap_with_temporal_constraints(self, manager):- from local_deep_research.advanced_search_system.constraints.base_constraint import (- Constraint,- ConstraintType,- )- from local_deep_research.advanced_search_system.source_management.diversity_manager import (- DiversityMetrics,- )-- metrics = DiversityMetrics(- type_diversity=0.8,- temporal_diversity=0.3,- geographic_diversity=0.5,- credibility_distribution={"high": 5},- specialty_coverage={},- overall_score=0.5,- )- constraints = [- Constraint(- id="c1",- type=ConstraintType.TEMPORAL,- description="After 2010",- value="2010",- )- ]- gaps = manager._identify_diversity_gaps(metrics, constraints)- assert "temporal" in gaps-- def test_geographic_gap_with_location_constraints(self, manager):- from local_deep_research.advanced_search_system.constraints.base_constraint import (- Constraint,- ConstraintType,- )- from local_deep_research.advanced_search_system.source_management.diversity_manager import (- DiversityMetrics,- )-- metrics = DiversityMetrics(- type_diversity=0.8,- temporal_diversity=0.5,- geographic_diversity=0.3,- credibility_distribution={"high": 5},- specialty_coverage={},- overall_score=0.5,- )- constraints = [- Constraint(- id="c1",- type=ConstraintType.LOCATION,- description="In Colorado",- value="Colorado",- )- ]- gaps = manager._identify_diversity_gaps(metrics, constraints)- assert "geographic" in gaps---# =============================================================================-# select_diverse_sources-# =============================================================================---class TestSelectDiverseSources:- """Tests for select_diverse_sources() method."""-- def test_returns_all_when_fewer_than_target(self, manager):- sources = ["http://a.com", "http://b.com"]- result = manager.select_diverse_sources(sources, target_count=5)- assert result == sources-- def test_returns_all_when_equal_to_target(self, manager):- sources = ["http://a.com", "http://b.com"]- result = manager.select_diverse_sources(sources, target_count=2)- assert result == sources-- def test_selects_subset_when_more_than_target(self, manager):- # Pre-analyze sources- for url in [- "https://stanford.edu",- "https://cdc.gov",- "https://bbc.co.uk",- "https://blog.example.com",- "https://forum.example.com",- ]:- manager.analyze_source(url)- sources = [- "https://stanford.edu",- "https://cdc.gov",- "https://bbc.co.uk",- "https://blog.example.com",- "https://forum.example.com",- ]- result = manager.select_diverse_sources(sources, target_count=3)- assert len(result) == 3-- def test_prefers_diverse_types(self, manager):- # Pre-analyze: 2 academic + 1 news + 1 gov- manager.analyze_source("https://mit.edu")- manager.analyze_source("https://stanford.edu")- manager.analyze_source("https://bbc.co.uk")- manager.analyze_source("https://nasa.gov")-- sources = [- "https://mit.edu",- "https://stanford.edu",- "https://bbc.co.uk",- "https://nasa.gov",- ]- result = manager.select_diverse_sources(sources, target_count=3)- # Should include diverse types, not just top 3 by score- result_types = {- manager.source_profiles[url].source_type for url in result- }- assert len(result_types) >= 2---# =============================================================================-# track_source_effectiveness-# =============================================================================---class TestTrackSourceEffectiveness:- """Tests for track_source_effectiveness() method."""-- def test_unknown_source_does_nothing(self, manager):- # Should not raise- manager.track_source_effectiveness("http://unknown.com", 0.8, True)-- def test_boosts_credibility_when_satisfied(self, manager):- manager.analyze_source("https://example.com")- original = manager.source_profiles[- "https://example.com"- ].credibility_score- manager.track_source_effectiveness("https://example.com", 0.8, True)- new = manager.source_profiles["https://example.com"].credibility_score- assert new > original-- def test_credibility_capped_at_one(self, manager):- from local_deep_research.advanced_search_system.source_management.diversity_manager import (- SourceProfile,- )-- manager.source_profiles["url"] = SourceProfile(- url="url",- domain="d",- source_type="academic",- credibility_score=0.99,- )- manager.track_source_effectiveness("url", 0.9, True)- assert manager.source_profiles["url"].credibility_score <= 1.0-- def test_no_boost_when_not_satisfied(self, manager):- manager.analyze_source("https://example.com")- original = manager.source_profiles[- "https://example.com"- ].credibility_score- manager.track_source_effectiveness("https://example.com", 0.8, False)- new = manager.source_profiles["https://example.com"].credibility_score- assert new == original---# =============================================================================-# recommend_additional_sources-# =============================================================================---class TestRecommendAdditionalSources:- """Tests for recommend_additional_sources() method."""-- def test_single_low_cred_source_triggers_type_and_credibility_recs(- self, manager- ):- """A single blog source should trigger both source_type and credibility gaps."""- from local_deep_research.advanced_search_system.source_management.diversity_manager import (- SourceProfile,- )-- manager.source_profiles["url1"] = SourceProfile(- url="url1", domain="d", source_type="blog", credibility_score=0.3- )- manager.source_types["blog"].add("url1")-- recs = manager.recommend_additional_sources(["url1"], [])- assert len(recs) > 0 # Must actually produce recommendations- rec_types = {r["type"] for r in recs}- assert "source_type" in rec_types- assert "credibility" in rec_types-- def test_recommendations_have_nonempty_query_modifiers_for_known_types(- self, manager- ):- """Each recommendation should have a usable query_modifier, not empty string."""- from local_deep_research.advanced_search_system.source_management.diversity_manager import (- SourceProfile,- )-- manager.source_profiles["url1"] = SourceProfile(- url="url1", domain="d", source_type="news", credibility_score=0.7- )- manager.source_types["news"].add("url1")-- recs = manager.recommend_additional_sources(["url1"], [])- for rec in recs:- assert "reason" in rec- assert "query_modifier" in rec- # source_type recs for desired types should have nonempty modifiers- if rec["type"] == "source_type" and rec["target"] in (- "academic",- "government",- "wiki",- ):- assert rec["query_modifier"] != ""-- def test_limits_to_five_recommendations(self, manager):- """Even with many gaps, output is capped at 5 recommendations."""- from local_deep_research.advanced_search_system.source_management.diversity_manager import (- SourceProfile,- )- from local_deep_research.advanced_search_system.constraints.base_constraint import (- Constraint,- ConstraintType,- )-- manager.source_profiles["url1"] = SourceProfile(- url="url1", domain="d", source_type="blog", credibility_score=0.1- )- manager.source_types["blog"].add("url1")-- # Add constraints to trigger temporal and geographic gaps too- constraints = [- Constraint(- id="t1",- type=ConstraintType.TEMPORAL,- description="d",- value="2010",- ),- Constraint(- id="l1",- type=ConstraintType.LOCATION,- description="d",- value="United States",- ),- Constraint(- id="l2",- type=ConstraintType.LOCATION,- description="d",- value="Canada",- ),- Constraint(- id="l3",- type=ConstraintType.LOCATION,- description="d",- value="Australia",- ),- ]- recs = manager.recommend_additional_sources(["url1"], constraints)- assert len(recs) <= 5-- def test_geographic_recs_use_region_domain(self, manager):- """Geographic recommendations should use _get_region_domain for the query."""- from local_deep_research.advanced_search_system.source_management.diversity_manager import (- SourceProfile,- )- from local_deep_research.advanced_search_system.constraints.base_constraint import (- Constraint,- ConstraintType,- )-- manager.source_profiles["url1"] = SourceProfile(- url="url1",- domain="d",- source_type="academic",- credibility_score=0.9,- )- manager.source_types["academic"].add("url1")-- constraints = [- Constraint(- id="l1",- type=ConstraintType.LOCATION,- description="d",- value="United Kingdom",- ),- ]- recs = manager.recommend_additional_sources(["url1"], constraints)- geo_recs = [r for r in recs if r["type"] == "geographic"]- if geo_recs:- assert ".uk" in geo_recs[0]["query_modifier"]---# =============================================================================-# Manager initialization-# =============================================================================---class TestManagerInit:- """Tests for SourceDiversityManager initialization."""-- def test_all_priorities_between_zero_and_one(self, manager):- """Priority values represent credibility weights, must be valid scores."""- for source_type, priority in manager.type_priorities.items():- assert 0.0 <= priority <= 1.0, (- f"{source_type} has invalid priority {priority}"- )-- def test_priority_ordering_matches_credibility_hierarchy(self, manager):- """Academic/government should outrank news/wiki which outranks blog/forum/social."""- p = manager.type_priorities- assert p["academic"] > p["news"]- assert p["government"] > p["news"]- assert p["news"] > p["blog"]- assert p["blog"] > p["forum"]- assert p["forum"] > p["social"]-- def test_source_types_is_defaultdict(self, manager):- """source_types must be defaultdict so accessing unknown keys doesn't raise."""- # This is critical: analyze_source does `self.source_types[source_type].add(url)`- # without checking if the key exists first- unknown_set = manager.source_types["never_seen_before"]- assert isinstance(unknown_set, set)- assert len(unknown_set) == 0-- def test_two_managers_have_independent_state(self, mock_model):- """Each manager instance must have its own source_profiles dict."""- from local_deep_research.advanced_search_system.source_management.diversity_manager import (- SourceDiversityManager,- )-- m1 = SourceDiversityManager(mock_model)- m2 = SourceDiversityManager(mock_model)- m1.analyze_source("https://example.com")- assert "https://example.com" not in m2.source_profilesdiff --git a/tests/advanced_search_system/source_management/test_diversity_manager_edge_cases.py b/tests/advanced_search_system/source_management/test_diversity_manager_edge_cases.pydeleted file mode 100644index 42dc785942..0000000000--- a/tests/advanced_search_system/source_management/test_diversity_manager_edge_cases.py+++ /dev/null@@ -1,324 +0,0 @@-"""High-value edge case tests for source_management/diversity_manager.py.--Tests pure logic methods (no LLM calls) covering domain extraction,-source type classification, credibility scoring, temporal/geographic-extraction, and diversity metrics calculation.-"""--from unittest.mock import MagicMock--from local_deep_research.advanced_search_system.source_management.diversity_manager import (- SourceDiversityManager,- SourceProfile,-)---class TestSourceProfileDefaults:- """Test SourceProfile dataclass default values."""-- def test_optional_fields_default_to_none(self):- """temporal_coverage, geographic_focus, last_accessed default to None."""- p = SourceProfile(- url="http://example.com",- domain="example.com",- source_type="general",- credibility_score=0.5,- )- assert p.temporal_coverage is None- assert p.geographic_focus is None- assert p.last_accessed is None- assert p.evidence_count == 0- assert p.specialties == []---class TestExtractDomain:- """Test SourceDiversityManager._extract_domain."""-- def _mgr(self):- return SourceDiversityManager(model=MagicMock())-- def test_https_url(self):- assert (- self._mgr()._extract_domain("https://example.com/path")- == "example.com"- )-- def test_http_url(self):- assert self._mgr()._extract_domain("http://test.org/page") == "test.org"-- def test_strips_www(self):- assert (- self._mgr()._extract_domain("https://www.example.com/p")- == "example.com"- )-- def test_bare_domain_no_path(self):- """URL with no trailing slash or path."""- assert (- self._mgr()._extract_domain("https://example.com") == "example.com"- )-- def test_fallback_for_non_url(self):- """Non-URL string is returned as-is."""- assert self._mgr()._extract_domain("not-a-url") == "not-a-url"---class TestDetermineSourceType:- """Test _determine_source_type with known domain patterns."""-- def _mgr(self):- return SourceDiversityManager(model=MagicMock())-- def test_edu_domain_is_academic(self):- result = self._mgr()._determine_source_type(- "https://mit.edu/paper", "mit.edu", None- )- assert result == "academic"-- def test_arxiv_is_academic(self):- result = self._mgr()._determine_source_type(- "https://arxiv.org/abs/123", "arxiv.org", None- )- assert result == "academic"-- def test_jstor_is_academic(self):- result = self._mgr()._determine_source_type(- "https://jstor.org/stable/123", "jstor.org", None- )- assert result == "academic"-- def test_gov_domain_is_government(self):- result = self._mgr()._determine_source_type(- "https://nasa.gov/data", "nasa.gov", None- )- assert result == "government"-- def test_wikipedia_is_wiki(self):- result = self._mgr()._determine_source_type(- "https://en.wikipedia.org/wiki/Test", "en.wikipedia.org", None- )- assert result == "wiki"-- def test_bbc_is_news(self):- result = self._mgr()._determine_source_type(- "https://bbc.co.uk/news", "bbc.co.uk", None- )- assert result == "news"-- def test_nytimes_is_news(self):- result = self._mgr()._determine_source_type(- "https://nytimes.com/article", "nytimes.com", None- )- assert result == "news"-- def test_no_match_no_content_is_general(self):- """Unknown domain without content returns 'general' without LLM call."""- mgr = self._mgr()- result = mgr._determine_source_type(- "https://random-site.io/page", "random-site.io", None- )- assert result == "general"- mgr.model.invoke.assert_not_called()---class TestCalculateCredibility:- """Test _calculate_credibility scoring logic."""-- def _mgr(self):- return SourceDiversityManager(model=MagicMock())-- def test_edu_domain_bonus(self):- """'.edu' in domain adds 0.1 to base score."""- score = self._mgr()._calculate_credibility(- "https://mit.edu", "mit.edu", "academic", None- )- # academic base=0.9, +0.1 capped at 1.0- assert score == 1.0-- def test_https_bonus(self):- """HTTPS URL adds 0.05 to base score."""- score = self._mgr()._calculate_credibility(- "https://example.com", "example.com", "general", None- )- # general base=0.5, +0.05=0.55- assert score == 0.55-- def test_bonuses_stack(self):- """Domain and HTTPS bonuses compound on top of base score."""- score = self._mgr()._calculate_credibility(- "https://example.edu/page", "example.edu", "general", None- )- # general=0.5 + edu=0.1 + https=0.05 = 0.65- assert abs(score - 0.65) < 0.01-- def test_citation_pattern_bonus(self):- """Content with citation patterns adds 0.1."""- score = self._mgr()._calculate_credibility(- "http://example.com",- "example.com",- "general",- "See reference [1] and (2024)",- )- # general=0.5 + citation=0.1 = 0.6- assert score >= 0.6-- def test_year_only_citation_pattern(self):- """Year-in-parens pattern alone triggers the bonus."""- score = self._mgr()._calculate_credibility(- "http://example.com",- "example.com",- "general",- "Published (2021) in journal",- )- assert score >= 0.6---class TestExtractTemporalCoverage:- """Test _extract_temporal_coverage."""-- def _mgr(self):- return SourceDiversityManager(model=MagicMock())-- def test_none_content(self):- assert self._mgr()._extract_temporal_coverage(None) is None-- def test_no_years_in_content(self):- assert self._mgr()._extract_temporal_coverage("No years here") is None-- def test_single_year(self):- result = self._mgr()._extract_temporal_coverage("Published in 2020")- assert result is not None- assert result[0].year == 2020- assert result[1].year == 2020-- def test_multiple_years_span(self):- result = self._mgr()._extract_temporal_coverage(- "From 1990 to 2020 data"- )- assert result[0].year == 1990- assert result[1].year == 2020---class TestExtractGeographicFocus:- """Test _extract_geographic_focus."""-- def _mgr(self):- return SourceDiversityManager(model=MagicMock())-- def test_uk_tld(self):- result = self._mgr()._extract_geographic_focus(- "https://example.uk/page", None- )- assert result == "United Kingdom"-- def test_au_tld(self):- result = self._mgr()._extract_geographic_focus(- "https://example.com.au/page", None- )- assert result == "Australia"-- def test_us_path_segment(self):- result = self._mgr()._extract_geographic_focus(- "https://example.com/us/policy", None- )- assert result == "United States"-- def test_no_geographic_info(self):- result = self._mgr()._extract_geographic_focus(- "https://example.com", None- )- assert result is None-- def test_content_location_detected(self):- result = self._mgr()._extract_geographic_focus(- "https://example.com", "The United States leads in research"- )- assert result is not None---class TestCalculateDiversityMetrics:- """Test calculate_diversity_metrics."""-- def test_empty_sources_returns_zeros(self):- """Empty source list returns all-zero metrics."""- mgr = SourceDiversityManager(model=MagicMock())- metrics = mgr.calculate_diversity_metrics([])- assert metrics.type_diversity == 0.0- assert metrics.overall_score == 0.0- assert metrics.credibility_distribution == {}-- def test_geographic_diversity_capped_at_one(self):- """Geographic diversity caps at 1.0 with many regions."""- mgr = SourceDiversityManager(model=MagicMock())- for i, region in enumerate(["US", "UK", "Canada", "Australia"]):- url = f"https://site{i}.com"- mgr.source_profiles[url] = SourceProfile(- url=url,- domain=f"site{i}.com",- source_type="general",- credibility_score=0.5,- geographic_focus=region,- )- metrics = mgr.calculate_diversity_metrics(- [f"https://site{i}.com" for i in range(4)]- )- assert metrics.geographic_diversity == 1.0-- def test_credibility_boundary_0_8_is_high(self):- """Score of exactly 0.8 is classified as 'high'."""- mgr = SourceDiversityManager(model=MagicMock())- url = "https://test.com"- mgr.source_profiles[url] = SourceProfile(- url=url,- domain="test.com",- source_type="academic",- credibility_score=0.8,- )- metrics = mgr.calculate_diversity_metrics([url])- assert metrics.credibility_distribution.get("high", 0) == 1---class TestSelectDiverseSources:- """Test select_diverse_sources."""-- def test_fewer_than_target_returns_all(self):- """When fewer sources than target, all are returned."""- mgr = SourceDiversityManager(model=MagicMock())- sources = ["https://a.com", "https://b.com"]- result = mgr.select_diverse_sources(sources, target_count=5)- assert result == sources-- def test_empty_source_list(self):- """Empty source list returns empty list."""- mgr = SourceDiversityManager(model=MagicMock())- result = mgr.select_diverse_sources([], target_count=5)- assert result == []---class TestHelperMethods:- """Test _get_source_type_modifier and _get_region_domain."""-- def _mgr(self):- return SourceDiversityManager(model=MagicMock())-- def test_academic_modifier_nonempty(self):- result = self._mgr()._get_source_type_modifier("academic")- assert len(result) > 0- assert ".edu" in result-- def test_government_modifier_nonempty(self):- result = self._mgr()._get_source_type_modifier("government")- assert ".gov" in result-- def test_unknown_modifier_empty(self):- result = self._mgr()._get_source_type_modifier("unknown_type")- assert result == ""-- def test_united_states_domain(self):- result = self._mgr()._get_region_domain("United States")- assert ".us" in result- assert ".com" in result-- def test_unknown_region_fallback(self):- result = self._mgr()._get_region_domain("Antarctica")- assert result == ".com"diff --git a/tests/advanced_search_system/source_management/test_diversity_manager_high_value.py b/tests/advanced_search_system/source_management/test_diversity_manager_high_value.pydeleted file mode 100644index 137c15a58d..0000000000--- a/tests/advanced_search_system/source_management/test_diversity_manager_high_value.py+++ /dev/null@@ -1,698 +0,0 @@-"""High-value pure logic tests for diversity_manager.py.--Covers dataclass fields/defaults, domain extraction edge cases,-source type classification, credibility scoring, temporal/geographic-extraction, diversity metrics formulas, temporal diversity scoring,-gap identification, diverse source selection, and helper methods.-"""--from datetime import datetime-from unittest.mock import MagicMock, patch---from local_deep_research.advanced_search_system.source_management.diversity_manager import (- DiversityMetrics,- SourceDiversityManager,- SourceProfile,-)---# ----------------------------------------------------------------------------# Dataclass field / default tests-# ------------------------------------------------------------------------------class TestSourceProfileDataclass:- """Verify SourceProfile dataclass fields and defaults."""-- def test_required_fields_assigned(self):- profile = SourceProfile(- url="http://x.com",- domain="x.com",- source_type="news",- credibility_score=0.7,- )- assert profile.url == "http://x.com"- assert profile.domain == "x.com"- assert profile.source_type == "news"- assert profile.credibility_score == 0.7-- def test_specialties_default_is_independent_list(self):- """Each instance gets its own specialties list (no shared mutable default)."""- p1 = SourceProfile(- url="a", domain="a", source_type="x", credibility_score=0.5- )- p2 = SourceProfile(- url="b", domain="b", source_type="x", credibility_score=0.5- )- p1.specialties.append("topic")- assert p2.specialties == []-- def test_evidence_count_default_zero(self):- profile = SourceProfile(- url="u", domain="d", source_type="t", credibility_score=0.1- )- assert profile.evidence_count == 0---class TestDiversityMetricsDataclass:- """Verify DiversityMetrics dataclass fields."""-- def test_all_fields_stored(self):- metrics = DiversityMetrics(- type_diversity=0.5,- temporal_diversity=0.3,- geographic_diversity=0.2,- credibility_distribution={"high": 2, "low": 1},- specialty_coverage={"ai": 3},- overall_score=0.4,- )- assert metrics.type_diversity == 0.5- assert metrics.credibility_distribution == {"high": 2, "low": 1}- assert metrics.specialty_coverage == {"ai": 3}---# ----------------------------------------------------------------------------# Helper to build a manager without a real model-# ------------------------------------------------------------------------------def _make_manager(**overrides):- """Create a SourceDiversityManager with a MagicMock model."""- mgr = SourceDiversityManager(model=MagicMock())- for key, val in overrides.items():- setattr(mgr, key, val)- return mgr---# ----------------------------------------------------------------------------# _extract_domain-# ------------------------------------------------------------------------------class TestExtractDomain:- """Edge cases for URL domain extraction."""-- def test_subdomain_preserved(self):- mgr = _make_manager()- assert (- mgr._extract_domain("https://api.example.com/v1")- == "api.example.com"- )-- def test_port_included_in_domain(self):- mgr = _make_manager()- result = mgr._extract_domain("http://localhost:8080/page")- assert "localhost" in result-- def test_deeply_nested_path(self):- mgr = _make_manager()- assert mgr._extract_domain("https://a.b.c.d.com/x/y/z") == "a.b.c.d.com"-- def test_empty_string_returns_as_is(self):- mgr = _make_manager()- assert mgr._extract_domain("") == ""-- def test_ftp_scheme_not_matched(self):- """ftp:// does not match the http(s) regex; raw string returned."""- mgr = _make_manager()- assert (- mgr._extract_domain("ftp://files.example.com/f")- == "ftp://files.example.com/f"- )---# ----------------------------------------------------------------------------# _determine_source_type-# ------------------------------------------------------------------------------class TestDetermineSourceType:- """Domain pattern matching for source type classification."""-- def test_scholar_in_url_is_academic(self):- mgr = _make_manager()- result = mgr._determine_source_type(- "https://scholar.google.com/citations", "scholar.google.com", None- )- assert result == "academic"-- def test_pubmed_is_academic(self):- mgr = _make_manager()- assert (- mgr._determine_source_type(- "https://pubmed.ncbi.nlm.nih.gov/123",- "pubmed.ncbi.nlm.nih.gov",- None,- )- == "academic"- )-- def test_mil_domain_is_government(self):- mgr = _make_manager()- assert (- mgr._determine_source_type(- "https://army.mil/report", "army.mil", None- )- == "government"- )-- def test_reuters_is_news(self):- mgr = _make_manager()- assert (- mgr._determine_source_type(- "https://reuters.com/article", "reuters.com", None- )- == "news"- )-- def test_cnn_is_news(self):- mgr = _make_manager()- assert (- mgr._determine_source_type("https://cnn.com/story", "cnn.com", None)- == "news"- )-- def test_ac_uk_is_academic(self):- mgr = _make_manager()- assert (- mgr._determine_source_type(- "https://ox.ac.uk/paper", "ox.ac.uk", None- )- == "academic"- )-- def test_academic_in_url_but_not_domain(self):- """'scholar' in the URL path still triggers academic."""- mgr = _make_manager()- result = mgr._determine_source_type(- "https://google.com/scholar?q=test", "google.com", None- )- assert result == "academic"-- def test_priority_academic_over_news(self):- """Academic patterns are checked first and win over news."""- mgr = _make_manager()- # domain has both 'edu' and 'news' -- academic checked first- result = mgr._determine_source_type(- "https://news.stanford.edu/article", "news.stanford.edu", None- )- assert result == "academic"-- def test_content_fallback_calls_analyze(self):- """When no pattern matches but content is provided, _analyze_content_type is called."""- mgr = _make_manager()- with patch.object(- mgr, "_analyze_content_type", return_value="blog"- ) as mock_act:- result = mgr._determine_source_type(- "https://random.io/page", "random.io", "Some blog content"- )- assert result == "blog"- mock_act.assert_called_once_with("Some blog content")---# ----------------------------------------------------------------------------# _calculate_credibility-# ------------------------------------------------------------------------------class TestCalculateCredibility:- """Scoring logic for credibility."""-- def test_http_no_https_bonus(self):- mgr = _make_manager()- score = mgr._calculate_credibility(- "http://example.com", "example.com", "general", None- )- assert score == 0.5 # base only, no https bonus-- def test_gov_domain_bonus(self):- mgr = _make_manager()- score = mgr._calculate_credibility(- "https://data.gov/set", "data.gov", "government", None- )- # government base=0.85, +0.1(gov)=0.95, +0.05(https)=1.0- assert score == 1.0-- def test_author_pattern_bonus(self):- mgr = _make_manager()- score = mgr._calculate_credibility(- "http://example.com",- "example.com",- "general",- "By John Smith, this paper explores...",- )- # general=0.5 + author=0.05 = 0.55- assert score >= 0.55-- def test_citation_and_author_stack(self):- mgr = _make_manager()- content = "Author: Jane Doe. References [1] show trends from (2020)."- score = mgr._calculate_credibility(- "http://example.com", "example.com", "general", content- )- # general=0.5 + citation=0.1 + author=0.05 = 0.65- assert abs(score - 0.65) < 0.01-- def test_unknown_source_type_base_score(self):- mgr = _make_manager()- score = mgr._calculate_credibility(- "http://example.com", "example.com", "unknown_type", None- )- assert score == 0.5 # default from type_priorities.get fallback-- def test_score_never_exceeds_one(self):- """Even with all bonuses, score is capped at 1.0."""- mgr = _make_manager()- content = "Author: A B. [1] (2020) references."- score = mgr._calculate_credibility(- "https://mit.edu/paper", "mit.edu", "academic", content- )- assert score <= 1.0---# ----------------------------------------------------------------------------# _extract_temporal_coverage-# ------------------------------------------------------------------------------class TestExtractTemporalCoverage:- """Year extraction from text content."""-- def test_content_with_1900s_and_2000s(self):- mgr = _make_manager()- result = mgr._extract_temporal_coverage("Events from 1945 and 2005.")- assert result is not None- assert result[0].year == 1945- assert result[1].year == 2005-- def test_only_19xx_years(self):- mgr = _make_manager()- result = mgr._extract_temporal_coverage(- "Built in 1920 and renovated in 1985."- )- assert result[0].year == 1920- assert result[1].year == 1985-- def test_empty_string_returns_none(self):- mgr = _make_manager()- assert mgr._extract_temporal_coverage("") is None-- def test_non_year_numbers_ignored(self):- """Numbers that don't look like years (e.g., 1234, 2100) are not matched."""- mgr = _make_manager()- assert (- mgr._extract_temporal_coverage("Order 1234 shipped on day 5")- is None- )---# ----------------------------------------------------------------------------# _extract_geographic_focus-# ------------------------------------------------------------------------------class TestExtractGeographicFocus:- """Geographic pattern matching from URL and content."""-- def test_ca_tld_is_canada(self):- mgr = _make_manager()- result = mgr._extract_geographic_focus("https://example.ca/page", None)- assert result == "Canada"-- def test_eu_in_url_is_europe(self):- mgr = _make_manager()- result = mgr._extract_geographic_focus("https://example.eu/data", None)- assert result == "Europe"-- def test_content_with_multiple_mentions_picks_most_frequent(self):- mgr = _make_manager()- content = "UK policy affects UK citizens. Canada also participates."- result = mgr._extract_geographic_focus("https://example.com", content)- assert result == "UK"-- def test_content_case_insensitive_match(self):- mgr = _make_manager()- content = "The UNITED STATES announced new policy."- result = mgr._extract_geographic_focus("https://example.com", content)- assert result is not None---# ----------------------------------------------------------------------------# _calculate_temporal_diversity-# ------------------------------------------------------------------------------class TestCalculateTemporalDiversity:- """Year range scoring for temporal diversity."""-- def test_empty_ranges(self):- mgr = _make_manager()- assert mgr._calculate_temporal_diversity([]) == 0.0-- def test_single_year_range_zero_diversity(self):- """A single range covering one year gives 0.0 diversity."""- mgr = _make_manager()- result = mgr._calculate_temporal_diversity(- [(datetime(2020, 1, 1), datetime(2020, 12, 31))]- )- assert result == 0.0-- def test_twenty_year_span_is_max(self):- mgr = _make_manager()- result = mgr._calculate_temporal_diversity(- [(datetime(2000, 1, 1), datetime(2020, 12, 31))]- )- assert result == 1.0-- def test_span_over_twenty_capped(self):- mgr = _make_manager()- result = mgr._calculate_temporal_diversity(- [(datetime(1950, 1, 1), datetime(2020, 12, 31))]- )- assert result == 1.0-- def test_ten_year_span_half_diversity(self):- mgr = _make_manager()- result = mgr._calculate_temporal_diversity(- [(datetime(2010, 1, 1), datetime(2020, 12, 31))]- )- assert result == 0.5-- def test_multiple_overlapping_ranges(self):- mgr = _make_manager()- result = mgr._calculate_temporal_diversity(- [- (datetime(2000, 1, 1), datetime(2005, 12, 31)),- (datetime(2003, 1, 1), datetime(2010, 12, 31)),- ]- )- # span 2000-2010 = 10 years -> 0.5- assert result == 0.5---# ----------------------------------------------------------------------------# calculate_diversity_metrics-# ------------------------------------------------------------------------------class TestCalculateDiversityMetrics:- """Formula tests for the diversity metrics computation."""-- def _setup_profiles(self, mgr, profiles_data):- """Load pre-built profiles into manager."""- for data in profiles_data:- url = data["url"]- mgr.source_profiles[url] = SourceProfile(**data)-- def test_single_source_type_diversity(self):- mgr = _make_manager()- url = "https://only.com"- mgr.source_profiles[url] = SourceProfile(- url=url,- domain="only.com",- source_type="news",- credibility_score=0.7,- )- metrics = mgr.calculate_diversity_metrics([url])- # 1 unique type / 3 minimum = 0.333...- assert abs(metrics.type_diversity - 1.0 / 3) < 0.01-- def test_three_types_reaches_full_type_diversity(self):- mgr = _make_manager()- types = ["academic", "news", "wiki"]- urls = []- for idx, stype in enumerate(types):- url = f"https://site{idx}.com"- urls.append(url)- mgr.source_profiles[url] = SourceProfile(- url=url,- domain=f"site{idx}.com",- source_type=stype,- credibility_score=0.5,- )- metrics = mgr.calculate_diversity_metrics(urls)- assert metrics.type_diversity == 1.0-- def test_credibility_boundary_0_6_is_medium(self):- mgr = _make_manager()- url = "https://med.com"- mgr.source_profiles[url] = SourceProfile(- url=url,- domain="med.com",- source_type="general",- credibility_score=0.6,- )- metrics = mgr.calculate_diversity_metrics([url])- assert "medium" in metrics.credibility_distribution- assert metrics.credibility_distribution["medium"] == 1-- def test_credibility_below_0_6_is_low(self):- mgr = _make_manager()- url = "https://low.com"- mgr.source_profiles[url] = SourceProfile(- url=url,- domain="low.com",- source_type="general",- credibility_score=0.59,- )- metrics = mgr.calculate_diversity_metrics([url])- assert "low" in metrics.credibility_distribution-- def test_overall_score_formula(self):- """Verify the weighted formula for overall_score."""- mgr = _make_manager()- urls = []- for idx, stype in enumerate(["academic", "news", "wiki"]):- url = f"https://s{idx}.com"- urls.append(url)- mgr.source_profiles[url] = SourceProfile(- url=url,- domain=f"s{idx}.com",- source_type=stype,- credibility_score=0.9,- geographic_focus=["US", "UK", "CA"][idx],- temporal_coverage=(- datetime(2000, 1, 1),- datetime(2020, 12, 31),- ),- )- metrics = mgr.calculate_diversity_metrics(urls)- # type_diversity=1.0, temporal=1.0, geo=1.0, high_ratio=3/3=1.0- expected = 1.0 * 0.3 + 1.0 * 0.2 + 1.0 * 0.2 + 1.0 * 0.3- assert abs(metrics.overall_score - expected) < 0.01-- def test_specialty_coverage_aggregated(self):- mgr = _make_manager()- url1 = "https://a.com"- url2 = "https://b.com"- mgr.source_profiles[url1] = SourceProfile(- url=url1,- domain="a.com",- source_type="news",- credibility_score=0.5,- specialties=["ai", "ml"],- )- mgr.source_profiles[url2] = SourceProfile(- url=url2,- domain="b.com",- source_type="wiki",- credibility_score=0.5,- specialties=["ai"],- )- metrics = mgr.calculate_diversity_metrics([url1, url2])- assert metrics.specialty_coverage["ai"] == 2- assert metrics.specialty_coverage["ml"] == 1---# ----------------------------------------------------------------------------# _identify_diversity_gaps-# ------------------------------------------------------------------------------class TestIdentifyDiversityGaps:- """Gap identification logic."""-- def test_low_type_diversity_flags_missing_types(self):- mgr = _make_manager()- url = "https://blog.com"- mgr.source_profiles[url] = SourceProfile(- url=url,- domain="blog.com",- source_type="blog",- credibility_score=0.5,- )- metrics = DiversityMetrics(- type_diversity=0.3,- temporal_diversity=0.8,- geographic_diversity=0.8,- credibility_distribution={"low": 1},- specialty_coverage={},- overall_score=0.3,- )- gaps = mgr._identify_diversity_gaps(metrics, [])- assert "source_type" in gaps- # All of academic, government, news, wiki should be missing- assert set(gaps["source_type"]) == {- "academic",- "government",- "news",- "wiki",- }-- def test_high_type_diversity_no_type_gap(self):- mgr = _make_manager()- for stype in ["academic", "government", "news", "wiki"]:- url = f"https://{stype}.com"- mgr.source_profiles[url] = SourceProfile(- url=url,- domain=f"{stype}.com",- source_type=stype,- credibility_score=0.5,- )- metrics = DiversityMetrics(- type_diversity=0.9,- temporal_diversity=0.8,- geographic_diversity=0.8,- credibility_distribution={"medium": 4},- specialty_coverage={},- overall_score=0.7,- )- gaps = mgr._identify_diversity_gaps(metrics, [])- assert "source_type" not in gaps-- def test_low_credibility_ratio_flags_gap(self):- mgr = _make_manager()- metrics = DiversityMetrics(- type_diversity=0.9,- temporal_diversity=0.8,- geographic_diversity=0.8,- credibility_distribution={"low": 10},- specialty_coverage={},- overall_score=0.3,- )- gaps = mgr._identify_diversity_gaps(metrics, [])- assert "credibility" in gaps-- def test_high_credibility_ratio_no_gap(self):- mgr = _make_manager()- metrics = DiversityMetrics(- type_diversity=0.9,- temporal_diversity=0.8,- geographic_diversity=0.8,- credibility_distribution={"high": 5, "low": 1},- specialty_coverage={},- overall_score=0.8,- )- gaps = mgr._identify_diversity_gaps(metrics, [])- assert "credibility" not in gaps---# ----------------------------------------------------------------------------# select_diverse_sources-# ------------------------------------------------------------------------------class TestSelectDiverseSources:- """Scoring and selection of diverse sources."""-- def test_selects_up_to_target_count(self):- """With diverse source types, selection reaches the target count."""- mgr = _make_manager()- urls = []- types = [- "academic",- "news",- "wiki",- "government",- "blog",- "general",- "forum",- "social",- "academic",- "news",- ]- for idx, stype in enumerate(types):- url = f"https://site{idx}.com"- urls.append(url)- mgr.source_profiles[url] = SourceProfile(- url=url,- domain=f"site{idx}.com",- source_type=stype,- credibility_score=0.5,- )- result = mgr.select_diverse_sources(urls, target_count=5)- assert len(result) == 5-- def test_diverse_types_preferred(self):- """Sources with unique types are preferred over duplicates."""- mgr = _make_manager()- urls = []- types = ["academic", "news", "general", "general", "general"]- for idx, stype in enumerate(types):- url = f"https://s{idx}.com"- urls.append(url)- mgr.source_profiles[url] = SourceProfile(- url=url,- domain=f"s{idx}.com",- source_type=stype,- credibility_score=0.5,- )- result = mgr.select_diverse_sources(urls, target_count=2)- selected_types = {mgr.source_profiles[u].source_type for u in result}- # Should pick at least 2 different types- assert len(selected_types) >= 2-- def test_equal_to_target_returns_all(self):- mgr = _make_manager()- urls = ["https://a.com", "https://b.com"]- result = mgr.select_diverse_sources(urls, target_count=2)- assert result == urls---# ----------------------------------------------------------------------------# _get_source_type_modifier and _get_region_domain-# ------------------------------------------------------------------------------class TestGetSourceTypeModifier:- """Search modifier mapping tests."""-- def test_news_modifier_contains_keywords(self):- mgr = _make_manager()- result = mgr._get_source_type_modifier("news")- assert "news" in result-- def test_wiki_modifier(self):- mgr = _make_manager()- result = mgr._get_source_type_modifier("wiki")- assert "wikipedia" in result-- def test_blog_modifier(self):- mgr = _make_manager()- result = mgr._get_source_type_modifier("blog")- assert "blog" in result---class TestGetRegionDomain:- """Region-to-domain suffix mapping tests."""-- def test_united_kingdom(self):- mgr = _make_manager()- assert mgr._get_region_domain("United Kingdom") == ".uk"-- def test_canada(self):- mgr = _make_manager()- assert mgr._get_region_domain("Canada") == ".ca"-- def test_australia(self):- mgr = _make_manager()- assert mgr._get_region_domain("Australia") == ".au"-- def test_europe_includes_multiple_tlds(self):- mgr = _make_manager()- result = mgr._get_region_domain("Europe")- assert ".eu" in result- assert ".de" in result- assert ".fr" in resultdiff --git a/tests/advanced_search_system/test_evidence_requirements_behavior.py b/tests/advanced_search_system/test_evidence_requirements_behavior.pydeleted file mode 100644index d05902a6d5..0000000000--- a/tests/advanced_search_system/test_evidence_requirements_behavior.py+++ /dev/null@@ -1,231 +0,0 @@-"""-Behavioral tests for evidence/requirements module.--Tests EvidenceRequirements class with get_requirements() and get_minimum_confidence().-"""---class TestGetRequirements:- """Tests for EvidenceRequirements.get_requirements() method."""-- def test_property_requirements(self):- from local_deep_research.advanced_search_system.constraints.base_constraint import (- ConstraintType,- )- from local_deep_research.advanced_search_system.evidence.requirements import (- EvidenceRequirements,- )-- req = EvidenceRequirements.get_requirements(ConstraintType.PROPERTY)- assert "preferred" in req- assert "acceptable" in req- assert "sources" in req- assert "direct_statement" in req["preferred"]-- def test_name_pattern_requirements(self):- from local_deep_research.advanced_search_system.constraints.base_constraint import (- ConstraintType,- )- from local_deep_research.advanced_search_system.evidence.requirements import (- EvidenceRequirements,- )-- req = EvidenceRequirements.get_requirements(ConstraintType.NAME_PATTERN)- assert "linguistic_analysis" in req["preferred"]-- def test_event_requirements(self):- from local_deep_research.advanced_search_system.constraints.base_constraint import (- ConstraintType,- )- from local_deep_research.advanced_search_system.evidence.requirements import (- EvidenceRequirements,- )-- req = EvidenceRequirements.get_requirements(ConstraintType.EVENT)- assert "news_report" in req["preferred"]-- def test_statistic_requirements(self):- from local_deep_research.advanced_search_system.constraints.base_constraint import (- ConstraintType,- )- from local_deep_research.advanced_search_system.evidence.requirements import (- EvidenceRequirements,- )-- req = EvidenceRequirements.get_requirements(ConstraintType.STATISTIC)- assert "statistical_data" in req["preferred"]-- def test_temporal_requirements(self):- from local_deep_research.advanced_search_system.constraints.base_constraint import (- ConstraintType,- )- from local_deep_research.advanced_search_system.evidence.requirements import (- EvidenceRequirements,- )-- req = EvidenceRequirements.get_requirements(ConstraintType.TEMPORAL)- assert "official_record" in req["preferred"]-- def test_location_requirements(self):- from local_deep_research.advanced_search_system.constraints.base_constraint import (- ConstraintType,- )- from local_deep_research.advanced_search_system.evidence.requirements import (- EvidenceRequirements,- )-- req = EvidenceRequirements.get_requirements(ConstraintType.LOCATION)- assert "geographical_data" in req["preferred"]-- def test_comparison_requirements(self):- from local_deep_research.advanced_search_system.constraints.base_constraint import (- ConstraintType,- )- from local_deep_research.advanced_search_system.evidence.requirements import (- EvidenceRequirements,- )-- req = EvidenceRequirements.get_requirements(ConstraintType.COMPARISON)- assert "statistical_comparison" in req["preferred"]-- def test_existence_requirements(self):- from local_deep_research.advanced_search_system.constraints.base_constraint import (- ConstraintType,- )- from local_deep_research.advanced_search_system.evidence.requirements import (- EvidenceRequirements,- )-- req = EvidenceRequirements.get_requirements(ConstraintType.EXISTENCE)- assert "direct_statement" in req["preferred"]-- def test_all_requirements_have_three_keys(self):- """All constraint types should have preferred, acceptable, and sources."""- from local_deep_research.advanced_search_system.constraints.base_constraint import (- ConstraintType,- )- from local_deep_research.advanced_search_system.evidence.requirements import (- EvidenceRequirements,- )-- for ct in ConstraintType:- req = EvidenceRequirements.get_requirements(ct)- assert "preferred" in req- assert "acceptable" in req- assert "sources" in req-- def test_all_requirements_have_non_empty_lists(self):- from local_deep_research.advanced_search_system.constraints.base_constraint import (- ConstraintType,- )- from local_deep_research.advanced_search_system.evidence.requirements import (- EvidenceRequirements,- )-- for ct in ConstraintType:- req = EvidenceRequirements.get_requirements(ct)- assert len(req["preferred"]) > 0- assert len(req["acceptable"]) > 0- assert len(req["sources"]) > 0---class TestGetMinimumConfidence:- """Tests for EvidenceRequirements.get_minimum_confidence() method."""-- def test_statistic_highest_threshold(self):- from local_deep_research.advanced_search_system.constraints.base_constraint import (- ConstraintType,- )- from local_deep_research.advanced_search_system.evidence.requirements import (- EvidenceRequirements,- )-- assert (- EvidenceRequirements.get_minimum_confidence(- ConstraintType.STATISTIC- )- == 0.8- )-- def test_event_moderate_threshold(self):- from local_deep_research.advanced_search_system.constraints.base_constraint import (- ConstraintType,- )- from local_deep_research.advanced_search_system.evidence.requirements import (- EvidenceRequirements,- )-- assert (- EvidenceRequirements.get_minimum_confidence(ConstraintType.EVENT)- == 0.7- )-- def test_property_threshold(self):- from local_deep_research.advanced_search_system.constraints.base_constraint import (- ConstraintType,- )- from local_deep_research.advanced_search_system.evidence.requirements import (- EvidenceRequirements,- )-- assert (- EvidenceRequirements.get_minimum_confidence(ConstraintType.PROPERTY)- == 0.6- )-- def test_name_pattern_lowest_explicit_threshold(self):- from local_deep_research.advanced_search_system.constraints.base_constraint import (- ConstraintType,- )- from local_deep_research.advanced_search_system.evidence.requirements import (- EvidenceRequirements,- )-- assert (- EvidenceRequirements.get_minimum_confidence(- ConstraintType.NAME_PATTERN- )- == 0.5- )-- def test_unlisted_type_gets_default_0_6(self):- from local_deep_research.advanced_search_system.constraints.base_constraint import (- ConstraintType,- )- from local_deep_research.advanced_search_system.evidence.requirements import (- EvidenceRequirements,- )-- assert (- EvidenceRequirements.get_minimum_confidence(ConstraintType.LOCATION)- == 0.6- )-- def test_all_thresholds_between_0_and_1(self):- from local_deep_research.advanced_search_system.constraints.base_constraint import (- ConstraintType,- )- from local_deep_research.advanced_search_system.evidence.requirements import (- EvidenceRequirements,- )-- for ct in ConstraintType:- threshold = EvidenceRequirements.get_minimum_confidence(ct)- assert 0.0 <= threshold <= 1.0-- def test_statistic_higher_than_name_pattern(self):- """Statistical claims require higher confidence than name patterns."""- from local_deep_research.advanced_search_system.constraints.base_constraint import (- ConstraintType,- )- from local_deep_research.advanced_search_system.evidence.requirements import (- EvidenceRequirements,- )-- stat = EvidenceRequirements.get_minimum_confidence(- ConstraintType.STATISTIC- )- name = EvidenceRequirements.get_minimum_confidence(- ConstraintType.NAME_PATTERN- )- assert stat > name