Skip to content

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

Remove experimental search strategies not in the frontend (#4420)

LearningCircuit9c29e14c40cb
diff --git a/changelog.d/+remove-experimental-search-strategies.removal.md b/changelog.d/+remove-experimental-search-strategies.removal.md
new file mode 100644
index 0000000000..3cdd77ca10
--- /dev/null
+++ b/changelog.d/+remove-experimental-search-strategies.removal.md
@@ -0,0 +1 @@
+Removed the experimental search strategies that were only reachable through the "Show All Strategies" toggle (rapid, parallel, iterative, recursive, adaptive, smart, standard, iterdrag, browsecomp, evidence, the constrained/dual-confidence family, modular, and others), along with the toggle itself. The strategy dropdown now offers source-based, focused-iteration, focused-iteration-standard, topic-organization, mcp, and langgraph-agent. The news feature's internal news-aggregation strategy is unaffected.
diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md
index 433c45d556..1d5b9d74fc 100644
--- a/docs/CONFIGURATION.md
+++ b/docs/CONFIGURATION.md
@@ -566,9 +566,8 @@ They are not available in the Web UI because they are needed to start the applic
| `search.region` | `LDR_SEARCH_REGION` | `us` | Geographic region for search results localization. Affects which results are prioritized based on regional relevance. | SEARCH |
| `search.safe_search` | `LDR_SEARCH_SAFE_SEARCH` | `true` | Filter out adult and inappropriate content from search results. Passed to search engines that support content filtering. | SEARCH |
| `search.search_language` | `LDR_SEARCH_SEARCH_LANGUAGE` | `English` | Preferred language for search results. Search engines will attempt to return and prioritize results in this language when available. | SEARCH |
-| `search.search_strategy` | `LDR_SEARCH_SEARCH_STRATEGY` | `langgraph-agent` | Research methodology. 'source-based': Finds and extracts from sources (good for comprehensive research). 'focused-iteration': Uses entity-based progressive exploration (optimized for factual Q&A, ~95% SimpleQA accuracy, requires larger context windows). 'focused-iteration-standard': Comprehensive variant of focused-iteration with broader exploration. 'iterative-refinement': LLM-guided progressive refinement with gap analysis. 'topic-organization': Organizes research around discovered topic clusters. 'mcp': Agentic ReAct-pattern research using MCP tools. | SEARCH |
+| `search.search_strategy` | `LDR_SEARCH_SEARCH_STRATEGY` | `langgraph-agent` | Research methodology. 'source-based': Finds and extracts from sources (good for comprehensive research). 'focused-iteration': Uses entity-based progressive exploration (optimized for factual Q&A, ~95% SimpleQA accuracy, requires larger context windows). 'focused-iteration-standard': Comprehensive variant of focused-iteration with broader exploration. 'topic-organization': Organizes research around discovered topic clusters. 'mcp': Agentic ReAct-pattern research using MCP tools. 'langgraph-agent': Autonomous agentic research where the LLM decides what to search and when to synthesize. | SEARCH |
| `search.searches_per_section` | `LDR_SEARCH_SEARCHES_PER_SECTION` | `2` | Number of independent searches per report section when generating structured reports. Increases coverage but also increases API usage. | SEARCH |
-| `search.show_all_strategies` | `LDR_SEARCH_SHOW_ALL_STRATEGIES` | `false` | When enabled, all available search strategies (including advanced and experimental ones) are shown in strategy dropdowns. When disabled, only the recommended strategies are shown. | SEARCH |
| `search.skip_relevance_filter` | `LDR_SEARCH_SKIP_RELEVANCE_FILTER` | `true` | When checked, LLM-based relevance filtering is suppressed for general-purpose search engines that do not require it. Keyword-based engines (arXiv, PubMed, Wikipedia, GitHub, etc.) always run the filter regardless of this checkbox; per-engine settings override both. | SEARCH |
| `search.snippets_only` | `LDR_SEARCH_SNIPPETS_ONLY` | `true` | Only retrieve search snippets instead of full webpage content. Reduces API usage and processing time, but provides less context for analysis. | SEARCH |
| `search.time_period` | `LDR_SEARCH_TIME_PERIOD` | `y` | Time range filter for search results. Limits results to content published within the specified period (day, week, month, year, or all time). | SEARCH |
diff --git a/docs/cli-tools.md b/docs/cli-tools.md
index 43702a04ba..ca646023ca 100644
--- a/docs/cli-tools.md
+++ b/docs/cli-tools.md
@@ -38,7 +38,7 @@ python -m local_deep_research.benchmarks.cli.benchmark_commands simpleqa [option
| `--iterations` | 3 | Search iterations per question |
| `--questions` | 3 | Questions per iteration |
| `--search-tool` | searxng | Search engine to use |
-| `--search-strategy` | source_based | Strategy (source_based, standard, rapid, parallel, iterdrag) |
+| `--search-strategy` | source_based | Strategy (source-based, focused-iteration, focused-iteration-standard, topic-organization) |
| `--search-model` | (default) | LLM model for research |
| `--search-provider` | (default) | LLM provider |
| `--eval-model` | (default) | Model for answer evaluation |
@@ -74,7 +74,7 @@ Same options as `simpleqa`.
# Run BrowseComp with focused-iteration strategy
python -m local_deep_research.benchmarks.cli.benchmark_commands browsecomp \
--examples 20 \
- --search-strategy iterdrag \
+ --search-strategy focused-iteration \
--iterations 5
```
diff --git a/docs/features.md b/docs/features.md
index 70c723ced9..097e48dcb4 100644
--- a/docs/features.md
+++ b/docs/features.md
@@ -115,15 +115,15 @@ The system automatically selects appropriate search engines based on query type:
### Search Strategies
-30+ search strategies including:
+Search strategies:
- `source-based`: Comprehensive research with detailed source tracking
-- `focused-iteration`: Iterative refinement (highest accuracy)
-- `rapid`: Speed-optimized quick searches
-- `parallel`: Concurrent multi-query execution
-- `dual-confidence`: Enhanced accuracy with confidence scoring
-- `evidence-based`: Evidence gathering and verification
+- `focused-iteration`: Iterative refinement, quick Q&A (highest factual accuracy)
+- `focused-iteration-standard`: Comprehensive variant with broader exploration
+- `topic-organization`: Clusters sources into topics for structured output
+- `mcp`: Agentic ReAct-pattern research using MCP tools
+- `langgraph-agent`: Autonomous agentic research
-See [Architecture Overview](architecture/OVERVIEW.md) for the full list.
+See [Architecture Overview](architecture/OVERVIEW.md) for details.
## LLM Integration
diff --git a/docs/mcp-server.md b/docs/mcp-server.md
index c66c4ea735..595e231a3a 100644
--- a/docs/mcp-server.md
+++ b/docs/mcp-server.md
@@ -184,7 +184,7 @@ Fast research summary. Typically takes **1-5 minutes**.
|-----------|------|----------|-------------|
| `query` | string | Yes | Research question (max 10,000 chars) |
| `search_engine` | string | No | Search engine to use (e.g., `"arxiv"`, `"wikipedia"`, `"auto"`) |
-| `strategy` | string | No | Research strategy (e.g., `"source-based"`, `"rapid"`) |
+| `strategy` | string | No | Research strategy (e.g., `"source-based"`, `"focused-iteration"`) |
| `iterations` | integer | No | Number of search iterations (1-10) |
| `questions_per_iteration` | integer | No | Questions per iteration (1-10) |
@@ -347,16 +347,16 @@ Returns the current server configuration including LLM provider, model, temperat
## Research Strategies Guide
-LDR supports 19+ research strategies. Here are the most commonly used ones via MCP:
+LDR supports the following research strategies via MCP:
| Strategy | Speed | Accuracy | Best For |
|----------|-------|----------|----------|
-| `rapid` | Fast | Lower | Breaking news, simple facts |
| `source-based` | Medium | High | Topics needing authoritative citations |
-| `focused-iteration` | Medium | Highest (~95%) | Complex technical topics |
+| `focused-iteration` | Medium | Highest (~95%) | Complex factual / technical topics |
+| `focused-iteration-standard` | Medium | High | Comprehensive long-form answers with citations |
+| `topic-organization` | Medium | High | Structured output clustered by theme |
| `mcp` (ReAct) | Varies | High | Multi-step reasoning, when AI decides approach |
-| `parallel` | Fast | Medium | Broad coverage, multiple angles |
-| `evidence` | Slow | Very High | Verification-critical research |
+| `langgraph-agent` | Varies | High | Autonomous agentic research across engines |
Use `list_strategies()` to see all available strategies and their descriptions.
diff --git a/docs/strategies/deleted/pr-remove-experimental-search-strategies.md b/docs/strategies/deleted/pr-remove-experimental-search-strategies.md
new file mode 100644
index 0000000000..02cbeababa
--- /dev/null
+++ b/docs/strategies/deleted/pr-remove-experimental-search-strategies.md
@@ -0,0 +1,160 @@
+# PR — remove experimental search strategies not in the frontend
+
+Components deleted in this PR (see the PR diff / `git show <sha>:<path>` for
+the full pre-deletion code — this file only summarises what was novel).
+
+All deleted strategies were reachable only through `create_strategy()` when
+selected via the "Show All Strategies" toggle (`search.show_all_strategies`,
+also removed) plus their own tests; none were on the default dropdown. The
+surviving, factory-reachable strategies are `SourceBasedSearchStrategy`
+(`source-based`), `FocusedIterationStrategy` (`focused-iteration` /
+`focused-iteration-standard`), `TopicOrganizationStrategy`
+(`topic-organization`), `MCPSearchStrategy` (`mcp`), `LangGraphAgentStrategy`
+(`langgraph-agent`), and the internal `NewsAggregationStrategy` (`news`).
+
+---
+
+## Component group: constraint / evidence / dual-confidence chain
+
+Files deleted (all under `src/local_deep_research/advanced_search_system/strategies/`):
+`evidence_based_strategy.py`, `evidence_based_strategy_v2.py`,
+`constrained_search_strategy.py`, `parallel_constrained_strategy.py`,
+`early_stop_constrained_strategy.py`, `smart_query_strategy.py`,
+`dual_confidence_strategy.py`, `dual_confidence_with_rejection.py`,
+`concurrent_dual_confidence_strategy.py`, `constraint_parallel_strategy.py`,
+plus the support packages `constraint_checking/` and `answer_decoding/`.
+
+- Reachability: a single-rooted inheritance chain
+ (`EvidenceBasedStrategy` → `ConstrainedSearchStrategy` → … →
+ `DualConfidenceWithRejectionStrategy` → `{Concurrent…, ConstraintParallel}`)
+ reachable only via the show-all dropdown and their own tests.
+- Closest reachable successor: none direct — this was the BrowseComp
+ entity-finding lineage. `FocusedIterationStrategy` covers factual Q&A in
+ production and still uses the surviving BrowseComp *question generators*
+ (`questions/browsecomp_question.py`, `questions/flexible_browsecomp_question.py`).
+
+### Useful ideas from the pre-deletion versions
+
+- **Dual-confidence scoring** — scored candidates with separate positive /
+ negative / uncertainty signals (`uncertainty_penalty`, `negative_weight`)
+ rather than a single relevance score, with an early-rejection threshold to
+ prune candidates that strongly violate a critical constraint. A genuinely
+ distinctive evaluation idea; only ever exercised on BrowseComp-style
+ entity puzzles, not on general research.
+- **Concurrent search + evaluation** — `ConcurrentDualConfidenceStrategy` ran
+ candidate search and constraint evaluation on overlapping thread pools with
+ a quality-plateau early stop, instead of strict search-then-evaluate rounds.
+- **`constraint_checking/` checkers** — pluggable checker hierarchy
+ (strict / threshold / dual-confidence / rejection-engine) over a shared
+ `BaseConstraintChecker` interface. The pluggability was the interesting part;
+ it had no consumer outside this strategy chain.
+
+### Why deletion was safe
+
+The whole lineage was self-contained (each class only inherited from the one
+above it) and never on the default dropdown. The reusable, validated pieces —
+the BrowseComp question generators and the `candidate_exploration/` explorers —
+live in separate packages that survive and are still used by
+`FocusedIterationStrategy`.
+
+### Recovery path
+
+Do not restore the files. If dual-confidence scoring proves worth reviving,
+add it as an evaluation option on a surviving strategy rather than
+resurrecting the inheritance chain.
+
+---
+
+## Component group: query-decomposition strategies
+
+Files deleted: `recursive_decomposition_strategy.py`,
+`adaptive_decomposition_strategy.py`, `smart_decomposition_strategy.py`.
+
+- Reachability: factory keys `recursive`, `adaptive`, `smart`; show-all only.
+- Closest reachable successor: `SourceBasedSearchStrategy` / the
+ decomposition question generator (`questions/decomposition_question.py`,
+ which survives).
+
+### Useful ideas
+
+- **Adaptive step typing** — `AdaptiveDecompositionStrategy` modelled a run as
+ typed steps (`StepType`: constraint-extraction / initial-search /
+ verification / refinement / synthesis) with a confidence heuristic
+ (verified-facts / constraints, +0.1 for having candidates, capped 0.95).
+ A tidy state model that was never benchmarked against the simpler strategies.
+
+### Why deletion was safe
+
+Exploratory; the surviving `DecompositionQuestionGenerator` keeps the
+sub-query generation idea available to any strategy.
+
+### Recovery path
+
+Do not restore. Add a decomposition option to a surviving strategy if needed.
+
+---
+
+## Component group: simple / single-pass strategies
+
+Files deleted: `rapid_search_strategy.py`, `parallel_search_strategy.py`,
+`standard_strategy.py`, `iterdrag_strategy.py`,
+`iterative_reasoning_strategy.py` (factory keys `iterative` and
+`iterative-reasoning`).
+
+- Reachability: show-all only, plus benchmark defaults that pointed at
+ `iterdrag` (now repointed to `source-based`).
+- Closest reachable successor: `SourceBasedSearchStrategy` (single/parallel
+ passes) and `FocusedIterationStrategy` (iterative reasoning with knowledge
+ accumulation).
+
+### Useful ideas
+
+- **IterDRAG** — interleaved iterative retrieval and generation; was the
+ historical benchmark default. Its retrieval-augmented loop is subsumed by
+ focused-iteration's knowledge accumulation.
+- **`RapidSearchStrategy`** — deliberately single-iteration for latency-bound
+ use; the same effect is achievable with `source-based` and
+ `max_iterations=1`.
+
+### Why deletion was safe
+
+All were thin variants of behavior the two surviving general strategies
+provide via parameters.
+
+### Recovery path
+
+Prefer flags on `source-based` / `focused-iteration` over restoring the files.
+
+---
+
+## Component group: meta / specialised strategies
+
+Files deleted: `iterative_refinement_strategy.py`,
+`browsecomp_optimized_strategy.py`, `browsecomp_entity_strategy.py`,
+`modular_strategy.py` (factory keys `modular` / `modular-parallel`).
+
+- Reachability: show-all only.
+- Closest reachable successor: `FocusedIterationStrategy` (BrowseComp
+ optimisation + question generation) and `TopicOrganizationStrategy`.
+
+### Useful ideas
+
+- **`IterativeRefinementStrategy`** — a *wrapper* meta-strategy: it ran an
+ inner strategy (default `source-based`), then used LLM gap-analysis to drive
+ follow-up refinement rounds. The wrap-any-strategy interface was the novel
+ part; it added cost without a benchmarked win.
+- **`ModularStrategy`** — composed constraint-checker + candidate-explorer
+ modules selected by string keys. The module-composition idea is interesting
+ but only ever wired to the now-deleted constraint checkers.
+- **`BrowseCompEntityStrategy`** — entity-focused knowledge-graph building for
+ BrowseComp puzzles; the question-generation half survives in `questions/`.
+
+### Why deletion was safe
+
+None were on the default dropdown; their validated sub-pieces (BrowseComp
+question generators, `candidate_exploration/`) survive independently.
+
+### Recovery path
+
+Do not restore. Re-expose the refinement/modular ideas as options on a
+surviving strategy if a benchmark justifies it.
diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md
index 82014fe2c4..60353798ae 100644
--- a/docs/troubleshooting.md
+++ b/docs/troubleshooting.md
@@ -531,9 +531,9 @@ sudo lsof -i :5000 # May need sudo for system services
search.questions_per_iteration = 3 # Instead of 5
```
-3. **Use faster strategy:**
+3. **Use a lighter strategy:**
```
- search.strategy = rapid # Instead of source-based
+ search.search_strategy = source-based # Instead of the agentic default
```
4. **Limit search results:**
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__.py
deleted file mode 100644
index e6fed9798d..0000000000
--- a/src/local_deep_research/advanced_search_system/answer_decoding/__init__.py
+++ /dev/null
@@ -1,3 +0,0 @@
-"""Answer decoding module for BrowseComp."""
-
-__all__: list[str] = []
diff --git a/src/local_deep_research/advanced_search_system/constraint_checking/README.md b/src/local_deep_research/advanced_search_system/constraint_checking/README.md
deleted file mode 100644
index 4571fb7cb5..0000000000
--- a/src/local_deep_research/advanced_search_system/constraint_checking/README.md
+++ /dev/null
@@ -1,150 +0,0 @@
-# Constraint Checking System
-
-This module provides an inheritance-based constraint checking system for validating candidates against constraints in the Local Deep Research framework.
-
-## Architecture
-
-The system is built around inheritance and provides multiple implementations:
-
-### Base Class
-- **`BaseConstraintChecker`**: Abstract base class defining the interface
-
-### Concrete Implementations
-- **`DualConfidenceChecker`**: Uses positive/negative/uncertainty confidence scoring
-- **`ThresholdChecker`**: Simple threshold-based checking
-- **`StrictChecker`**: Example of very strict constraint validation
-
-### Supporting Components
-- **`EvidenceAnalyzer`**: Analyzes evidence using dual confidence scoring
-- **`RejectionEngine`**: Makes rejection decisions based on evidence
-- **`ConstraintCheckResult`**: Data class containing evaluation results
-
-## Usage Examples
-
-### Using DualConfidenceChecker
-```python
-from constraint_checking import DualConfidenceChecker
-
-checker = DualConfidenceChecker(
- model=llm,
- evidence_gatherer=evidence_function,
- negative_threshold=0.25, # Reject if negative evidence > 25%
- positive_threshold=0.4, # Reject if positive evidence < 40%
-)
-
-result = checker.check_candidate(candidate, constraints)
-```
-
-### Using ThresholdChecker
-```python
-from constraint_checking import ThresholdChecker
-
-checker = ThresholdChecker(
- model=llm,
- evidence_gatherer=evidence_function,
- satisfaction_threshold=0.7, # Individual constraint threshold
- required_satisfaction_rate=0.8 # Overall satisfaction rate needed
-)
-
-result = checker.check_candidate(candidate, constraints)
-```
-
-### Using StrictChecker
-```python
-from constraint_checking import StrictChecker
-
-checker = StrictChecker(
- model=llm,
- evidence_gatherer=evidence_function,
- strict_threshold=0.9, # Very high threshold
- name_pattern_required=True # NAME_PATTERN constraints are mandatory
-)
-
-result = checker.check_candidate(candidate, constraints)
-```
-
-## Creating Custom Variants
-
-To create your own constraint checker variant:
-
-1. **Inherit from BaseConstraintChecker**:
-```python
-from .base_constraint_checker import BaseConstraintChecker, ConstraintCheckResult
-
-class MyCustomChecker(BaseConstraintChecker):
- def __init__(self, *args, my_param=0.5, **kwargs):
- super().__init__(*args, **kwargs)
- self.my_param = my_param
-```
-
-2. **Implement required methods**:
-```python
- def check_candidate(self, candidate, constraints):
- # Your implementation here
- return ConstraintCheckResult(...)
-
- def should_reject_candidate(self, candidate, constraint, evidence_data):
- # Your rejection logic here
- return should_reject, reason
-```
-
-3. **Add custom logic**:
-```python
- def _my_custom_evaluation(self, candidate, constraint):
- # Your custom evaluation logic
- pass
-```
-
-## Integration with Strategies
-
-Use in your strategy by initializing the checker:
-
-```python
-class MyStrategy(BaseStrategy):
- def __init__(self, *args, **kwargs):
- super().__init__(*args, **kwargs)
-
- # Choose your constraint checker
- self.constraint_checker = DualConfidenceChecker(
- model=self.model,
- evidence_gatherer=self._gather_evidence_for_constraint,
- # ... other parameters
- )
-
- def _evaluate_candidate(self, candidate):
- result = self.constraint_checker.check_candidate(candidate, self.constraints)
-
- # Process result
- candidate.evaluation_results = result.detailed_results
- candidate.score = result.total_score
-
- return result.total_score
-```
-
-## Available Checkers
-
-### DualConfidenceChecker
-- **Best for**: Nuanced evaluation with detailed confidence scoring
-- **Parameters**: `negative_threshold`, `positive_threshold`, `uncertainty_penalty`, `negative_weight`
-- **Output**: Detailed positive/negative/uncertainty scores per constraint
-
-### ThresholdChecker
-- **Best for**: Fast, simple constraint checking
-- **Parameters**: `satisfaction_threshold`, `required_satisfaction_rate`
-- **Output**: Simple satisfied/not satisfied per constraint
-
-### StrictChecker
-- **Best for**: Cases requiring very high confidence
-- **Parameters**: `strict_threshold`, `name_pattern_required`
-- **Output**: Binary pass/fail with strict requirements
-
-## Extending the System
-
-The inheritance-based design makes it easy to:
-
-1. **Create specialized checkers** for specific domains
-2. **Mix and match components** (e.g., use DualConfidence evidence analysis with custom rejection logic)
-3. **Add new constraint types** with custom handling
-4. **Implement domain-specific optimizations**
-
-See `strict_checker.py` for an example of creating a custom variant.
diff --git a/src/local_deep_research/advanced_search_system/constraint_checking/__init__.py b/src/local_deep_research/advanced_search_system/constraint_checking/__init__.py
deleted file mode 100644
index 5ee75dcea1..0000000000
--- a/src/local_deep_research/advanced_search_system/constraint_checking/__init__.py
+++ /dev/null
@@ -1,35 +0,0 @@
-"""
-Constraint checking and candidate assessment system.
-
-This module provides inheritance-based components for checking candidates
-against constraints, with different implementations available.
-"""
-
-from .base_constraint_checker import (
- BaseConstraintChecker,
- ConstraintCheckResult,
-)
-
-# Legacy imports for backward compatibility
-from .constraint_checker import ConstraintChecker
-from .dual_confidence_checker import DualConfidenceChecker
-from .evidence_analyzer import ConstraintEvidence, EvidenceAnalyzer
-from .rejection_engine import RejectionEngine
-from .strict_checker import StrictChecker
-from .threshold_checker import ThresholdChecker
-
-__all__ = [
- # Base classes
- "BaseConstraintChecker",
- "ConstraintCheckResult",
- # Concrete implementations
- "DualConfidenceChecker",
- "ThresholdChecker",
- "StrictChecker",
- # Supporting components
- "EvidenceAnalyzer",
- "ConstraintEvidence",
- "RejectionEngine",
- # Legacy
- "ConstraintChecker",
-]
diff --git a/src/local_deep_research/advanced_search_system/constraint_checking/base_constraint_checker.py b/src/local_deep_research/advanced_search_system/constraint_checking/base_constraint_checker.py
deleted file mode 100644
index 25c592ef65..0000000000
--- a/src/local_deep_research/advanced_search_system/constraint_checking/base_constraint_checker.py
+++ /dev/null
@@ -1,119 +0,0 @@
-"""
-Base constraint checker for inheritance-based constraint checking system.
-
-This module provides the base interface and common functionality for
-constraint checking implementations.
-"""
-
-from abc import ABC, abstractmethod
-from dataclasses import dataclass
-from typing import Any, Optional
-
-from langchain_core.language_models import BaseChatModel
-from loguru import logger
-
-from ..candidates.base_candidate import Candidate
-from ..constraints.base_constraint import Constraint
-
-
-@dataclass
-class ConstraintCheckResult:
- """Result of checking a candidate against all constraints."""
-
- candidate: Candidate
- total_score: float
- constraint_scores: dict[str, dict[str, Any]]
- should_reject: bool
- rejection_reason: Optional[str]
- detailed_results: list[dict[str, Any]]
-
-
-class BaseConstraintChecker(ABC):
- """
- Base class for constraint checking implementations.
-
- This provides the common interface and shared functionality that
- all constraint checkers should implement.
- """
-
- def __init__(
- self,
- model: BaseChatModel,
- evidence_gatherer=None, # Will be passed in from strategy
- **kwargs,
- ):
- """
- Initialize the base constraint checker.
-
- Args:
- model: Language model for evidence analysis
- evidence_gatherer: Function to gather evidence (from strategy)
- **kwargs: Additional parameters for specific implementations
- """
- self.model = model
- self.evidence_gatherer = evidence_gatherer
-
- @abstractmethod
- def check_candidate(
- self, candidate: Candidate, constraints: list[Constraint]
- ) -> ConstraintCheckResult:
- """
- Check a candidate against all constraints.
-
- Args:
- candidate: The candidate to check
- constraints: List of constraints to check against
-
- Returns:
- ConstraintCheckResult: Complete evaluation result
- """
- pass
-
- @abstractmethod
- def should_reject_candidate(
- self, candidate: Candidate, constraint: Constraint, evidence_data: Any
- ) -> tuple[bool, str]:
- """
- Determine if a candidate should be rejected for a specific constraint.
-
- Args:
- candidate: The candidate being evaluated
- constraint: The constraint being checked
- evidence_data: Evidence data (format depends on implementation)
-
- Returns:
- Tuple[bool, str]: (should_reject, reason)
- """
- pass
-
- def _gather_evidence_for_constraint(
- self, candidate: Candidate, constraint: Constraint
- ) -> list[dict[str, Any]]:
- """Gather evidence for a constraint using the provided evidence gatherer."""
- if self.evidence_gatherer:
- return self.evidence_gatherer(candidate, constraint)
- logger.warning("No evidence gatherer provided - cannot gather evidence")
- return []
-
- def _log_constraint_result(
- self,
- candidate: Candidate,
- constraint: Constraint,
- score: float,
- details: dict[str, Any],
- ):
- """Log constraint evaluation result."""
- symbol = "✓" if score >= 0.8 else "○" if score >= 0.5 else "✗"
- logger.info(
- f"{symbol} {candidate.name} | {constraint.value}: {int(score * 100)}%"
- )
-
- def _calculate_weighted_score(
- self, constraint_scores: list[float], weights: list[float]
- ) -> float:
- """Calculate weighted average score."""
- if not constraint_scores or not weights:
- return 0.0
- return sum(
- s * w for s, w in zip(constraint_scores, weights, strict=False)
- ) / sum(weights)
diff --git a/src/local_deep_research/advanced_search_system/constraint_checking/constraint_checker.py b/src/local_deep_research/advanced_search_system/constraint_checking/constraint_checker.py
deleted file mode 100644
index dd70494d1c..0000000000
--- a/src/local_deep_research/advanced_search_system/constraint_checking/constraint_checker.py
+++ /dev/null
@@ -1,220 +0,0 @@
-"""
-Main constraint checker that orchestrates constraint validation.
-
-This module provides the primary interface for checking candidates against constraints.
-"""
-
-from dataclasses import dataclass
-from typing import Dict, List, Optional
-
-from langchain_core.language_models import BaseChatModel
-from loguru import logger
-
-from ..candidates.base_candidate import Candidate
-from ..constraints.base_constraint import Constraint
-from .evidence_analyzer import EvidenceAnalyzer
-from .rejection_engine import RejectionEngine, RejectionResult
-
-
-@dataclass
-class ConstraintCheckResult:
- """Result of checking a candidate against all constraints."""
-
- candidate: Candidate
- total_score: float
- constraint_scores: Dict[str, Dict]
- rejection_result: Optional[RejectionResult]
- detailed_results: List[Dict]
-
-
-class ConstraintChecker:
- """
- Main constraint checker that validates candidates against constraints.
-
- This checker:
- 1. Gathers evidence for each constraint
- 2. Analyzes evidence using dual confidence scoring
- 3. Makes rejection decisions based on evidence
- 4. Provides detailed scoring breakdown
- """
-
- def __init__(
- self,
- model: BaseChatModel,
- evidence_gatherer=None, # Will be passed in from strategy
- negative_threshold: float = 0.25,
- positive_threshold: float = 0.4,
- uncertainty_penalty: float = 0.2,
- negative_weight: float = 0.5,
- ):
- """
- Initialize the constraint checker.
-
- Args:
- model: Language model for evidence analysis
- evidence_gatherer: Function to gather evidence (from strategy)
- negative_threshold: Rejection threshold for negative evidence
- positive_threshold: Minimum positive evidence required
- uncertainty_penalty: Penalty for uncertain evidence
- negative_weight: Weight for negative evidence in scoring
- """
- self.model = model
- self.evidence_gatherer = evidence_gatherer
-
- # Initialize components
- self.evidence_analyzer = EvidenceAnalyzer(model)
- self.rejection_engine = RejectionEngine(
- negative_threshold, positive_threshold
- )
-
- # Scoring parameters
- self.uncertainty_penalty = uncertainty_penalty
- self.negative_weight = negative_weight
-
- def check_candidate(
- self, candidate: Candidate, constraints: List[Constraint]
- ) -> ConstraintCheckResult:
- """
- Check a candidate against all constraints.
-
- Args:
- candidate: The candidate to check
- constraints: List of constraints to check against
-
- Returns:
- ConstraintCheckResult: Complete evaluation result
- """
- logger.info(f"Checking candidate: {candidate.name}")
-
- constraint_results = {}
- constraint_scores = {}
- detailed_results = []
- total_score = 0.0
-
- for constraint in constraints:
- # Gather evidence for this constraint
- evidence_list = self._gather_evidence_for_constraint(
- candidate, constraint
- )
-
- if evidence_list:
- # Analyze evidence with dual confidence
- dual_evidence = [
- self.evidence_analyzer.analyze_evidence_dual_confidence(
- e, constraint
- )
- for e in evidence_list
- ]
-
- constraint_results[constraint] = dual_evidence
-
- # Calculate average scores for this constraint
- avg_positive = sum(
- e.positive_confidence for e in dual_evidence
- ) / len(dual_evidence)
- avg_negative = sum(
- e.negative_confidence for e in dual_evidence
- ) / len(dual_evidence)
- avg_uncertainty = sum(
- e.uncertainty for e in dual_evidence
- ) / len(dual_evidence)
-
- # Calculate constraint score
- score = self.evidence_analyzer.evaluate_evidence_list(
- evidence_list,
- constraint,
- self.uncertainty_penalty,
- self.negative_weight,
- )
-
- # Store results
- constraint_scores[constraint.value] = {
- "total": score,
- "positive": avg_positive,
- "negative": avg_negative,
- "uncertainty": avg_uncertainty,
- "weight": constraint.weight,
- }
-
- detailed_results.append(
- {
- "constraint": constraint.value,
- "score": score,
- "positive": avg_positive,
- "negative": avg_negative,
- "uncertainty": avg_uncertainty,
- "weight": constraint.weight,
- "type": constraint.type.value,
- }
- )
-
- # Log result
- symbol = "✓" if score >= 0.8 else "○" if score >= 0.5 else "✗"
- logger.info(
- f"{symbol} {candidate.name} | {constraint.value}: {int(score * 100)}% "
- f"(+{int(avg_positive * 100)}% -{int(avg_negative * 100)}% ?{int(avg_uncertainty * 100)}%)"
- )
-
- else:
- # No evidence found
- score = 0.5 - self.uncertainty_penalty
-
- constraint_scores[constraint.value] = {
- "total": score,
- "positive": 0.0,
- "negative": 0.0,
- "uncertainty": 1.0,
- "weight": constraint.weight,
- }
-
- detailed_results.append(
- {
- "constraint": constraint.value,
- "score": score,
- "positive": 0.0,
- "negative": 0.0,
- "uncertainty": 1.0,
- "weight": constraint.weight,
- "type": constraint.type.value,
- }
- )
-
- logger.info(
- f"? {candidate.name} | {constraint.value}: No evidence found"
- )
-
- # Check for rejection
- rejection_result = self.rejection_engine.check_all_constraints(
- candidate, constraint_results
- )
-
- if rejection_result and rejection_result.should_reject:
- # Candidate should be rejected
- total_score = 0.0
- else:
- # Calculate weighted average score
- if detailed_results:
- weights = [r["weight"] for r in detailed_results]
- scores = [r["score"] for r in detailed_results]
- total_score = sum(
- s * w for s, w in zip(scores, weights, strict=False)
- ) / sum(weights)
-
- logger.info(f"Final score for {candidate.name}: {total_score:.2%}")
-
- return ConstraintCheckResult(
- candidate=candidate,
- total_score=total_score,
- constraint_scores=constraint_scores,
- rejection_result=rejection_result,
- detailed_results=detailed_results,
- )
-
- def _gather_evidence_for_constraint(
- self, candidate: Candidate, constraint: Constraint
- ) -> List[Dict]:
- """Gather evidence for a constraint using the provided evidence gatherer."""
- if self.evidence_gatherer:
- return self.evidence_gatherer(candidate, constraint)
- logger.warning("No evidence gatherer provided - cannot gather evidence")
- return []
diff --git a/src/local_deep_research/advanced_search_system/constraint_checking/dual_confidence_checker.py b/src/local_deep_research/advanced_search_system/constraint_checking/dual_confidence_checker.py
deleted file mode 100644
index b257ac9e33..0000000000
--- a/src/local_deep_research/advanced_search_system/constraint_checking/dual_confidence_checker.py
+++ /dev/null
@@ -1,424 +0,0 @@
-"""
-Dual confidence constraint checker implementation.
-
-This implementation uses dual confidence scoring (positive/negative/uncertainty)
-to evaluate constraints and make rejection decisions.
-"""
-
-from typing import Dict, List, Tuple
-
-from loguru import logger
-
-from ..candidates.base_candidate import Candidate
-from ..constraints.base_constraint import Constraint
-from .base_constraint_checker import (
- BaseConstraintChecker,
- ConstraintCheckResult,
-)
-from .evidence_analyzer import ConstraintEvidence, EvidenceAnalyzer
-
-
-class DualConfidenceChecker(BaseConstraintChecker):
- """
- Constraint checker using dual confidence scoring.
-
- This checker:
- 1. Analyzes evidence using positive/negative/uncertainty scores
- 2. Makes rejection decisions based on confidence thresholds
- 3. Provides detailed scoring breakdown
- """
-
- def __init__(
- self,
- *args,
- negative_threshold: float = 0.25, # Reject if negative evidence > 25%
- positive_threshold: float = 0.4, # Reject if positive evidence < 40%
- uncertainty_penalty: float = 0.2,
- negative_weight: float = 0.5,
- uncertainty_threshold: float = 0.6, # Re-evaluate if uncertainty > 60%
- max_reevaluations: int = 2, # Maximum re-evaluation rounds
- **kwargs,
- ):
- """
- Initialize dual confidence checker.
-
- Args:
- negative_threshold: Threshold for negative evidence rejection
- positive_threshold: Minimum positive evidence required
- uncertainty_penalty: Penalty for uncertain evidence
- negative_weight: Weight for negative evidence in scoring
- uncertainty_threshold: Re-evaluate if uncertainty exceeds this
- max_reevaluations: Maximum number of re-evaluation rounds
- """
- super().__init__(*args, **kwargs)
-
- self.negative_threshold = negative_threshold
- self.positive_threshold = positive_threshold
- self.uncertainty_penalty = uncertainty_penalty
- self.negative_weight = negative_weight
- self.uncertainty_threshold = uncertainty_threshold
- self.max_reevaluations = max_reevaluations
-
- # Initialize evidence analyzer
- self.evidence_analyzer = EvidenceAnalyzer(self.model)
-
- def check_candidate(
- self,
- candidate: Candidate,
- constraints: List[Constraint],
- original_query: str = None,
- ) -> ConstraintCheckResult:
- """Check candidate using dual confidence analysis with LLM pre-screening."""
- logger.info(f"Checking candidate: {candidate.name} (dual confidence)")
-
- # LLM PRE-SCREENING: Check all constraints in one call to save SearXNG capacity
- pre_screen_result = self._llm_prescreen_candidate(
- candidate, constraints, original_query
- )
- if pre_screen_result["should_reject"]:
- logger.info(
- f"🚫 LLM pre-screen rejected {candidate.name}: {pre_screen_result['reason']}"
- )
- return ConstraintCheckResult(
- candidate=candidate,
- constraint_scores={},
- should_reject=True,
- rejection_reason=pre_screen_result["reason"],
- total_score=0.0,
- detailed_results=pre_screen_result["detailed_results"],
- )
-
- constraint_scores = {}
- detailed_results = []
- rejection_reason = None
- should_reject = False
-
- for constraint in constraints:
- # Perform initial evaluation with re-evaluation for uncertain constraints
- result = self._evaluate_constraint_with_reevaluation(
- candidate, constraint
- )
-
- avg_positive = result["positive"]
- avg_negative = result["negative"]
- avg_uncertainty = result["uncertainty"]
- score = result["score"]
- reevaluation_count = result.get("reevaluation_count", 0)
-
- # Check for rejection based on final results
- reject, reason = self.should_reject_candidate_from_averages(
- candidate, constraint, avg_positive, avg_negative
- )
-
- if reject and not should_reject: # Only record first rejection
- should_reject = True
- rejection_reason = reason
-
- # Store results
- constraint_scores[constraint.value] = {
- "total": score,
- "positive": avg_positive,
- "negative": avg_negative,
- "uncertainty": avg_uncertainty,
- "weight": constraint.weight,
- "reevaluation_count": reevaluation_count,
- }
-
- detailed_results.append(
- {
- "constraint": constraint.value,
- "score": score,
- "positive": avg_positive,
- "negative": avg_negative,
- "uncertainty": avg_uncertainty,
- "weight": constraint.weight,
- "type": constraint.type.value,
- "reevaluation_count": reevaluation_count,
- }
- )
-
- # Log detailed result with re-evaluation info
- self._log_constraint_result_detailed(
- candidate,
- constraint,
- score,
- avg_positive,
- avg_negative,
- avg_uncertainty,
- reevaluation_count,
- )
-
- # Calculate total score
- if should_reject:
- total_score = 0.0
- else:
- if detailed_results:
- weights = [r["weight"] for r in detailed_results]
- scores = [r["score"] for r in detailed_results]
- total_score = self._calculate_weighted_score(scores, weights)
- else:
- total_score = 0.0
-
- logger.info(f"Final score for {candidate.name}: {total_score:.2%}")
-
- return ConstraintCheckResult(
- candidate=candidate,
- total_score=total_score,
- constraint_scores=constraint_scores,
- should_reject=should_reject,
- rejection_reason=rejection_reason,
- detailed_results=detailed_results,
- )
-
- def _evaluate_constraint_with_reevaluation(
- self, candidate: Candidate, constraint: Constraint
- ) -> Dict:
- """Evaluate constraint with potential re-evaluation for uncertain results."""
- reevaluation_count = 0
- evidence_list = []
-
- while reevaluation_count <= self.max_reevaluations:
- # Gather evidence (fresh each time for re-evaluation)
- evidence_list = self._gather_evidence_for_constraint(
- candidate, constraint
- )
-
- if not evidence_list:
- # No evidence found
- return {
- "positive": 0.0,
- "negative": 0.0,
- "uncertainty": 1.0,
- "score": 0.5 - self.uncertainty_penalty,
- "evidence_list": [],
- "reevaluation_count": reevaluation_count,
- }
-
- # Analyze with dual confidence
- dual_evidence = [
- self.evidence_analyzer.analyze_evidence_dual_confidence(
- e, constraint
- )
- for e in evidence_list
- ]
-
- # Calculate averages
- avg_positive = sum(
- e.positive_confidence for e in dual_evidence
- ) / len(dual_evidence)
- avg_negative = sum(
- e.negative_confidence for e in dual_evidence
- ) / len(dual_evidence)
- avg_uncertainty = sum(e.uncertainty for e in dual_evidence) / len(
- dual_evidence
- )
-
- # Calculate score
- score = self.evidence_analyzer.evaluate_evidence_list(
- evidence_list,
- constraint,
- self.uncertainty_penalty,
- self.negative_weight,
- )
-
- # Check if we need re-evaluation
- if (
- reevaluation_count < self.max_reevaluations
- and avg_uncertainty > self.uncertainty_threshold
- and not self._should_early_reject(avg_positive, avg_negative)
- ):
- reevaluation_count += 1
- logger.info(
- f"🔄 Re-evaluating {candidate.name} | {constraint.value} "
- f"(round {reevaluation_count}) - high uncertainty: {avg_uncertainty:.0%}"
- )
- continue
- # Final result or early rejection
- if reevaluation_count > 0:
- logger.info(
- f"✅ Final evaluation for {candidate.name} | {constraint.value} "
- f"after {reevaluation_count} re-evaluation(s)"
- )
-
- return {
- "positive": avg_positive,
- "negative": avg_negative,
- "uncertainty": avg_uncertainty,
- "score": score,
- "evidence_list": evidence_list,
- "reevaluation_count": reevaluation_count,
- }
-
- # Should not reach here, but fallback
- return {
- "positive": avg_positive,
- "negative": avg_negative,
- "uncertainty": avg_uncertainty,
- "score": score,
- "evidence_list": evidence_list,
- "reevaluation_count": reevaluation_count,
- }
-
- def _should_early_reject(
- self, avg_positive: float, avg_negative: float
- ) -> bool:
- """Check if candidate should be rejected early (before re-evaluation)."""
- return (
- avg_negative > self.negative_threshold
- or avg_positive < self.positive_threshold
- )
-
- def should_reject_candidate_from_averages(
- self,
- candidate: Candidate,
- constraint: Constraint,
- avg_positive: float,
- avg_negative: float,
- ) -> Tuple[bool, str]:
- """Determine rejection based on average confidence scores."""
- # PRIMARY REJECTION: High negative evidence
- if avg_negative > self.negative_threshold:
- reason = f"High negative evidence ({avg_negative:.0%}) for constraint '{constraint.value}'"
- logger.info(f"❌ REJECTION: {candidate.name} - {reason}")
- return True, reason
-
- # SECONDARY REJECTION: Low positive evidence
- if avg_positive < self.positive_threshold:
- reason = f"Insufficient positive evidence ({avg_positive:.0%}) for constraint '{constraint.value}'"
- logger.info(f"❌ REJECTION: {candidate.name} - {reason}")
- return True, reason
-
- return False, ""
-
- def should_reject_candidate(
- self,
- candidate: Candidate,
- constraint: Constraint,
- dual_evidence: List[ConstraintEvidence],
- ) -> Tuple[bool, str]:
- """Determine rejection based on dual confidence scores."""
- if not dual_evidence:
- return False, ""
-
- # Calculate averages
- avg_positive = sum(e.positive_confidence for e in dual_evidence) / len(
- dual_evidence
- )
- avg_negative = sum(e.negative_confidence for e in dual_evidence) / len(
- dual_evidence
- )
-
- # PRIMARY REJECTION: High negative evidence
- if avg_negative > self.negative_threshold:
- reason = f"High negative evidence ({avg_negative:.0%}) for constraint '{constraint.value}'"
- logger.info(f"❌ REJECTION: {candidate.name} - {reason}")
- return True, reason
-
- # SECONDARY REJECTION: Low positive evidence
- if avg_positive < self.positive_threshold:
- reason = f"Insufficient positive evidence ({avg_positive:.0%}) for constraint '{constraint.value}'"
- logger.info(f"❌ REJECTION: {candidate.name} - {reason}")
- return True, reason
-
- return False, ""
-
- def _log_constraint_result_detailed(
- self,
- candidate,
- constraint,
- score,
- positive,
- negative,
- uncertainty,
- reevaluation_count=0,
- ):
- """Log detailed constraint result."""
- symbol = "✓" if score >= 0.8 else "○" if score >= 0.5 else "✗"
-
- # Add re-evaluation indicator
- reeval_indicator = (
- f" [R{reevaluation_count}]" if reevaluation_count > 0 else ""
- )
-
- logger.info(
- f"{symbol} {candidate.name} | {constraint.value}: {int(score * 100)}% "
- f"(+{int(positive * 100)}% -{int(negative * 100)}% ?{int(uncertainty * 100)}%){reeval_indicator}"
- )
-
- def _llm_prescreen_candidate(
- self, candidate, constraints, original_query=None
- ):
- """Simple quality check for answer candidates."""
-
- if not original_query:
- return {
- "should_reject": False,
- "reason": "No original query provided",
- "detailed_results": [],
- }
-
- prompt = f"""Question: {original_query}
-Answer: {candidate.name}
-
-Is this a good answer to the question? Rate 0-100 where:
-- 90-100: Excellent direct answer
-- 70-89: Good answer
-- 50-69: Partial answer
-- 30-49: Weak answer
-- 0-29: Poor/wrong answer
-
-Just give the number:"""
-
- try:
- response = self.model.invoke(prompt).content
-
- # Parse confidence score
- import re
-
- confidence_match = re.search(r"(\d{1,3})", response.strip())
-
- if confidence_match:
- quality_score = int(confidence_match.group(1))
-
- # Accept good answers (50+ out of 100)
- if quality_score >= 50:
- return {
- "should_reject": False,
- "reason": f"Good answer quality: {quality_score}%",
- "detailed_results": [
- {
- "constraint": "answer_quality",
- "positive_confidence": quality_score / 100.0,
- "source": "answer_quality_check",
- }
- ],
- }
- return {
- "should_reject": True,
- "reason": f"Poor answer quality: {quality_score}%",
- "detailed_results": [
- {
- "constraint": "answer_quality",
- "negative_confidence": (100 - quality_score)
- / 100.0,
- "source": "answer_quality_check",
- }
- ],
- }
-
- # Parsing failed - accept by default
- return {
- "should_reject": False,
- "reason": "Could not parse quality score - accepting",
- "detailed_results": [],
- }
-
- except Exception:
- logger.warning(
- f"Fast LLM pre-screening failed for {candidate.name}"
- )
- return {
- "should_reject": False,
- "reason": "",
- "detailed_results": [],
- }
diff --git a/src/local_deep_research/advanced_search_system/constraint_checking/evidence_analyzer.py b/src/local_deep_research/advanced_search_system/constraint_checking/evidence_analyzer.py
deleted file mode 100644
index 34c70c998e..0000000000
--- a/src/local_deep_research/advanced_search_system/constraint_checking/evidence_analyzer.py
+++ /dev/null
@@ -1,174 +0,0 @@
-"""
-Evidence analysis for constraint checking.
-
-This module provides dual confidence evidence analysis that separates
-positive evidence, negative evidence, and uncertainty.
-"""
-
-import re
-from dataclasses import dataclass
-from typing import Dict, List
-
-from langchain_core.language_models import BaseChatModel
-from loguru import logger
-
-from ..constraints.base_constraint import Constraint
-
-
-@dataclass
-class ConstraintEvidence:
- """Evidence for a constraint with dual confidence scores."""
-
- positive_confidence: float # How sure we are the constraint IS satisfied
- negative_confidence: (
- float # How sure we are the constraint is NOT satisfied
- )
- uncertainty: float # How uncertain we are (neither positive nor negative)
- evidence_text: str
- source: str
-
-
-class EvidenceAnalyzer:
- """
- Analyzes evidence using dual confidence scoring.
-
- This approach separates:
- - Positive confidence: Evidence that constraint IS satisfied
- - Negative confidence: Evidence that constraint is NOT satisfied
- - Uncertainty: Lack of clear evidence either way
- """
-
- def __init__(self, model: BaseChatModel):
- """Initialize the evidence analyzer."""
- self.model = model
-
- def analyze_evidence_dual_confidence(
- self, evidence: Dict, constraint: Constraint
- ) -> ConstraintEvidence:
- """Analyze evidence to extract dual confidence scores."""
- text = evidence.get("text", "")
-
- # Use LLM to analyze evidence with dual confidence
- prompt = f"""
-Analyze this evidence for the constraint "{constraint.value}" (type: {constraint.type.value}).
-
-Evidence:
-{text[:1000]}
-
-Provide three confidence scores (0-1):
-1. POSITIVE_CONFIDENCE: How confident are you that this constraint IS satisfied?
-2. NEGATIVE_CONFIDENCE: How confident are you that this constraint is NOT satisfied?
-3. UNCERTAINTY: How uncertain are you (lack of clear evidence)?
-
-The three scores should approximately sum to 1.0.
-
-Format:
-POSITIVE: [score]
-NEGATIVE: [score]
-UNCERTAINTY: [score]
-"""
-
- try:
- response = self.model.invoke(prompt).content
-
- # Extract scores
- positive = self._extract_score(response, "POSITIVE")
- negative = self._extract_score(response, "NEGATIVE")
- uncertainty = self._extract_score(response, "UNCERTAINTY")
-
- # Normalize if needed
- total = positive + negative + uncertainty
- if total > 0:
- positive /= total
- negative /= total
- uncertainty /= total
- else:
- # Default to high uncertainty
- uncertainty = 0.8
- positive = 0.1
- negative = 0.1
-
- return ConstraintEvidence(
- positive_confidence=positive,
- negative_confidence=negative,
- uncertainty=uncertainty,
- evidence_text=text[:500],
- source=evidence.get("source", "search"),
- )
-
- except Exception:
- logger.exception("Error analyzing evidence")
- # Default to high uncertainty
- return ConstraintEvidence(
- positive_confidence=0.1,
- negative_confidence=0.1,
- uncertainty=0.8,
- evidence_text=text[:500],
- source=evidence.get("source", "search"),
- )
-
- def _extract_score(self, text: str, label: str) -> float:
- """Extract confidence score from LLM response."""
- pattern = rf"{label}:\s*\[?(\d*\.?\d+)\]?"
- match = re.search(pattern, text, re.IGNORECASE)
- if match:
- try:
- return float(match.group(1))
- except (ValueError, TypeError):
- pass
- return 0.1 # Default low score
-
- def evaluate_evidence_list(
- self,
- evidence_list: List[Dict],
- constraint: Constraint,
- uncertainty_penalty: float = 0.2,
- negative_weight: float = 0.5,
- ) -> float:
- """
- Evaluate a list of evidence using dual confidence scoring.
-
- Args:
- evidence_list: List of evidence dictionaries
- constraint: The constraint being evaluated
- uncertainty_penalty: Penalty for uncertainty
- negative_weight: Weight for negative evidence
-
- Returns:
- float: Overall score between 0.0 and 1.0
- """
- if not evidence_list:
- # No evidence means high uncertainty
- return 0.5 - uncertainty_penalty
-
- # Convert evidence to dual confidence format
- constraint_evidence = []
- for evidence in evidence_list:
- dual_evidence = self.analyze_evidence_dual_confidence(
- evidence, constraint
- )
- constraint_evidence.append(dual_evidence)
-
- # Calculate overall score
- total_positive = sum(e.positive_confidence for e in constraint_evidence)
- total_negative = sum(e.negative_confidence for e in constraint_evidence)
- total_uncertainty = sum(e.uncertainty for e in constraint_evidence)
-
- # Normalize
- evidence_count = len(constraint_evidence)
- avg_positive = total_positive / evidence_count
- avg_negative = total_negative / evidence_count
- avg_uncertainty = total_uncertainty / evidence_count
-
- # Calculate final score
- # High positive + low negative = high score
- # Low positive + high negative = low score
- # High uncertainty = penalty
- score = (
- avg_positive
- - (avg_negative * negative_weight)
- - (avg_uncertainty * uncertainty_penalty)
- )
-
- # Clamp to [0, 1]
- return max(0.0, min(1.0, score))
diff --git a/src/local_deep_research/advanced_search_system/constraint_checking/rejection_engine.py b/src/local_deep_research/advanced_search_system/constraint_checking/rejection_engine.py
deleted file mode 100644
index 96958cd5dc..0000000000
--- a/src/local_deep_research/advanced_search_system/constraint_checking/rejection_engine.py
+++ /dev/null
@@ -1,143 +0,0 @@
-"""
-Rejection engine for constraint-based candidate filtering.
-
-This module provides logic for rejecting candidates based on constraint violations.
-"""
-
-from dataclasses import dataclass
-from typing import Dict, List, Optional
-
-from loguru import logger
-
-from ..candidates.base_candidate import Candidate
-from ..constraints.base_constraint import Constraint
-from .evidence_analyzer import ConstraintEvidence
-
-
-@dataclass
-class RejectionResult:
- """Result of a rejection check."""
-
- should_reject: bool
- reason: str
- constraint_value: str
- positive_confidence: float
- negative_confidence: float
-
-
-class RejectionEngine:
- """
- Engine for making rejection decisions based on constraint violations.
-
- This engine uses simple, clear rules to determine when candidates
- should be rejected based on their constraint evaluation results.
- """
-
- def __init__(
- self,
- negative_threshold: float = 0.25, # Reject if negative evidence > 25%
- positive_threshold: float = 0.4, # Reject if positive evidence < 40%
- ):
- """
- Initialize the rejection engine.
-
- Args:
- negative_threshold: Threshold for negative evidence rejection
- positive_threshold: Minimum positive evidence required
- """
- self.negative_threshold = negative_threshold
- self.positive_threshold = positive_threshold
-
- def should_reject_candidate(
- self,
- candidate: Candidate,
- constraint: Constraint,
- evidence_list: List[ConstraintEvidence],
- ) -> RejectionResult:
- """
- Determine if a candidate should be rejected based on constraint evidence.
-
- Args:
- candidate: The candidate being evaluated
- constraint: The constraint being checked
- evidence_list: List of evidence for this constraint
-
- Returns:
- RejectionResult: Whether to reject and why
- """
- if not evidence_list:
- # No evidence - don't reject but note the lack of evidence
- return RejectionResult(
- should_reject=False,
- reason="No evidence available",
- constraint_value=constraint.value,
- positive_confidence=0.0,
- negative_confidence=0.0,
- )
-
- # Calculate average confidence scores
- avg_positive = sum(e.positive_confidence for e in evidence_list) / len(
- evidence_list
- )
- avg_negative = sum(e.negative_confidence for e in evidence_list) / len(
- evidence_list
- )
-
- # PRIMARY REJECTION RULE: High negative evidence
- if avg_negative > self.negative_threshold:
- return RejectionResult(
- should_reject=True,
- reason=f"High negative evidence ({avg_negative:.0%})",
- constraint_value=constraint.value,
- positive_confidence=avg_positive,
- negative_confidence=avg_negative,
- )
-
- # SECONDARY REJECTION RULE: Low positive evidence
- if avg_positive < self.positive_threshold:
- return RejectionResult(
- should_reject=True,
- reason=f"Insufficient positive evidence ({avg_positive:.0%})",
- constraint_value=constraint.value,
- positive_confidence=avg_positive,
- negative_confidence=avg_negative,
- )
-
- # No rejection needed
- return RejectionResult(
- should_reject=False,
- reason="Constraints satisfied",
- constraint_value=constraint.value,
- positive_confidence=avg_positive,
- negative_confidence=avg_negative,
- )
-
- def check_all_constraints(
- self,
- candidate: Candidate,
- constraint_results: Dict[Constraint, List[ConstraintEvidence]],
- ) -> Optional[RejectionResult]:
- """
- Check all constraints for a candidate and return first rejection reason.
-
- Args:
- candidate: The candidate being evaluated
- constraint_results: Dictionary mapping constraints to their evidence
-
- Returns:
- RejectionResult if should reject, None if should accept
- """
- for constraint, evidence_list in constraint_results.items():
- result = self.should_reject_candidate(
- candidate, constraint, evidence_list
- )
-
- if result.should_reject:
- logger.info(
- f"❌ REJECTION: {candidate.name} - {constraint.value} - {result.reason}"
- )
- return result
-
- # No rejections found
- logger.info(f"✓ ACCEPTED: {candidate.name} - All constraints satisfied")
- return None
diff --git a/src/local_deep_research/advanced_search_system/constraint_checking/strict_checker.py b/src/local_deep_research/advanced_search_system/constraint_checking/strict_checker.py
deleted file mode 100644
index 03d53ed8f5..0000000000
--- a/src/local_deep_research/advanced_search_system/constraint_checking/strict_checker.py
+++ /dev/null
@@ -1,264 +0,0 @@
-"""
-Strict constraint checker - example of creating a custom variant.
-
-This implementation is very strict about constraint satisfaction,
-requiring high confidence for all constraints.
-"""
-
-from typing import Dict, List, Tuple
-
-from loguru import logger
-
-from ..candidates.base_candidate import Candidate
-from ..constraints.base_constraint import Constraint, ConstraintType
-from .base_constraint_checker import (
- BaseConstraintChecker,
- ConstraintCheckResult,
-)
-
-
-class StrictChecker(BaseConstraintChecker):
- """
- Strict constraint checker that requires high confidence for all constraints.
-
- This is an example of how to create custom constraint checking variants
- by inheriting from BaseConstraintChecker.
- """
-
- def __init__(
- self,
- *args,
- strict_threshold: float = 0.9, # Very high threshold
- name_pattern_required: bool = True, # NAME_PATTERN constraints are mandatory
- **kwargs,
- ):
- """
- Initialize strict checker.
-
- Args:
- strict_threshold: Very high threshold for all constraints
- name_pattern_required: Whether NAME_PATTERN constraints are mandatory
- """
- super().__init__(*args, **kwargs)
- self.strict_threshold = strict_threshold
- self.name_pattern_required = name_pattern_required
-
- def check_candidate(
- self, candidate: Candidate, constraints: List[Constraint]
- ) -> ConstraintCheckResult:
- """Check candidate with strict requirements."""
- logger.info(f"Checking candidate: {candidate.name} (strict mode)")
-
- constraint_scores = {}
- detailed_results = []
- rejection_reason = None
- should_reject = False
-
- for constraint in constraints:
- # Gather evidence
- evidence_list = self._gather_evidence_for_constraint(
- candidate, constraint
- )
-
- # Calculate score
- score = self._evaluate_constraint_strictly(
- candidate, constraint, evidence_list
- )
-
- # Check for rejection
- reject, reason = self.should_reject_candidate(
- candidate, constraint, evidence_list
- )
-
- if reject and not should_reject:
- should_reject = True
- rejection_reason = reason
-
- # Store results
- constraint_scores[constraint.value] = {
- "total": score,
- "strict_pass": score >= self.strict_threshold,
- "weight": constraint.weight,
- }
-
- detailed_results.append(
- {
- "constraint": constraint.value,
- "score": score,
- "strict_pass": score >= self.strict_threshold,
- "weight": constraint.weight,
- "type": constraint.type.value,
- }
- )
-
- self._log_constraint_result(candidate, constraint, score, {})
-
- # Calculate total score
- if should_reject:
- total_score = 0.0
- else:
- # All constraints must pass strict threshold
- all_pass = all(r["strict_pass"] for r in detailed_results)
- total_score = 1.0 if all_pass else 0.0
-
- logger.info(
- f"Strict evaluation for {candidate.name}: {'PASS' if total_score > 0 else 'FAIL'}"
- )
-
- return ConstraintCheckResult(
- candidate=candidate,
- total_score=total_score,
- constraint_scores=constraint_scores,
- should_reject=should_reject,
- rejection_reason=rejection_reason,
- detailed_results=detailed_results,
- )
-
- def should_reject_candidate(
- self,
- candidate: Candidate,
- constraint: Constraint,
- evidence_data: List[Dict],
- ) -> Tuple[bool, str]:
- """Strict rejection rules."""
- if not evidence_data:
- return True, f"No evidence for constraint '{constraint.value}'"
-
- score = self._evaluate_constraint_strictly(
- candidate, constraint, evidence_data
- )
-
- # Special handling for NAME_PATTERN constraints
- if (
- constraint.type == ConstraintType.NAME_PATTERN
- and self.name_pattern_required
- ):
- if score < 0.95: # Even stricter for name patterns
- return (
- True,
- f"NAME_PATTERN constraint '{constraint.value}' failed strict evaluation",
- )
-
- # General strict threshold
- if score < self.strict_threshold:
- return (
- True,
- f"Constraint '{constraint.value}' below strict threshold ({score:.0%})",
- )
-
- return False, ""
-
- def _evaluate_constraint_strictly(
- self,
- candidate: Candidate,
- constraint: Constraint,
- evidence_list: List[Dict],
- ) -> float:
- """Evaluate constraint with strict criteria."""
- if not evidence_list:
- return 0.0
-
- # For NAME_PATTERN constraints, use direct name checking
- if constraint.type == ConstraintType.NAME_PATTERN:
- return self._check_name_pattern_strictly(
- candidate.name, constraint.value
- )
-
- # For other constraints, use LLM with strict prompt
- combined_evidence = "\n".join(
- [e.get("text", "")[:300] for e in evidence_list[:2]]
- )
-
- prompt = f"""
-STRICT EVALUATION: Does "{candidate.name}" definitely and clearly satisfy: "{constraint.value}"?
-
-Evidence:
-{combined_evidence}
-
-Be very strict. Only return a high score if there is clear, unambiguous evidence.
-
-Score (0.0-1.0):
-"""
-
- try:
- response = self.model.invoke(prompt).content.strip()
- import re
-
- match = re.search(r"(\d*\.?\d+)", response)
- if match:
- return max(0.0, min(float(match.group(1)), 1.0))
- except Exception:
- logger.exception("Error in strict evaluation")
- return 0.5 # Uncertain on error, don't auto-reject
-
- return 0.0
-
- def _check_name_pattern_strictly(
- self, candidate_name: str, pattern_description: str
- ) -> float:
- """Strict name pattern checking."""
- # Example: Check for body parts in name
- if "body part" in pattern_description.lower():
- body_parts = [
- "arm",
- "leg",
- "foot",
- "feet",
- "hand",
- "eye",
- "ear",
- "nose",
- "mouth",
- "tooth",
- "teeth",
- "head",
- "face",
- "neck",
- "back",
- "chest",
- "heart",
- "finger",
- "thumb",
- "toe",
- "knee",
- "elbow",
- "shoulder",
- "spine",
- "bone",
- ]
-
- name_lower = candidate_name.lower()
- for part in body_parts:
- if part in name_lower.split() or part in name_lower:
- logger.info(
- f"✓ Found body part '{part}' in '{candidate_name}'"
- )
- return 1.0
-
- logger.info(f"✗ No body part found in '{candidate_name}'")
- return 0.0
-
- # For other name patterns, use LLM
- prompt = f"""
-Does the name "{candidate_name}" match this pattern: "{pattern_description}"?
-
-Be very strict. Return 1.0 only if it clearly matches, 0.0 otherwise.
-
-Score:
-"""
-
- try:
- response = self.model.invoke(prompt).content.strip()
- import re
-
- match = re.search(r"(\d*\.?\d+)", response)
- if match:
- return max(0.0, min(float(match.group(1)), 1.0))
- except Exception:
- logger.warning(
- f"LLM constraint scoring failed for '{candidate_name}', "
- "returning uncertain score",
- )
- return 0.5
-
- return 0.0
diff --git a/src/local_deep_research/advanced_search_system/constraint_checking/threshold_checker.py b/src/local_deep_research/advanced_search_system/constraint_checking/threshold_checker.py
deleted file mode 100644
index 4dd9276222..0000000000
--- a/src/local_deep_research/advanced_search_system/constraint_checking/threshold_checker.py
+++ /dev/null
@@ -1,213 +0,0 @@
-"""
-Simple threshold-based constraint checker.
-
-This implementation uses simple yes/no threshold checking for constraints,
-making it faster but less nuanced than dual confidence checking.
-"""
-
-from typing import Any
-
-from loguru import logger
-
-from ..candidates.base_candidate import Candidate
-from ..constraints.base_constraint import Constraint
-from .base_constraint_checker import (
- BaseConstraintChecker,
- ConstraintCheckResult,
-)
-
-
-class ThresholdChecker(BaseConstraintChecker):
- """
- Simple threshold-based constraint checker.
-
- This checker:
- 1. Uses simple LLM yes/no responses for constraint satisfaction
- 2. Makes rejection decisions based on simple thresholds
- 3. Faster than dual confidence but less detailed
- """
-
- def __init__(
- self,
- *args,
- satisfaction_threshold: float = 0.7, # Minimum score to consider satisfied
- required_satisfaction_rate: float = 0.8, # % of constraints that must be satisfied
- **kwargs,
- ):
- """
- Initialize threshold checker.
-
- Args:
- satisfaction_threshold: Minimum score for constraint satisfaction
- required_satisfaction_rate: Percentage of constraints that must be satisfied
- """
- super().__init__(*args, **kwargs)
- self.satisfaction_threshold = satisfaction_threshold
- self.required_satisfaction_rate = required_satisfaction_rate
-
- def check_candidate(
- self, candidate: Candidate, constraints: list[Constraint]
- ) -> ConstraintCheckResult:
- """Check candidate using simple threshold analysis."""
- logger.info(f"Checking candidate: {candidate.name} (threshold)")
-
- constraint_scores = {}
- detailed_results = []
- satisfied_count = 0
- total_constraints = len(constraints)
-
- for constraint in constraints:
- # Gather evidence
- evidence_list = self._gather_evidence_for_constraint(
- candidate, constraint
- )
-
- if evidence_list:
- # Simple satisfaction check
- satisfaction_score = self._check_constraint_satisfaction(
- candidate, constraint, evidence_list
- )
-
- is_satisfied = satisfaction_score >= self.satisfaction_threshold
- if is_satisfied:
- satisfied_count += 1
-
- # Store results
- constraint_scores[constraint.value] = {
- "total": satisfaction_score,
- "satisfied": is_satisfied,
- "weight": constraint.weight,
- }
-
- detailed_results.append(
- {
- "constraint": constraint.value,
- "score": satisfaction_score,
- "satisfied": is_satisfied,
- "weight": constraint.weight,
- "type": constraint.type.value,
- }
- )
-
- self._log_constraint_result(
- candidate, constraint, satisfaction_score, {}
- )
-
- else:
- # No evidence - consider unsatisfied
- constraint_scores[constraint.value] = {
- "total": 0.0,
- "satisfied": False,
- "weight": constraint.weight,
- }
-
- detailed_results.append(
- {
- "constraint": constraint.value,
- "score": 0.0,
- "satisfied": False,
- "weight": constraint.weight,
- "type": constraint.type.value,
- }
- )
-
- logger.info(
- f"? {candidate.name} | {constraint.value}: No evidence found"
- )
-
- # Check rejection based on satisfaction rate
- satisfaction_rate = (
- satisfied_count / total_constraints if total_constraints > 0 else 0
- )
- should_reject = satisfaction_rate < self.required_satisfaction_rate
-
- rejection_reason = None
- if should_reject:
- rejection_reason = f"Only {satisfied_count}/{total_constraints} constraints satisfied ({satisfaction_rate:.0%})"
-
- # Calculate total score
- if should_reject:
- total_score = 0.0
- else:
- # Use satisfaction rate as score
- total_score = satisfaction_rate
-
- logger.info(
- f"Final score for {candidate.name}: {total_score:.2%} ({satisfied_count}/{total_constraints} satisfied)"
- )
-
- return ConstraintCheckResult(
- candidate=candidate,
- total_score=total_score,
- constraint_scores=constraint_scores,
- should_reject=should_reject,
- rejection_reason=rejection_reason,
- detailed_results=detailed_results,
- )
-
- def should_reject_candidate(
- self,
- candidate: Candidate,
- constraint: Constraint,
- evidence_data: list[dict[str, Any]],
- ) -> tuple[bool, str]:
- """Simple rejection based on evidence availability and quality."""
- if not evidence_data:
- return (
- True,
- f"No evidence found for constraint '{constraint.value}'",
- )
-
- satisfaction_score = self._check_constraint_satisfaction(
- candidate, constraint, evidence_data
- )
-
- if satisfaction_score < self.satisfaction_threshold:
- return (
- True,
- f"Constraint '{constraint.value}' not satisfied (score: {satisfaction_score:.0%})",
- )
-
- return False, ""
-
- def _check_constraint_satisfaction(
- self,
- candidate: Candidate,
- constraint: Constraint,
- evidence_list: list[dict[str, Any]],
- ) -> float:
- """Check if constraint is satisfied using simple LLM prompt."""
- # Combine evidence texts
- combined_evidence = "\n".join(
- [e.get("text", "")[:200] for e in evidence_list[:3]]
- )
-
- prompt = f"""
-Does the candidate "{candidate.name}" satisfy this constraint: "{constraint.value}"?
-
-Evidence:
-{combined_evidence}
-
-Consider the evidence and respond with a satisfaction score from 0.0 to 1.0 where:
-- 1.0 = Definitely satisfies the constraint
-- 0.5 = Partially satisfies or unclear
-- 0.0 = Definitely does not satisfy the constraint
-
-Score:
-"""
-
- try:
- response = self.model.invoke(prompt).content.strip()
-
- # Extract score
- import re
-
- match = re.search(r"(\d*\.?\d+)", response)
- if match:
- score = float(match.group(1))
- return max(0.0, min(score, 1.0))
-
- except Exception:
- logger.exception("Error checking constraint satisfaction")
-
- return 0.5 # Default to neutral if parsing fails
diff --git a/src/local_deep_research/advanced_search_system/strategies/__init__.py b/src/local_deep_research/advanced_search_system/strategies/__init__.py
index 7b25c0738f..2dc3714f17 100644
--- a/src/local_deep_research/advanced_search_system/strategies/__init__.py
+++ b/src/local_deep_research/advanced_search_system/strategies/__init__.py
@@ -1,45 +1,13 @@
# Search System Strategies Package
-from .adaptive_decomposition_strategy import AdaptiveDecompositionStrategy
from .base_strategy import BaseSearchStrategy
-from .browsecomp_entity_strategy import BrowseCompEntityStrategy
-from .browsecomp_optimized_strategy import BrowseCompOptimizedStrategy
-from .constraint_parallel_strategy import ConstraintParallelStrategy
-from .dual_confidence_strategy import DualConfidenceStrategy
-from .dual_confidence_with_rejection import DualConfidenceWithRejectionStrategy
-from .evidence_based_strategy import EvidenceBasedStrategy
from .focused_iteration_strategy import FocusedIterationStrategy
-from .iterative_reasoning_strategy import IterativeReasoningStrategy
-from .iterdrag_strategy import IterDRAGStrategy
from .mcp_strategy import MCPSearchStrategy
-from .modular_strategy import ModularStrategy
-from .parallel_constrained_strategy import ParallelConstrainedStrategy
-from .parallel_search_strategy import ParallelSearchStrategy
-from .rapid_search_strategy import RapidSearchStrategy
-from .recursive_decomposition_strategy import RecursiveDecompositionStrategy
-from .smart_decomposition_strategy import SmartDecompositionStrategy
from .source_based_strategy import SourceBasedSearchStrategy
-from .standard_strategy import StandardSearchStrategy
__all__ = [
- "AdaptiveDecompositionStrategy",
"BaseSearchStrategy",
- "BrowseCompEntityStrategy",
- "BrowseCompOptimizedStrategy",
- "ConstraintParallelStrategy",
- "DualConfidenceStrategy",
- "DualConfidenceWithRejectionStrategy",
- "EvidenceBasedStrategy",
"FocusedIterationStrategy",
- "IterDRAGStrategy",
- "IterativeReasoningStrategy",
"MCPSearchStrategy",
- "ModularStrategy",
- "ParallelConstrainedStrategy",
- "ParallelSearchStrategy",
- "RapidSearchStrategy",
- "RecursiveDecompositionStrategy",
- "SmartDecompositionStrategy",
"SourceBasedSearchStrategy",
- "StandardSearchStrategy",
]
diff --git a/src/local_deep_research/advanced_search_system/strategies/adaptive_decomposition_strategy.py b/src/local_deep_research/advanced_search_system/strategies/adaptive_decomposition_strategy.py
deleted file mode 100644
index 79c4fe468d..0000000000
--- a/src/local_deep_research/advanced_search_system/strategies/adaptive_decomposition_strategy.py
+++ /dev/null
@@ -1,567 +0,0 @@
-"""
-Adaptive Decomposition Strategy for step-by-step query analysis.
-
-This strategy dynamically adapts its approach based on intermediate findings,
-making decisions at each step rather than decomposing everything upfront.
-"""
-
-from dataclasses import dataclass
-from enum import Enum
-from typing import Any, Dict, List, Optional
-
-from langchain_core.language_models import BaseChatModel
-from loguru import logger
-
-from ...utilities.search_utilities import format_findings, remove_think_tags
-from ..findings.repository import FindingsRepository
-from ..questions.standard_question import StandardQuestionGenerator
-from .base_strategy import BaseSearchStrategy
-from .source_based_strategy import SourceBasedSearchStrategy
-
-
-class StepType(Enum):
- """Types of steps in the adaptive process."""
-
- CONSTRAINT_EXTRACTION = "constraint_extraction"
- INITIAL_SEARCH = "initial_search"
- VERIFICATION = "verification"
- REFINEMENT = "refinement"
- SYNTHESIS = "synthesis"
-
-
-@dataclass
-class StepResult:
- """Result from a single adaptive step."""
-
- step_type: StepType
- description: str
- findings: Dict
- next_action: Optional[str] = None
- confidence: float = 0.0
-
-
-class AdaptiveDecompositionStrategy(BaseSearchStrategy):
- """
- A strategy that adapts its decomposition based on intermediate findings.
-
- Instead of decomposing everything upfront, it takes a step-by-step approach,
- using each step's findings to inform the next action.
- """
-
- def __init__(
- self,
- model: BaseChatModel,
- search: Any,
- all_links_of_system: List[Any],
- max_steps: int = 15,
- min_confidence: float = 0.8,
- source_search_iterations: int = 2,
- source_questions_per_iteration: int = 20,
- settings_snapshot: dict | None = None,
- ):
- """Initialize the adaptive decomposition strategy.
-
- Args:
- model: The language model to use
- search: The search engine instance
- all_links_of_system: List to store all encountered links
- max_steps: Maximum steps to prevent infinite loops
- min_confidence: Minimum confidence to consider answer complete
- source_search_iterations: Iterations for source-based searches
- source_questions_per_iteration: Questions per iteration for source-based searches
- settings_snapshot: Optional settings snapshot for configuration
- """
- super().__init__(
- all_links_of_system, settings_snapshot=settings_snapshot
- )
- self.model = model
- self.search = search
- self.max_steps = max_steps
- self.min_confidence = min_confidence
- self.source_search_iterations = source_search_iterations
- self.source_questions_per_iteration = source_questions_per_iteration
- self.question_generator = StandardQuestionGenerator(model)
- self.findings_repository = FindingsRepository(model)
- self.step_results: List[StepResult] = []
- self.working_knowledge = {}
-
- def analyze_topic(self, query: str) -> Dict:
- """Analyze a topic using adaptive decomposition.
-
- Args:
- query: The research query to analyze
-
- Returns:
- Dictionary containing analysis results
- """
- self.all_links_of_system.clear()
- self.questions_by_iteration = []
- self.findings = []
- self.step_results = []
- self.working_knowledge = {
- "original_query": query,
- "constraints": [],
- "candidates": [],
- "verified_facts": [],
- "uncertainties": [],
- }
-
- # Progress callback for UI
- if self.progress_callback:
- self.progress_callback(
- "Starting adaptive analysis",
- 1,
- {"phase": "init", "strategy": "adaptive_decomposition"},
- )
-
- logger.info(f"Starting adaptive analysis for: {query}")
-
- # Start with constraint extraction
- current_step = 0
- while current_step < self.max_steps:
- # Decide next step based on current knowledge
- next_step = self._decide_next_step(query, current_step)
-
- if next_step is None:
- break
-
- logger.info(f"Step {current_step + 1}: {next_step.step_type.value}")
-
- # Update progress
- if self.progress_callback:
- self.progress_callback(
- f"Step {current_step + 1}: {next_step.step_type.value}",
- int((current_step / self.max_steps) * 80) + 10,
- {
- "phase": "adaptive_step",
- "step": current_step + 1,
- "step_type": next_step.step_type.value,
- },
- )
-
- # Execute the step
- step_result = self._execute_step(next_step, query)
- self.step_results.append(step_result)
-
- # Check if we have a confident answer
- if step_result.confidence >= self.min_confidence:
- logger.info(
- f"Confident answer found (confidence: {step_result.confidence})"
- )
- break
-
- current_step += 1
-
- # Final synthesis of all findings
- final_result = self._synthesize_findings(query)
-
- # Update progress
- if self.progress_callback:
- self.progress_callback(
- "Analysis complete",
- 100,
- {"phase": "complete", "strategy": "adaptive_decomposition"},
- )
-
- return final_result
-
- def _decide_next_step(
- self, query: str, _step_count: int
- ) -> Optional[StepResult]:
- """Decide the next step based on current knowledge.
-
- Args:
- query: The original query
- step_count: Current step number
-
- Returns:
- Next step to execute, or None if complete
- """
- # Format current knowledge for analysis
- knowledge_summary = f"""
-Original Query: {query}
-
-Current Knowledge:
-- Extracted Constraints: {self.working_knowledge.get("constraints", [])}
-- Candidate Locations: {self.working_knowledge.get("candidates", [])}
-- Verified Facts: {self.working_knowledge.get("verified_facts", [])}
-- Uncertainties: {self.working_knowledge.get("uncertainties", [])}
-
-Previous Steps: {[s.step_type.value for s in self.step_results]}
-"""
-
- prompt = f"""Based on the current knowledge, decide the next best action.
-
-{knowledge_summary}
-
-What should be the next step? Options:
-1. CONSTRAINT_EXTRACTION - Extract specific constraints from the query
-2. INITIAL_SEARCH - Perform broad search for candidates
-3. VERIFICATION - Verify specific facts about candidates
-4. REFINEMENT - Refine search based on new information
-5. SYNTHESIS - We have enough information to answer
-
-Respond with:
-NEXT_STEP: [step type]
-DESCRIPTION: [what specifically to do]
-REASONING: [why this is the best next step]
-CONFIDENCE: [0-1 score of how confident we are in the current answer]
-"""
-
- response = self.model.invoke(prompt)
- content = remove_think_tags(str(response.content))
-
- # Parse response
- lines = content.strip().split("\n")
- next_step_type = None
- description = ""
- confidence = 0.0
-
- for line in lines:
- if line.startswith("NEXT_STEP:"):
- step_str = line.split(":", 1)[1].strip()
- try:
- next_step_type = StepType[step_str]
- except KeyError:
- # Try to match partial
- for step_type in StepType:
- if step_type.value in step_str.lower():
- next_step_type = step_type
- break
- elif line.startswith("DESCRIPTION:"):
- description = line.split(":", 1)[1].strip()
- elif line.startswith("CONFIDENCE:"):
- try:
- confidence = float(line.split(":", 1)[1].strip())
- except ValueError:
- confidence = 0.0
-
- if next_step_type is None:
- return None
-
- return StepResult(
- step_type=next_step_type,
- description=description,
- findings={},
- confidence=confidence,
- )
-
- def _execute_step(self, step: StepResult, query: str) -> StepResult:
- """Execute a specific step in the adaptive process.
-
- Args:
- step: The step to execute
- query: The original query
-
- Returns:
- Updated step result with findings
- """
- if step.step_type == StepType.CONSTRAINT_EXTRACTION:
- return self._extract_constraints(query)
- if step.step_type == StepType.INITIAL_SEARCH:
- return self._perform_initial_search(step.description)
- if step.step_type == StepType.VERIFICATION:
- return self._verify_candidates(step.description)
- if step.step_type == StepType.REFINEMENT:
- return self._refine_search(step.description)
- if step.step_type == StepType.SYNTHESIS:
- return self._synthesize_current_knowledge(query)
- return step
-
- def _extract_constraints(self, query: str) -> StepResult:
- """Extract specific constraints and clues from the query.
-
- Args:
- query: The original query
-
- Returns:
- Step result with extracted constraints
- """
- prompt = f"""Extract all specific constraints and clues from this query:
-
-Query: {query}
-
-List each constraint/clue separately and explain why it's important:
-"""
-
- response = self.model.invoke(prompt)
- content = remove_think_tags(str(response.content))
-
- # Parse constraints
- constraints = []
- lines = content.strip().split("\n")
- for line in lines:
- if line.strip() and (line[0].isdigit() or line.startswith("-")):
- constraints.append(line.strip())
-
- self.working_knowledge["constraints"] = constraints
-
- return StepResult(
- step_type=StepType.CONSTRAINT_EXTRACTION,
- description="Extract constraints from query",
- findings={"constraints": constraints},
- confidence=0.0,
- )
-
- def _perform_initial_search(self, description: str) -> StepResult:
- """Perform initial search based on extracted constraints.
-
- Args:
- description: Search description
-
- Returns:
- Step result with search findings
- """
- # Use source-based strategy for the search
- source_strategy = SourceBasedSearchStrategy(
- model=self.model,
- search=self.search,
- all_links_of_system=self.all_links_of_system,
- include_text_content=True,
- use_cross_engine_filter=True,
- use_atomic_facts=True,
- )
-
- source_strategy.max_iterations = 1 # Quick initial search
- source_strategy.questions_per_iteration = 10
-
- if self.progress_callback:
- source_strategy.set_progress_callback(self.progress_callback)
-
- results = source_strategy.analyze_topic(description)
-
- # Extract candidate locations from results
- candidates = self._extract_candidates_from_results(results)
- self.working_knowledge["candidates"] = candidates
-
- return StepResult(
- step_type=StepType.INITIAL_SEARCH,
- description=description,
- findings={"candidates": candidates, "raw_results": results},
- confidence=0.2,
- )
-
- def _verify_candidates(self, description: str) -> StepResult:
- """Verify specific facts about candidate locations.
-
- Args:
- description: Verification description
-
- Returns:
- Step result with verification findings
- """
- # Perform targeted search for verification
- source_strategy = SourceBasedSearchStrategy(
- model=self.model,
- search=self.search,
- all_links_of_system=self.all_links_of_system,
- include_text_content=True,
- use_cross_engine_filter=True,
- use_atomic_facts=True,
- )
-
- source_strategy.max_iterations = 1
- source_strategy.questions_per_iteration = 15
-
- if self.progress_callback:
- source_strategy.set_progress_callback(self.progress_callback)
-
- results = source_strategy.analyze_topic(description)
-
- # Update verified facts
- verified_facts = self._extract_verified_facts(results)
- self.working_knowledge["verified_facts"].extend(verified_facts)
-
- # Calculate confidence based on verification
- confidence = self._calculate_confidence()
-
- return StepResult(
- step_type=StepType.VERIFICATION,
- description=description,
- findings={"verified_facts": verified_facts},
- confidence=confidence,
- )
-
- def _refine_search(self, description: str) -> StepResult:
- """Refine search based on accumulated knowledge.
-
- Args:
- description: Refinement description
-
- Returns:
- Step result with refined findings
- """
- # Similar to verification but with more targeted approach
- return self._verify_candidates(description)
-
- def _synthesize_current_knowledge(self, query: str) -> StepResult:
- """Synthesize current knowledge into an answer.
-
- Args:
- query: The original query
-
- Returns:
- Step result with synthesized answer
- """
- knowledge_summary = f"""
-Original Query: {query}
-
-Constraints: {self.working_knowledge["constraints"]}
-Candidates: {self.working_knowledge["candidates"]}
-Verified Facts: {self.working_knowledge["verified_facts"]}
-"""
-
- prompt = f"""Based on all the information gathered, provide the answer:
-
-{knowledge_summary}
-
-Provide:
-1. The specific answer to the query
-2. Supporting evidence for the answer
-3. Confidence level (0-1)
-"""
-
- response = self.model.invoke(prompt)
- content = remove_think_tags(str(response.content))
-
- return StepResult(
- step_type=StepType.SYNTHESIS,
- description="Final synthesis",
- findings={"answer": content},
- confidence=0.9,
- )
-
- def _synthesize_findings(self, query: str) -> Dict:
- """Synthesize all findings into final result.
-
- Args:
- query: The original query
-
- Returns:
- Final results dictionary
- """
- # Compile all findings
- all_findings = []
- all_links = []
- all_questions = []
-
- for step in self.step_results:
- finding = {
- "phase": f"{step.step_type.value} (Step {self.step_results.index(step) + 1})",
- "content": step.description,
- "findings": step.findings,
- "confidence": step.confidence,
- "timestamp": self._get_timestamp(),
- }
- all_findings.append(finding)
-
- # Extract links and questions from raw results if available
- if "raw_results" in step.findings:
- raw = step.findings["raw_results"]
- if "all_links_of_system" in raw:
- all_links.extend(raw["all_links_of_system"])
- if "questions_by_iteration" in raw:
- all_questions.extend(
- raw.get("questions_by_iteration", {}).values()
- )
-
- # Get final answer
- final_answer = "No confident answer found."
- for step in reversed(self.step_results):
- if (
- step.step_type == StepType.SYNTHESIS
- and "answer" in step.findings
- ):
- final_answer = step.findings["answer"]
- break
-
- # Format questions dictionary
- questions_dict = {}
- for i, questions in enumerate(all_questions):
- if isinstance(questions, list):
- questions_dict[i + 1] = questions
-
- formatted_findings = format_findings(
- all_findings, final_answer, questions_dict
- )
-
- return {
- "current_knowledge": final_answer,
- "formatted_findings": formatted_findings,
- "findings": all_findings,
- "iterations": len(self.step_results),
- "questions_by_iteration": questions_dict,
- "all_links_of_system": all_links,
- "sources": all_links,
- "step_results": [step.__dict__ for step in self.step_results],
- "strategy": "adaptive_decomposition",
- "working_knowledge": self.working_knowledge,
- "questions": {
- "total": sum(len(q) for q in questions_dict.values()),
- "by_iteration": questions_dict,
- },
- }
-
- def _extract_candidates_from_results(self, results: Dict) -> List[str]:
- """Extract candidate locations from search results."""
- candidates = []
- if "current_knowledge" in results:
- # Use LLM to extract location names
- prompt = f"""Extract any location names mentioned in this text:
-
-{results["current_knowledge"][:1000]}
-
-List only location names, one per line:"""
-
- response = self.model.invoke(prompt)
- content = remove_think_tags(str(response.content))
-
- for line in content.strip().split("\n"):
- if line.strip():
- candidates.append(line.strip())
-
- return candidates
-
- def _extract_verified_facts(self, results: Dict) -> List[str]:
- """Extract verified facts from search results."""
- facts = []
- if "current_knowledge" in results:
- # Use LLM to extract verified facts
- prompt = f"""Extract specific verified facts from this text:
-
-{results["current_knowledge"][:1000]}
-
-List only confirmed facts, one per line:"""
-
- response = self.model.invoke(prompt)
- content = remove_think_tags(str(response.content))
-
- for line in content.strip().split("\n"):
- if line.strip():
- facts.append(line.strip())
-
- return facts
-
- def _calculate_confidence(self) -> float:
- """Calculate confidence based on verified facts vs constraints."""
- if not self.working_knowledge["constraints"]:
- return 0.0
-
- verified_count = len(self.working_knowledge["verified_facts"])
- constraint_count = len(self.working_knowledge["constraints"])
-
- # Simple ratio with some adjustments
- base_confidence = verified_count / constraint_count
-
- # Boost if we have specific candidates
- if self.working_knowledge["candidates"]:
- base_confidence += 0.1
-
- # Cap at 0.95 to leave room for synthesis
- return min(base_confidence, 0.95)
-
- def _get_timestamp(self) -> str:
- """Get current timestamp for findings."""
- from datetime import datetime, timezone
-
- return datetime.now(timezone.utc).isoformat()
diff --git a/src/local_deep_research/advanced_search_system/strategies/browsecomp_entity_strategy.py b/src/local_deep_research/advanced_search_system/strategies/browsecomp_entity_strategy.py
deleted file mode 100644
index 1efd9b00f2..0000000000
--- a/src/local_deep_research/advanced_search_system/strategies/browsecomp_entity_strategy.py
+++ /dev/null
@@ -1,1051 +0,0 @@
-"""
-BrowseComp Entity-Focused Search Strategy
-
-This strategy is specifically designed for BrowseComp questions that require finding
-specific entities (companies, people, events) that match multiple constraints.
-
-Key features:
-1. Entity extraction and progressive search
-2. Knowledge graph building approach
-3. Multi-constraint verification with caching
-4. Specialized search patterns for different entity types
-"""
-
-import asyncio
-import json
-import re
-from collections import defaultdict
-from dataclasses import dataclass
-from typing import Dict, List, Tuple
-
-from loguru import logger
-
-from ...database.thread_local_session import thread_cleanup
-from ...utilities.json_utils import extract_json, get_llm_response_text
-from ...utilities.search_cache import get_search_cache
-from ..candidate_exploration import ConstraintGuidedExplorer
-from ..constraint_checking import DualConfidenceChecker
-from ..constraints import Constraint, ConstraintAnalyzer
-from ..questions import BrowseCompQuestionGenerator
-from .base_strategy import BaseSearchStrategy
-
-
-@dataclass
-class EntityCandidate:
- """Enhanced candidate with entity-specific metadata."""
-
- name: str
- entity_type: str # company, person, event, etc.
- aliases: List[str] = None
- properties: Dict[str, any] = None
- sources: List[str] = None
- confidence: float = 0.0
- constraint_matches: Dict[str, float] = None
-
- def __post_init__(self):
- self.aliases = self.aliases or []
- self.properties = self.properties or {}
- self.sources = self.sources or []
- self.constraint_matches = self.constraint_matches or {}
-
-
-MAX_LOCAL_CACHE = 200 # Cap in-memory search cache to prevent unbounded growth
-
-
-class EntityKnowledgeGraph:
- """Build and maintain knowledge about discovered entities."""
-
- def __init__(self):
- self.entities = {} # name -> EntityCandidate
- self.constraint_evidence = defaultdict(
- dict
- ) # constraint -> entity -> evidence
- self.search_cache = {} # query -> results
-
- def add_entity(self, entity: EntityCandidate):
- """Add or update an entity in the knowledge graph."""
- if entity.name in self.entities:
- # Merge information
- existing = self.entities[entity.name]
- existing.aliases.extend(entity.aliases)
- existing.aliases = list(set(existing.aliases))
- existing.properties.update(entity.properties)
- existing.sources.extend(entity.sources)
- existing.sources = list(set(existing.sources))
- existing.constraint_matches.update(entity.constraint_matches)
- else:
- self.entities[entity.name] = entity
-
- def add_constraint_evidence(
- self, constraint: str, entity_name: str, evidence: Dict
- ):
- """Add evidence for a constraint-entity pair."""
- self.constraint_evidence[constraint][entity_name] = evidence
-
- def get_entities_by_constraint(
- self, constraint: str, min_confidence: float = 0.5
- ) -> List[EntityCandidate]:
- """Get entities that match a constraint above confidence threshold."""
- matching = []
- for entity in self.entities.values():
- if constraint in entity.constraint_matches:
- if entity.constraint_matches[constraint] >= min_confidence:
- matching.append(entity)
- return sorted(
- matching,
- key=lambda e: e.constraint_matches.get(constraint, 0),
- reverse=True,
- )
-
-
-class BrowseCompEntityStrategy(BaseSearchStrategy):
- """
- Entity-focused search strategy for BrowseComp questions.
-
- This strategy:
- 1. Extracts key entities from the query
- 2. Performs broad entity discovery searches
- 3. Builds a knowledge graph of candidates
- 4. Progressively verifies constraints
- 5. Uses caching to avoid redundant searches
- """
-
- def __init__(
- self,
- model,
- search,
- all_links_of_system=None,
- settings_snapshot=None,
- **kwargs,
- ):
- super().__init__(
- all_links_of_system=all_links_of_system,
- settings_snapshot=settings_snapshot,
- )
-
- # Store model and search engine
- self.model = model
- self.search_engine = search
-
- # Initialize components that depend on model/search
- if self.model:
- self.constraint_analyzer = ConstraintAnalyzer(model=self.model)
- self.question_generator = BrowseCompQuestionGenerator(
- model=self.model
- )
- else:
- logger.warning("No model provided to BrowseCompEntityStrategy")
-
- self.knowledge_graph = EntityKnowledgeGraph()
-
- # Initialize constraint checker with entity-aware settings
- if self.model:
- self.constraint_checker = DualConfidenceChecker(
- model=self.model,
- evidence_gatherer=self._gather_entity_evidence,
- negative_threshold=0.3, # More lenient for entities
- positive_threshold=0.4,
- uncertainty_penalty=0.1,
- negative_weight=1.0,
- )
-
- # Initialize specialized explorer
- if self.search_engine and self.model:
- self.explorer = ConstraintGuidedExplorer(
- search_engine=self.search_engine, model=self.model
- )
-
- # Entity type patterns
- self.entity_patterns = {
- "company": [
- "company",
- "corporation",
- "group",
- "firm",
- "business",
- "conglomerate",
- ],
- "person": ["person", "individual", "character", "figure", "people"],
- "event": [
- "event",
- "incident",
- "occurrence",
- "game",
- "match",
- "competition",
- ],
- "location": [
- "place",
- "location",
- "city",
- "country",
- "region",
- "area",
- ],
- "product": ["product", "item", "device", "software", "app", "tool"],
- }
-
- async def search(
- self,
- query: str,
- search_engines: List[str] = None,
- progress_callback=None,
- **kwargs,
- ) -> Tuple[str, Dict]:
- """Execute entity-focused search strategy."""
- try:
- logger.info(f"🎯 Starting BrowseComp Entity Search for: {query}")
-
- # Phase 1: Constraint and entity analysis
- if progress_callback:
- progress_callback(
- {
- "phase": "entity_analysis",
- "progress": 10,
- "message": "Analyzing query for entities and constraints",
- }
- )
-
- constraints = self.constraint_analyzer.extract_constraints(query)
- entity_type = self._identify_entity_type(query)
- logger.info(
- f"Identified entity type: {entity_type}, {len(constraints)} constraints"
- )
-
- # Phase 2: Initial entity discovery
- if progress_callback:
- progress_callback(
- {
- "phase": "entity_discovery",
- "progress": 25,
- "message": f"Searching for {entity_type} entities",
- }
- )
-
- initial_entities = await self._discover_entities(
- query,
- entity_type,
- constraints[:2], # Use first 2 constraints for initial search
- )
- logger.info(f"Discovered {len(initial_entities)} initial entities")
-
- # Phase 3: Progressive constraint verification
- best_candidate = None
- iteration = 0
- max_iterations = 10
-
- while iteration < max_iterations:
- iteration += 1
-
- if progress_callback:
- progress_callback(
- {
- "phase": "constraint_verification",
- "progress": 25 + (iteration * 50 / max_iterations),
- "message": f"Verifying constraints (iteration {iteration}/{max_iterations})",
- }
- )
-
- # Generate targeted searches based on current knowledge
- questions = self.question_generator.generate_questions(
- current_knowledge=self._summarize_knowledge(),
- query=query,
- questions_per_iteration=5,
- iteration=iteration,
- )
-
- # Search for evidence
- new_entities = await self._search_with_questions(
- questions, entity_type
- )
-
- # Add to knowledge graph
- for entity in new_entities:
- self.knowledge_graph.add_entity(entity)
-
- # Evaluate all entities against constraints
- evaluated = await self._evaluate_entities(constraints)
-
- # Check for high-confidence matches
- if evaluated:
- best_candidate = evaluated[0]
- if best_candidate.confidence > 0.8:
- logger.info(
- f"✅ Found high-confidence match: {best_candidate.name} ({best_candidate.confidence:.2%})"
- )
- break
-
- # Early stopping if no progress
- if iteration > 3 and not self.knowledge_graph.entities:
- logger.warning(
- "No entities found after 3 iterations, stopping"
- )
- break
-
- # Phase 4: Generate final answer
- if progress_callback:
- progress_callback(
- {
- "phase": "answer_generation",
- "progress": 90,
- "message": "Generating final answer",
- }
- )
-
- if best_candidate and best_candidate.confidence > 0.5:
- answer = await self._generate_entity_answer(
- query, best_candidate, constraints
- )
- else:
- answer = await self._generate_uncertain_answer(
- query, evaluated[:3] if evaluated else []
- )
-
- # Prepare metadata
- metadata = {
- "strategy": "browsecomp_entity",
- "entity_type": entity_type,
- "entities_discovered": len(self.knowledge_graph.entities),
- "iterations": iteration,
- "best_candidate": best_candidate.name
- if best_candidate
- else None,
- "confidence": best_candidate.confidence
- if best_candidate
- else 0.0,
- "constraint_count": len(constraints),
- "cached_searches": len(self.knowledge_graph.search_cache),
- }
-
- return answer, metadata
-
- except Exception:
- logger.exception("Error in BrowseComp entity search")
- return "Search failed", {"error": "Search failed"}
-
- def _identify_entity_type(self, query: str) -> str:
- """Identify what type of entity we're looking for."""
- query_lower = query.lower()
-
- for entity_type, keywords in self.entity_patterns.items():
- if any(keyword in query_lower for keyword in keywords):
- return entity_type
-
- # Default based on common patterns
- if "who" in query_lower:
- return "person"
- if "which" in query_lower:
- return "product"
- if "what" in query_lower and "company" in query_lower:
- return "company"
- return "entity"
-
- async def _discover_entities(
- self,
- query: str,
- entity_type: str,
- initial_constraints: List[Constraint],
- ) -> List[EntityCandidate]:
- """Discover initial entity candidates."""
- entities = []
-
- # Generate entity-focused search queries
- search_queries = self._generate_entity_searches(
- entity_type, initial_constraints
- )
-
- # Execute searches in parallel
- search_tasks = []
- for search_query in search_queries[:5]: # Limit initial searches
- if search_query not in self.knowledge_graph.search_cache:
- search_tasks.append(self._cached_search(search_query))
-
- results = await asyncio.gather(*search_tasks)
-
- # Extract entities from results
- for query_results in results:
- extracted = await self._extract_entities_from_results(
- query_results, entity_type
- )
- entities.extend(extracted)
-
- return entities
-
- def _generate_entity_searches(
- self, entity_type: str, constraints: List[Constraint]
- ) -> List[str]:
- """Generate search queries for entity discovery."""
- searches = []
-
- # Type-specific base queries
- if entity_type == "company":
- searches.extend(
- [
- "largest companies conglomerates groups",
- "major corporation multinational business",
- "company group founded",
- ]
- )
- elif entity_type == "person":
- searches.extend(
- [
- "famous people individuals",
- "notable person character",
- "who known for",
- ]
- )
- elif entity_type == "event":
- searches.extend(
- [
- "major events competitions",
- "historical event game match",
- "significant occurrence",
- ]
- )
-
- # Add constraint-based searches
- for constraint in constraints:
- if constraint.type.value == "TEMPORAL":
- # Extract years/dates
- years = re.findall(r"\b(19\d{2}|20\d{2})\b", constraint.value)
- for year in years:
- searches.append(f"{entity_type} {year}")
- elif constraint.type.value == "LOCATION":
- # Extract location names
- locations = re.findall(
- r"\b[A-Z][a-z]+(?:\s+[A-Z][a-z]+)*\b", constraint.value
- )
- for location in locations:
- searches.append(f"{entity_type} {location}")
- elif constraint.type.value == "STATISTIC":
- # Extract numbers
- numbers = re.findall(r"\b\d+\b", constraint.value)
- for number in numbers:
- searches.append(f"{entity_type} {number}")
-
- return searches
-
- async def _extract_entities_from_results(
- self, results: List[Dict], entity_type: str
- ) -> List[EntityCandidate]:
- """Extract entity candidates from search results."""
- if not results:
- return []
-
- # Use LLM to extract entities
- results_text = "\n".join(
- [
- f"- {r.get('title', '')}: {r.get('snippet', '')[:200]}"
- for r in results[:10]
- ]
- )
-
- prompt = f"""Extract {entity_type} entities from these search results.
-
-Search Results:
-{results_text}
-
-For each entity found, provide:
-1. Name (official/full name)
-2. Aliases (other names, abbreviations)
-3. Key properties (founding year, location, size, etc.)
-
-Format as JSON:
-[
- {{
- "name": "Entity Name",
- "aliases": ["alias1", "alias2"],
- "properties": {{"key": "value"}}
- }}
-]
-
-Return only entities that are clearly {entity_type} entities."""
-
- response = await self.model.ainvoke(prompt)
- response_text = get_llm_response_text(response)
- entities_data = extract_json(response_text, expected_type=list)
-
- if entities_data is None:
- logger.warning("Failed to parse entity extraction response")
- return []
-
- entities = []
- for data in entities_data:
- entity = EntityCandidate(
- name=data["name"],
- entity_type=entity_type,
- aliases=data.get("aliases", []),
- properties=data.get("properties", {}),
- sources=[r.get("url", "") for r in results[:3]],
- )
- entities.append(entity)
-
- return entities
-
- async def _search_with_questions(
- self, questions: List[str], entity_type: str
- ) -> List[EntityCandidate]:
- """Search using generated questions and extract entities."""
- all_entities = []
-
- # Execute searches
- search_tasks = []
- for question in questions:
- if question not in self.knowledge_graph.search_cache:
- search_tasks.append(self._cached_search(question))
-
- results = await asyncio.gather(*search_tasks)
-
- # Extract entities
- for query_results in results:
- entities = await self._extract_entities_from_results(
- query_results, entity_type
- )
- all_entities.extend(entities)
-
- return all_entities
-
- async def _evaluate_entities(
- self, constraints: List[Constraint]
- ) -> List[EntityCandidate]:
- """Evaluate all entities against constraints."""
- evaluated = []
-
- for entity_name, entity in self.knowledge_graph.entities.items():
- # Check each constraint
- total_score = 0.0
- constraint_scores = {}
-
- for constraint in constraints:
- # Check if we already have evidence for this constraint-entity pair
- if constraint.value in self.knowledge_graph.constraint_evidence:
- if (
- entity_name
- in self.knowledge_graph.constraint_evidence[
- constraint.value
- ]
- ):
- evidence = self.knowledge_graph.constraint_evidence[
- constraint.value
- ][entity_name]
- score = evidence.get("score", 0.0)
- else:
- # Gather new evidence
- score = await self._verify_entity_constraint(
- entity, constraint
- )
- else:
- score = await self._verify_entity_constraint(
- entity, constraint
- )
-
- constraint_scores[constraint.value] = score
- total_score += score * constraint.weight
-
- # Update entity with scores
- entity.constraint_matches = constraint_scores
- entity.confidence = total_score / sum(c.weight for c in constraints)
-
- if entity.confidence > 0.3: # Only keep reasonable candidates
- evaluated.append(entity)
-
- # Sort by confidence
- return sorted(evaluated, key=lambda e: e.confidence, reverse=True)
-
- async def _verify_entity_constraint(
- self, entity: EntityCandidate, constraint: Constraint
- ) -> float:
- """Verify if an entity satisfies a constraint."""
- # Build targeted search query
- search_terms = [entity.name] + entity.aliases[:2]
- constraint_terms = self._extract_constraint_terms(constraint)
-
- best_score = 0.0
- for term in search_terms:
- query = f'"{term}" {" ".join(constraint_terms)}'
-
- # Search for evidence
- results = await self._cached_search(query)
-
- if results:
- # Quick verification with LLM
- evidence_text = " ".join(
- [r.get("snippet", "") for r in results[:3]]
- )
-
- prompt = f"""Does {entity.name} satisfy this constraint?
-
-Constraint: {constraint.description}
-Evidence: {evidence_text}
-
-Answer with a confidence score from 0.0 to 1.0 and brief explanation.
-Format: SCORE: X.X | REASON: explanation"""
-
- response = await self.model.ainvoke(prompt)
- content = response.content
-
- # Extract score
- score_match = re.search(r"SCORE:\s*([\d.]+)", content)
- if score_match:
- score = float(score_match.group(1))
- best_score = max(best_score, score)
-
- # Cache the evidence
- self.knowledge_graph.add_constraint_evidence(
- constraint.value,
- entity.name,
- {
- "score": score,
- "evidence": evidence_text,
- "reason": content,
- },
- )
-
- return best_score
-
- def _extract_constraint_terms(self, constraint: Constraint) -> List[str]:
- """Extract searchable terms from a constraint."""
- terms = []
-
- # Remove common prefixes
- value = constraint.value
- for prefix in ["The answer must", "Must be", "Should be", "Is"]:
- if value.startswith(prefix):
- value = value[len(prefix) :].strip()
- break
-
- # Extract specific terms based on constraint type
- if constraint.type.value == "TEMPORAL":
- # Extract years
- terms.extend(re.findall(r"\b(19\d{2}|20\d{2})\b", value))
- elif constraint.type.value == "STATISTIC":
- # Extract numbers
- terms.extend(re.findall(r"\b\d+\b", value))
- elif constraint.type.value == "LOCATION":
- # Extract proper nouns
- terms.extend(
- re.findall(r"\b[A-Z][a-z]+(?:\s+[A-Z][a-z]+)*\b", value)
- )
-
- # Add key descriptive words
- words = value.split()
- for word in words:
- if len(word) > 4 and word.lower() not in [
- "must",
- "should",
- "would",
- "could",
- ]:
- terms.append(word)
-
- return terms[:5] # Limit to avoid overly long queries
-
- def extract_entity_candidates(
- self, constraints: List[Constraint]
- ) -> List[str]:
- """
- Extract potential entity names using constraint analysis.
- Implements progressive entity discovery from improvement strategy.
- """
- candidates = []
-
- for constraint in constraints:
- # Look for proper nouns (likely entity names)
- proper_nouns = re.findall(
- r"\b[A-Z][a-z]+(?:\s+[A-Z][a-z]+)*\b", constraint.value
- )
- candidates.extend(proper_nouns)
-
- # Look for company name patterns
- company_patterns = [
- r"([A-Z][a-z]+(?:\s+[A-Z][a-z]+)*)\s+(?:Group|Inc|Ltd|Corp|Company|Corporation)",
- r"([A-Z][a-z]+(?:-[A-Z][a-z]+)*)\s+(?:Group|Inc|Ltd|Corp)",
- r"([A-Z]{2,}(?:-[A-Z]{2,})*)", # Acronyms like PRAN-RFL
- ]
-
- for pattern in company_patterns:
- matches = re.findall(pattern, constraint.value)
- candidates.extend(matches)
-
- # Remove duplicates and sort by specificity
- unique_candidates = list(set(candidates))
- return sorted(
- unique_candidates, key=self.entity_specificity, reverse=True
- )
-
- def entity_specificity(self, entity: str) -> float:
- """
- Score entity specificity for search prioritization.
- Higher scores = more specific entities to search first.
- """
- score = 0.0
-
- # Longer names are typically more specific
- score += len(entity) * 0.1
-
- # Multiple words indicate more specificity
- word_count = len(entity.split())
- score += word_count * 2.0
-
- # Company suffixes indicate high specificity
- company_suffixes = [
- "Group",
- "Inc",
- "Ltd",
- "Corp",
- "Corporation",
- "Company",
- "Conglomerate",
- ]
- if any(suffix in entity for suffix in company_suffixes):
- score += 10.0
-
- # Hyphenated names (like PRAN-RFL) are often specific
- if "-" in entity:
- score += 5.0
-
- # All caps acronyms are specific
- if entity.isupper() and len(entity) >= 3:
- score += 8.0
-
- return score
-
- def _gather_entity_evidence(self, candidate, constraint):
- """Evidence gatherer function for constraint checker."""
- # Convert to EntityCandidate if needed
- if not isinstance(candidate, EntityCandidate):
- entity = EntityCandidate(
- name=candidate.name
- if hasattr(candidate, "name")
- else str(candidate),
- entity_type="unknown",
- )
- else:
- entity = candidate
-
- # Check cache first
- if constraint.value in self.knowledge_graph.constraint_evidence:
- if (
- entity.name
- in self.knowledge_graph.constraint_evidence[constraint.value]
- ):
- evidence_data = self.knowledge_graph.constraint_evidence[
- constraint.value
- ][entity.name]
- return [
- {
- "text": evidence_data.get("evidence", ""),
- "source": "cache",
- "confidence": evidence_data.get("score", 0.5),
- }
- ]
-
- # Generate search query
- constraint_terms = self._extract_constraint_terms(constraint)
- query = f'"{entity.name}" {" ".join(constraint_terms)}'
-
- # Search
- results = (
- self.search_engine.run(query)
- if hasattr(self.search_engine, "run")
- else []
- )
-
- # Convert to evidence format
- evidence = []
- for i, result in enumerate(results[:3]):
- evidence.append(
- {
- "text": result.get("snippet", ""),
- "source": result.get("url", f"result_{i}"),
- "confidence": 0.7 - (i * 0.1),
- }
- )
-
- return evidence
-
- def _summarize_knowledge(self) -> str:
- """Summarize current knowledge for question generation."""
- summary_parts = []
-
- # Top entities by confidence
- entities_by_confidence = sorted(
- self.knowledge_graph.entities.values(),
- key=lambda e: e.confidence,
- reverse=True,
- )[:5]
-
- if entities_by_confidence:
- summary_parts.append("Top candidates found:")
- for entity in entities_by_confidence:
- summary_parts.append(
- f"- {entity.name} ({entity.entity_type}): {entity.confidence:.2%} confidence"
- )
- if entity.properties:
- props = ", ".join(
- f"{k}={v}"
- for k, v in list(entity.properties.items())[:3]
- )
- summary_parts.append(f" Properties: {props}")
-
- # Constraint satisfaction summary
- if self.knowledge_graph.constraint_evidence:
- summary_parts.append("\nConstraint verification status:")
- for constraint, entities in list(
- self.knowledge_graph.constraint_evidence.items()
- )[:3]:
- summary_parts.append(f"- {constraint[:50]}...")
- for entity_name, evidence in list(entities.items())[:2]:
- score = evidence.get("score", 0)
- summary_parts.append(f" {entity_name}: {score:.2%}")
-
- return "\n".join(summary_parts)
-
- async def _cached_search(self, query: str) -> List[Dict]:
- """Perform search with caching support."""
- cache = get_search_cache()
-
- # Check cache first
- cached_results = cache.get(query, "browsecomp_entity")
- if cached_results is not None:
- logger.debug(f"Using cached search results for: {query[:50]}...")
- return cached_results
-
- # Perform actual search
- try:
- if hasattr(self.search_engine, "run"):
- results = self.search_engine.run(query)
- elif hasattr(self.search_engine, "search"):
- results = self.search_engine.search(query)
- elif callable(self.search_engine):
- results = self.search_engine(query)
- else:
- logger.warning("Search engine has no callable method")
- return []
-
- # Normalize results format
- if isinstance(results, list):
- normalized_results = results
- elif isinstance(results, dict):
- normalized_results = results.get("results", [])
- else:
- normalized_results = []
-
- # Cache the results
- cache.put(
- query, normalized_results, "browsecomp_entity", ttl=1800
- ) # 30 minutes
-
- # Also populate the in-memory search_cache (with size cap)
- if len(self.knowledge_graph.search_cache) >= MAX_LOCAL_CACHE:
- try:
- oldest_key = next(iter(self.knowledge_graph.search_cache))
- del self.knowledge_graph.search_cache[oldest_key]
- except (StopIteration, KeyError):
- pass
- self.knowledge_graph.search_cache[query] = normalized_results
-
- logger.debug(f"Cached new search results for: {query[:50]}...")
- return normalized_results
-
- except Exception:
- logger.exception(f"Search failed for query '{query}'")
- return []
-
- async def _generate_entity_answer(
- self,
- query: str,
- best_entity: EntityCandidate,
- constraints: List[Constraint],
- ) -> str:
- """Generate answer for the best matching entity."""
- constraint_details = []
- for constraint in constraints:
- score = best_entity.constraint_matches.get(constraint.value, 0)
- constraint_details.append(
- f"- {constraint.description}: {score:.2%} confidence"
- )
-
- prompt = f"""Based on the search results, provide the answer to: {query}
-
-Best matching {best_entity.entity_type}: {best_entity.name}
-Overall confidence: {best_entity.confidence:.2%}
-
-Aliases/Other names: {", ".join(best_entity.aliases[:3]) if best_entity.aliases else "None found"}
-
-Properties:
-{json.dumps(best_entity.properties, indent=2) if best_entity.properties else "No properties found"}
-
-Constraint satisfaction:
-{chr(10).join(constraint_details)}
-
-Provide a clear, confident answer that explains why this entity matches the constraints."""
-
- response = await self.model.ainvoke(prompt)
- return response.content
-
- async def _generate_uncertain_answer(
- self, query: str, top_entities: List[EntityCandidate]
- ) -> str:
- """Generate answer when no high-confidence match is found."""
- if not top_entities:
- return "Unable to find any entities matching the specified constraints."
-
- candidates_info = []
- for entity in top_entities:
- candidates_info.append(
- f"- {entity.name}: {entity.confidence:.2%} confidence"
- )
-
- prompt = f"""Based on the search results for: {query}
-
-Found these potential matches but with low confidence:
-{chr(10).join(candidates_info)}
-
-The search was unable to find a definitive answer matching all constraints.
-
-Provide a helpful response explaining what was found and why no definitive answer could be determined."""
-
- response = await self.model.ainvoke(prompt)
- return response.content
-
- def analyze_topic(self, query: str) -> Dict:
- """
- Analyze a topic using entity-focused BrowseComp approach.
-
- Args:
- query: The research query to analyze
-
- Returns:
- Dict containing findings, iterations, and questions
- """
- import asyncio
-
- try:
- # Run async search — detect whether we're inside an event loop
- try:
- asyncio.get_running_loop()
- # Inside a running loop — run in a thread to avoid nesting
- import concurrent.futures
-
- with concurrent.futures.ThreadPoolExecutor() as executor:
- future = executor.submit(
- thread_cleanup(
- lambda: asyncio.run(
- self._analyze_topic_async(query)
- )
- )
- )
- return future.result()
- except RuntimeError:
- # No running event loop — safe to use asyncio.run() directly
- return asyncio.run(self._analyze_topic_async(query))
-
- except Exception as e:
- logger.exception("Error in analyze_topic")
- return {
- "findings": [f"Error analyzing query: {e!s}"],
- "iterations": 0,
- "questions": {},
- "entities_found": 0,
- "confidence": 0.0,
- }
-
- async def _analyze_topic_async(self, query: str) -> Dict:
- """Async implementation of topic analysis."""
- try:
- self._update_progress("Starting entity-focused analysis...", 0)
-
- # Parse constraints from query
- constraint_analyzer = ConstraintAnalyzer()
- constraints = constraint_analyzer.analyze_query(query)
-
- self._update_progress(
- f"Identified {len(constraints)} constraints", 10
- )
-
- # Generate initial search questions
- question_generator = BrowseCompQuestionGenerator()
- initial_questions = question_generator.generate_questions(
- query, constraints
- )
-
- self._update_progress("Generated initial questions", 20)
-
- # Progressive entity discovery
- all_entities = []
- iteration = 0
- max_iterations = 3
-
- while iteration < max_iterations:
- self._update_progress(
- f"Iteration {iteration + 1}: Discovering entities...",
- 30 + iteration * 20,
- )
-
- # Search for entities
- entities = await self._discover_entities_from_questions(
- initial_questions, self._determine_entity_type(query)
- )
- all_entities.extend(entities)
-
- # Break if we found high-confidence entities
- if any(e.confidence > 0.8 for e in entities):
- logger.info(
- f"Found high-confidence entities in iteration {iteration + 1}"
- )
- break
-
- iteration += 1
-
- self._update_progress(
- "Evaluating entities against constraints...", 80
- )
-
- # Evaluate entities
- evaluated_entities = await self._evaluate_entities(constraints)
-
- # Generate final answer
- if evaluated_entities:
- best_entity = max(
- evaluated_entities, key=lambda e: e.confidence
- )
- if best_entity.confidence > 0.6:
- answer = await self._generate_entity_answer(
- query, best_entity, constraints
- )
- else:
- answer = await self._generate_uncertain_answer(
- query, evaluated_entities[:3]
- )
- else:
- answer = (
- "No entities were found matching the specified constraints."
- )
-
- self._update_progress("Analysis complete", 100)
-
- # Return results in expected format
- return {
- "findings": [answer],
- "iterations": iteration + 1,
- "questions": {
- f"iteration_{i}": initial_questions
- for i in range(iteration + 1)
- },
- "entities_found": len(evaluated_entities),
- "confidence": best_entity.confidence
- if evaluated_entities
- else 0.0,
- "strategy": "browsecomp_entity",
- }
-
- except Exception as e:
- logger.exception("Error in async topic analysis")
- return {
- "findings": [f"Analysis failed: {e!s}"],
- "iterations": 0,
- "questions": {},
- "entities_found": 0,
- "confidence": 0.0,
- }
diff --git a/src/local_deep_research/advanced_search_system/strategies/browsecomp_optimized_strategy.py b/src/local_deep_research/advanced_search_system/strategies/browsecomp_optimized_strategy.py
deleted file mode 100644
index 0d694452be..0000000000
--- a/src/local_deep_research/advanced_search_system/strategies/browsecomp_optimized_strategy.py
+++ /dev/null
@@ -1,779 +0,0 @@
-"""
-BrowseComp-Optimized Search Strategy for Complex Query Solving
-
-This strategy is specifically designed to handle BrowseComp-style puzzle queries
-where specific clues need to be matched to find a location, person, or event.
-"""
-
-from dataclasses import dataclass, field
-from datetime import datetime, UTC
-from typing import Any, Dict, List, Optional
-
-from langchain_core.language_models import BaseChatModel
-from loguru import logger
-
-from ...utilities.search_utilities import format_findings, remove_think_tags
-from ..findings.repository import FindingsRepository
-from .base_strategy import BaseSearchStrategy
-from .source_based_strategy import SourceBasedSearchStrategy
-
-
-@dataclass
-class QueryClues:
- """Extract specific clues from a complex query."""
-
- location_clues: List[str] = field(default_factory=list)
- temporal_clues: List[str] = field(default_factory=list)
- numerical_clues: List[str] = field(default_factory=list)
- name_clues: List[str] = field(default_factory=list)
- incident_clues: List[str] = field(default_factory=list)
- comparison_clues: List[str] = field(default_factory=list)
- all_clues: List[str] = field(default_factory=list)
- query_type: str = "unknown" # location, person, event, object, etc.
-
-
-class BrowseCompOptimizedStrategy(BaseSearchStrategy):
- """
- A strategy optimized for solving BrowseComp-style puzzle queries.
-
- Key features:
- 1. Extracts specific clues from the query
- 2. Searches for combinations of clues
- 3. Progressively narrows down candidates
- 4. Uses specific place/person/object names when found
- 5. Verifies candidates against all clues
- """
-
- def __init__(
- self,
- model: BaseChatModel,
- search: Any,
- all_links_of_system: List[Any],
- max_browsecomp_iterations: int = 15,
- confidence_threshold: float = 0.90,
- max_iterations: int = 1, # This is for source-based strategy iterations
- questions_per_iteration: int = 3, # This is for source-based strategy questions
- settings_snapshot=None,
- ):
- """Initialize the BrowseComp-optimized strategy."""
- super().__init__(all_links_of_system, settings_snapshot)
- self.model = model
- self.search = search
- self.max_browsecomp_iterations = max_browsecomp_iterations
- self.confidence_threshold = confidence_threshold
- self.findings_repository = FindingsRepository(model)
-
- # Store the source-based strategy parameters
- self.source_max_iterations = max_iterations
- self.source_questions_per_iteration = questions_per_iteration
-
- # State tracking
- self.query_clues: Optional[QueryClues] = None
- self.confirmed_info: Dict[str, Any] = {}
- self.candidates: List[Dict[str, Any]] = []
- self.search_history: List[str] = []
- self.iteration: int = 0
-
- def analyze_topic(self, query: str) -> Dict:
- """Analyze a topic using BrowseComp-optimized approach."""
- # Initialize
- self.all_links_of_system.clear()
- self.questions_by_iteration = []
- self.findings = []
- self.iteration = 0
-
- # Extract clues from query
- self.query_clues = self._extract_clues(query)
-
- # Progress callback
- if self.progress_callback:
- self.progress_callback(
- f"Identified {len(self.query_clues.all_clues)} clues from query",
- 1,
- {
- "phase": "init",
- "strategy": "browsecomp_optimized",
- "clues_count": len(self.query_clues.all_clues),
- "query_type": self.query_clues.query_type,
- },
- )
-
- logger.info(f"Starting BrowseComp optimization for: {query}")
- logger.info(f"Extracted {len(self.query_clues.all_clues)} clues")
-
- # Add initial analysis
- initial_finding = {
- "phase": "Initial Analysis",
- "content": f"""
-**Query**: {query}
-
-**Strategy**: BrowseComp-Optimized
-- Query type: {self.query_clues.query_type}
-- Total clues: {len(self.query_clues.all_clues)}
-- Location clues: {len(self.query_clues.location_clues)}
-- Temporal clues: {len(self.query_clues.temporal_clues)}
-- Numerical clues: {len(self.query_clues.numerical_clues)}
-
-**Key Clues**:
-{chr(10).join(f"- {clue}" for clue in self.query_clues.all_clues[:5])}
-
-**Starting systematic search**...
-""".strip(),
- "timestamp": self._get_timestamp(),
- }
- self.findings.append(initial_finding)
-
- # Main search loop
- while self.iteration < self.max_browsecomp_iterations:
- self.iteration += 1
-
- # Progress update
- if self.progress_callback:
- progress = (
- int((self.iteration / self.max_browsecomp_iterations) * 80)
- + 10
- )
- self.progress_callback(
- f"Iteration {self.iteration}: {len(self.candidates)} candidates, {len(self.confirmed_info)} confirmed facts",
- progress,
- {
- "phase": "searching",
- "iteration": self.iteration,
- "candidates_count": len(self.candidates),
- "confirmed_facts": len(self.confirmed_info),
- },
- )
-
- # Generate targeted search query
- search_query = self._generate_targeted_search()
-
- if not search_query:
- logger.info("No more searches needed - sufficient candidates")
- break
-
- # Execute search
- logger.info(
- f"Iteration {self.iteration}: Searching for '{search_query}'"
- )
- search_results = self._execute_search(search_query)
-
- # Process results
- self._process_search_results(search_results, search_query)
-
- # Check if we have a strong candidate
- if self._evaluate_candidates():
- break
-
- # Add iteration finding
- iteration_summary = f"""
-**Search Query**: {search_query}
-
-**Candidates Found**: {len(self.candidates)}
-{chr(10).join(f"- {c['name']} (confidence: {c['confidence']:.0%})" for c in self.candidates[:3])}
-
-**Confirmed Facts**: {len(self.confirmed_info)}
-{chr(10).join(f"- {k}: {v}" for k, v in list(self.confirmed_info.items())[:3])}
-
-**Progress**: Iteration {self.iteration}/{self.max_browsecomp_iterations}
-"""
- self.findings.append(
- {
- "phase": f"Iteration {self.iteration}",
- "content": iteration_summary.strip(),
- "timestamp": self._get_timestamp(),
- }
- )
-
- # Generate final answer
- final_result = self._synthesize_final_answer(query)
-
- if self.progress_callback:
- self.progress_callback(
- f"Analysis complete - {self.iteration} iterations, {len(self.candidates)} final candidates",
- 100,
- {
- "phase": "complete",
- "strategy": "browsecomp_optimized",
- "total_iterations": self.iteration,
- "final_candidates": len(self.candidates),
- },
- )
-
- return final_result
-
- def _extract_clues(self, query: str) -> QueryClues:
- """Extract specific clues from the query."""
- prompt = f"""
-Analyze this query and extract ALL specific clues that help identify the answer.
-
-Query: {query}
-
-Extract the following types of clues (BE VERY SPECIFIC AND COMPREHENSIVE):
-1. Location clues (geographical features, regions, landmarks)
-2. Temporal clues (dates, time periods, years - extract exact years/ranges)
-3. Numerical clues (statistics, counts, comparisons - extract exact numbers)
-4. Name clues (hints about the name, body parts, colors, etc.)
-5. Incident clues (accidents, events, activities - be specific about what happened)
-6. Comparison clues (comparisons to other places/things - extract exact comparison ratios)
-
-IMPORTANT: Extract EVERY specific detail, number, date, and comparison mentioned.
-
-Also determine the query type: location, person, event, object, or other.
-
-Format your response as:
-QUERY_TYPE: [type]
-
-LOCATION_CLUES:
-- [clue 1]
-- [clue 2]
-
-TEMPORAL_CLUES:
-- [clue 1 with exact dates/years]
-
-NUMERICAL_CLUES:
-- [clue 1 with exact numbers]
-
-NAME_CLUES:
-- [clue 1]
-
-INCIDENT_CLUES:
-- [clue 1 with specific details]
-
-COMPARISON_CLUES:
-- [clue 1 with exact comparison ratio]
-
-ALL_CLUES_SUMMARY:
-- [most important clue 1]
-- [most important clue 2]
-- [most important clue 3]
-- [most important clue 4]
-- [most important clue 5]
-"""
-
- response = self.model.invoke(prompt)
- content = remove_think_tags(str(response.content))
-
- clues = QueryClues()
- current_section = None
-
- for line in content.strip().split("\n"):
- line = line.strip()
-
- if line.startswith("QUERY_TYPE:"):
- clues.query_type = line.split(":", 1)[1].strip().lower()
- elif line.endswith("_CLUES:") or line == "ALL_CLUES_SUMMARY:":
- current_section = (
- line.replace("_CLUES:", "")
- .replace("ALL_CLUES_SUMMARY:", "all")
- .lower()
- )
- elif line.startswith("-") and current_section:
- clue = line[1:].strip()
- if current_section == "location":
- clues.location_clues.append(clue)
- elif current_section == "temporal":
- clues.temporal_clues.append(clue)
- elif current_section == "numerical":
- clues.numerical_clues.append(clue)
- elif current_section == "name":
- clues.name_clues.append(clue)
- elif current_section == "incident":
- clues.incident_clues.append(clue)
- elif current_section == "comparison":
- clues.comparison_clues.append(clue)
- elif current_section == "all":
- clues.all_clues.append(clue)
-
- # Ensure we have all clues
- if not clues.all_clues:
- clues.all_clues = (
- clues.location_clues
- + clues.temporal_clues
- + clues.numerical_clues
- + clues.name_clues
- + clues.incident_clues
- + clues.comparison_clues
- )[:5] # Top 5 most important
-
- return clues
-
- def _generate_targeted_search(self) -> Optional[str]:
- """Generate a targeted search query based on current knowledge."""
- # If we have specific candidates, search for verification
- if self.candidates and self.iteration > 2:
- top_candidate = self.candidates[0]
-
- # Search for specific verification of top candidate with unverified clues
- unverified_clues = self._get_unverified_clues(top_candidate)
-
- if unverified_clues:
- # Pick the most specific unverified clue
- if any(
- "fell" in clue or "accident" in clue
- for clue in unverified_clues
- ):
- return f"{top_candidate['name']} accident fall death {' '.join(self.query_clues.temporal_clues[:1])}"
- if any(
- "search and rescue" in clue.lower() or "sar" in clue.lower()
- for clue in unverified_clues
- ):
- return f"{top_candidate['name']} search and rescue incidents 2014 statistics"
- if any("84.5" in clue for clue in unverified_clues):
- return f"{top_candidate['name']} 2014 search rescue statistics Grand Canyon 2022 comparison"
-
- # Initial searches - combine multiple clues
- if self.iteration <= 3:
- # First iteration - broad search with key clues
- if self.iteration == 1:
- key_terms = []
- if self.query_clues.location_clues:
- key_terms.extend(self.query_clues.location_clues[:1])
- if self.query_clues.name_clues:
- key_terms.extend(self.query_clues.name_clues[:1])
- if self.query_clues.query_type == "location":
- key_terms.append("hiking trail scenic viewpoint")
- return " ".join(key_terms)
-
- # Second iteration - add temporal/incident info
- if self.iteration == 2:
- key_terms = []
- if self.query_clues.temporal_clues:
- key_terms.extend(self.query_clues.temporal_clues[:1])
- if self.query_clues.incident_clues:
- key_terms.extend(self.query_clues.incident_clues[:1])
- if self.query_clues.location_clues:
- key_terms.extend(self.query_clues.location_clues[:1])
- return " ".join(key_terms)
-
- # Middle iterations - search for specific combinations
- elif 3 <= self.iteration <= 8:
- # Try different clue combinations
- combinations = [
- (self.query_clues.location_clues, self.query_clues.name_clues),
- (
- self.query_clues.temporal_clues,
- self.query_clues.incident_clues,
- ),
- (
- self.query_clues.numerical_clues,
- self.query_clues.location_clues,
- ),
- (self.query_clues.name_clues, self.query_clues.incident_clues),
- ]
-
- combo_idx = (self.iteration - 3) % len(combinations)
- clues1, clues2 = combinations[combo_idx]
-
- terms = []
- if clues1:
- terms.extend(clues1[:1])
- if clues2:
- terms.extend(clues2[:1])
-
- return " ".join(terms)
-
- # Late iterations - search for specific statistics or comparisons
- elif self.iteration > 8:
- if self.query_clues.comparison_clues:
- return " ".join(
- self.query_clues.comparison_clues[:1] + ["statistics data"]
- )
- if self.query_clues.numerical_clues:
- return " ".join(
- self.query_clues.numerical_clues[:1]
- + ["official statistics 2014 2022"]
- )
-
- # Default - use remaining clues
- all_unused = [
- c
- for c in self.query_clues.all_clues
- if c not in self.search_history
- ]
- if all_unused:
- return all_unused[0]
-
- return None
-
- def _execute_search(self, search_query: str) -> Dict:
- """Execute a search using source-based strategy."""
- # Track search history
- self.search_history.append(search_query)
-
- # Use source-based strategy
- source_strategy = SourceBasedSearchStrategy(
- model=self.model,
- search=self.search,
- all_links_of_system=self.all_links_of_system,
- include_text_content=True,
- use_cross_engine_filter=True,
- use_atomic_facts=True,
- )
-
- source_strategy.max_iterations = self.source_max_iterations
- source_strategy.questions_per_iteration = (
- self.source_questions_per_iteration
- )
-
- if self.progress_callback:
-
- def wrapped_callback(message, progress, data):
- data["parent_iteration"] = self.iteration
- data["parent_strategy"] = "browsecomp_optimized"
- self.progress_callback(
- f"Iteration {self.iteration}: {message}", progress, data
- )
-
- source_strategy.set_progress_callback(wrapped_callback)
-
- results = source_strategy.analyze_topic(search_query)
-
- if "questions_by_iteration" in results:
- self.questions_by_iteration.extend(
- results["questions_by_iteration"]
- )
-
- return results
-
- def _process_search_results(self, search_results: Dict, search_query: str):
- """Process search results and update candidates."""
- current_knowledge = search_results.get("current_knowledge", "")
-
- if not current_knowledge:
- return
-
- prompt = f"""
-Based on the search results, extract specific information about potential answers.
-
-Query Clues:
-- Query type: {self.query_clues.query_type}
-- Key clues: {", ".join(self.query_clues.all_clues[:3])}
-
-Search Query: {search_query}
-
-Search Results:
-{current_knowledge[:3000]}
-
-Current Candidates: {len(self.candidates)}
-{chr(10).join(f"- {c['name']} ({c['confidence']:.0%})" for c in self.candidates[:3])}
-
-Extract:
-1. SPECIFIC_NAMES: Any specific place names, trail names, or landmarks mentioned
-2. CONFIRMED_FACTS: Facts that match our clues (with which clue they match)
-3. NEW_CANDIDATES: New potential answers with confidence (0-1)
-4. ELIMINATED_CANDIDATES: Candidates we can rule out
-
-Format:
-SPECIFIC_NAMES:
-- [name 1]
-- [name 2]
-
-CONFIRMED_FACTS:
-- [fact]: matches [clue]
-
-NEW_CANDIDATES:
-- [name]: [confidence] (reason)
-
-ELIMINATED_CANDIDATES:
-- [name]: [reason for elimination]
-"""
-
- response = self.model.invoke(prompt)
- content = remove_think_tags(str(response.content))
-
- # Parse response
- current_section = None
-
- for line in content.strip().split("\n"):
- line = line.strip()
-
- if line.endswith(":"):
- current_section = line[:-1].lower()
- elif line.startswith("-") and current_section:
- item = line[1:].strip()
-
- if current_section == "specific_names":
- # Add as potential candidate if not already present
- if not any(
- c["name"].lower() == item.lower()
- for c in self.candidates
- ):
- self.candidates.append(
- {
- "name": item,
- "confidence": 0.7,
- "source": search_query,
- "matched_clues": [],
- }
- )
-
- elif current_section == "confirmed_facts":
- if ":" in item:
- fact, clue = item.split(":", 1)
- self.confirmed_info[fact.strip()] = clue.strip()
-
- elif current_section == "new_candidates":
- if ":" in item:
- parts = item.split(":", 1)
- name = parts[0].strip()
-
- # Parse confidence
- confidence_str = parts[1].strip()
- try:
- confidence = float(confidence_str.split()[0])
- except (ValueError, IndexError):
- confidence = 0.5
-
- # Update or add candidate
- existing = False
- for candidate in self.candidates:
- if candidate["name"].lower() == name.lower():
- candidate["confidence"] = max(
- candidate["confidence"], confidence
- )
- existing = True
- break
-
- if not existing:
- self.candidates.append(
- {
- "name": name,
- "confidence": confidence,
- "source": search_query,
- "matched_clues": [],
- }
- )
-
- elif current_section == "eliminated_candidates":
- if ":" in item:
- name = item.split(":")[0].strip()
- self.candidates = [
- c
- for c in self.candidates
- if c["name"].lower() != name.lower()
- ]
-
- # Update matched clues for candidates
- for candidate in self.candidates:
- candidate["matched_clues"] = self._get_matched_clues(
- candidate["name"]
- )
- # Update confidence based on matched clues
- clue_confidence = len(candidate["matched_clues"]) / len(
- self.query_clues.all_clues
- )
- candidate["confidence"] = (
- candidate["confidence"] + clue_confidence
- ) / 2
-
- # Sort candidates by confidence
- self.candidates.sort(key=lambda x: x["confidence"], reverse=True)
-
- # Keep only top candidates
- self.candidates = self.candidates[:5]
-
- def _get_matched_clues(self, candidate_name: str) -> List[str]:
- """Determine which clues a candidate matches."""
- matched = []
-
- # Check name clues
- for clue in self.query_clues.name_clues:
- if any(
- word.lower() in candidate_name.lower() for word in clue.split()
- ):
- matched.append(f"name: {clue}")
-
- # Check location clues
- for clue in self.query_clues.location_clues:
- if (
- candidate_name.lower()
- in self.confirmed_info.get(clue, "").lower()
- ):
- matched.append(f"location: {clue}")
-
- # Check confirmed facts
- for fact, clue in self.confirmed_info.items():
- if candidate_name.lower() in fact.lower():
- matched.append(f"fact: {clue}")
-
- # Check temporal clues if mentioned in confirmed facts
- for clue in self.query_clues.temporal_clues:
- for fact in self.confirmed_info:
- if candidate_name.lower() in fact.lower() and any(
- year in fact for year in clue.split() if year.isdigit()
- ):
- matched.append(f"temporal: {clue}")
-
- # Check incident clues
- for clue in self.query_clues.incident_clues:
- for fact in self.confirmed_info:
- if candidate_name.lower() in fact.lower() and any(
- word in fact.lower() for word in clue.lower().split()
- ):
- matched.append(f"incident: {clue}")
-
- return list(set(matched)) # Remove duplicates
-
- def _get_unverified_clues(self, candidate: Dict) -> List[str]:
- """Get clues that haven't been verified for a candidate."""
- all_clues = (
- self.query_clues.location_clues
- + self.query_clues.temporal_clues
- + self.query_clues.numerical_clues
- + self.query_clues.name_clues
- + self.query_clues.incident_clues
- + self.query_clues.comparison_clues
- )
-
- matched_clues = candidate.get("matched_clues", [])
- matched_clue_texts = [
- clue.split(": ", 1)[1] if ": " in clue else clue
- for clue in matched_clues
- ]
-
- unverified = []
- for clue in all_clues:
- if not any(
- clue in matched_text for matched_text in matched_clue_texts
- ):
- unverified.append(clue)
-
- return unverified
-
- def _evaluate_candidates(self) -> bool:
- """Check if we have a sufficiently confident answer."""
- if not self.candidates:
- return False
-
- top_candidate = self.candidates[0]
-
- # Need high confidence and clue matching
- if top_candidate["confidence"] >= self.confidence_threshold:
- matched_ratio = len(top_candidate["matched_clues"]) / len(
- self.query_clues.all_clues
- )
- # For BrowseComp, require higher clue matching threshold
- if matched_ratio >= 0.8: # At least 80% of clues matched
- return True
-
- # Very high confidence only if ALL clues matched
- if top_candidate["confidence"] >= 0.95:
- matched_ratio = len(top_candidate["matched_clues"]) / len(
- self.query_clues.all_clues
- )
- if matched_ratio >= 0.9: # At least 90% clues matched
- return True
-
- # For BrowseComp queries, always do at least 3 iterations
- if self.iteration < 3:
- return False
-
- # Or if we've done enough iterations and have a clear leader
- if self.iteration >= 8:
- if len(self.candidates) > 1:
- confidence_gap = (
- top_candidate["confidence"]
- - self.candidates[1]["confidence"]
- )
- if confidence_gap > 0.3: # 30% gap to second place
- return True
-
- return False
-
- def _synthesize_final_answer(self, original_query: str) -> Dict:
- """Generate final answer in BrowseComp format."""
- if self.candidates:
- top_candidate = self.candidates[0]
- answer = top_candidate["name"]
- confidence = int(top_candidate["confidence"] * 100)
- else:
- answer = "Unable to determine"
- confidence = 0
-
- # Generate explanation
- prompt = f"""
-Provide a concise final answer to this query:
-{original_query}
-
-Based on our research:
-- Top answer: {answer}
-- Confidence: {confidence}%
-- Matched clues: {len(top_candidate["matched_clues"]) if self.candidates else 0}/{len(self.query_clues.all_clues)}
-
-Confirmed facts:
-{chr(10).join(f"- {k}: {v}" for k, v in self.confirmed_info.items())}
-
-Format your response EXACTLY as:
-Explanation: {{brief explanation of why this answer matches the clues}}
-Exact Answer: {{the exact answer - just the name/place/etc}}
-Confidence: {{confidence}}%
-"""
-
- response = self.model.invoke(prompt)
- final_answer = remove_think_tags(str(response.content))
-
- # Add comprehensive findings
- synthesis_summary = f"""
-**Final Answer**: {answer}
-
-**Research Summary**:
-- Completed {self.iteration} search iterations
-- Evaluated {len(self.candidates)} candidates
-- Matched {len(top_candidate["matched_clues"]) if self.candidates else 0}/{len(self.query_clues.all_clues)} clues
-- Final confidence: {confidence}%
-
-**Top Candidates**:
-{chr(10).join(f"{i + 1}. {c['name']} ({c['confidence']:.0%})" for i, c in enumerate(self.candidates[:3]))}
-
-**Confirmed Facts**:
-{chr(10).join(f"- {k}: {v}" for k, v in self.confirmed_info.items())}
-
-**Search History**:
-{chr(10).join(f"{i + 1}. {q}" for i, q in enumerate(self.search_history))}
-"""
-
- self.findings.append(
- {
- "phase": "Final Synthesis",
- "content": synthesis_summary,
- "timestamp": self._get_timestamp(),
- }
- )
-
- # Compile questions
- questions_dict = {}
- for i, questions in enumerate(self.questions_by_iteration):
- if isinstance(questions, list):
- questions_dict[i + 1] = questions
- elif isinstance(questions, dict):
- questions_dict.update(questions)
-
- # Format findings
- formatted_findings = format_findings(
- self.findings, final_answer, questions_dict
- )
-
- return {
- "current_knowledge": final_answer,
- "formatted_findings": formatted_findings,
- "findings": self.findings,
- "iterations": self.iteration,
- "questions_by_iteration": questions_dict,
- "all_links_of_system": self.all_links_of_system,
- "sources": self.all_links_of_system,
- "candidates": self.candidates,
- "confirmed_info": self.confirmed_info,
- "clues": {
- "location": self.query_clues.location_clues,
- "temporal": self.query_clues.temporal_clues,
- "numerical": self.query_clues.numerical_clues,
- "name": self.query_clues.name_clues,
- "incident": self.query_clues.incident_clues,
- "comparison": self.query_clues.comparison_clues,
- },
- "strategy": "browsecomp_optimized",
- }
-
- def _get_timestamp(self) -> str:
- """Get current timestamp for findings."""
- return datetime.now(UTC).isoformat()
diff --git a/src/local_deep_research/advanced_search_system/strategies/concurrent_dual_confidence_strategy.py b/src/local_deep_research/advanced_search_system/strategies/concurrent_dual_confidence_strategy.py
deleted file mode 100644
index 5eb1d8733a..0000000000
--- a/src/local_deep_research/advanced_search_system/strategies/concurrent_dual_confidence_strategy.py
+++ /dev/null
@@ -1,418 +0,0 @@
-"""
-Concurrent dual confidence strategy with progressive search.
-
-Key features:
-1. Starts with all constraints combined for maximum specificity
-2. Evaluates candidates concurrently as they're found
-3. Progressively loosens constraints if needed
-4. Uses early rejection from dual confidence
-5. Dynamic stopping criteria instead of fixed limits
-"""
-
-import concurrent.futures
-import threading
-import time
-from dataclasses import dataclass, field
-from typing import List, Optional, Tuple
-
-from loguru import logger
-
-from ...database.thread_local_session import thread_cleanup
-from ..candidates.base_candidate import Candidate
-from ..constraints.base_constraint import Constraint, ConstraintType
-from .dual_confidence_with_rejection import DualConfidenceWithRejectionStrategy
-
-
-@dataclass
-class SearchState:
- """Tracks the current state of the concurrent search."""
-
- good_candidates: List[Tuple[Candidate, float]] = field(default_factory=list)
- total_evaluated: int = 0
- start_time: float = field(default_factory=time.time)
- remaining_constraints: List[Constraint] = field(default_factory=list)
- candidates_lock: threading.Lock = field(default_factory=threading.Lock)
- stop_search: threading.Event = field(default_factory=threading.Event)
- evaluation_futures: List[concurrent.futures.Future] = field(
- default_factory=list
- )
-
-
-class ConcurrentDualConfidenceStrategy(DualConfidenceWithRejectionStrategy):
- """
- Enhanced strategy that combines concurrent evaluation with progressive search.
- """
-
- def __init__(
- self,
- *args,
- # Concurrent execution settings
- max_workers: int = 10,
- # Candidate targets
- min_good_candidates: int = 3,
- target_candidates: int = 5,
- max_candidates: int = 10,
- # Quality thresholds
- min_score_threshold: float = 0.65,
- exceptional_score: float = 0.95,
- quality_plateau_threshold: float = 0.1,
- # Time and resource limits
- max_search_time: float = 30.0,
- max_evaluations: int = 30,
- # Search behavior
- initial_search_timeout: float = 5.0,
- **kwargs,
- ):
- super().__init__(*args, **kwargs)
-
- # Thread pool for concurrent evaluations
- self.evaluation_executor = concurrent.futures.ThreadPoolExecutor(
- max_workers=max_workers
- )
-
- # Candidate thresholds
- self.min_good_candidates = min_good_candidates
- self.target_candidates = target_candidates
- self.max_candidates = max_candidates
-
- # Quality settings
- self.min_score_threshold = min_score_threshold
- self.exceptional_score = exceptional_score
- self.quality_plateau_threshold = quality_plateau_threshold
-
- # Resource limits
- self.max_search_time = max_search_time
- self.max_evaluations = max_evaluations
- self.initial_search_timeout = initial_search_timeout
-
- # Search state
- self.state: Optional[SearchState] = None
-
- def close(self):
- """Shut down persistent thread pool executor.
-
- Also shut down in find_relevant_information()'s finally block, but
- this handles the edge case where the method is never called.
-
- Uses wait=False because wait=True would block the research thread.
- Safe due to double-cleanup pattern; shutdown() is idempotent.
- """
- if hasattr(self, "evaluation_executor"):
- try:
- self.evaluation_executor.shutdown(wait=False)
- except Exception:
- logger.exception("Error shutting down evaluation executor")
-
- def find_relevant_information(self):
- """Override to use concurrent search and evaluation."""
- # Initialize state
- self.state = SearchState(
- remaining_constraints=self.constraint_ranking.copy(),
- start_time=time.time(),
- )
-
- # Classify constraints by difficulty
- self._classify_constraint_difficulty()
-
- # Start progressive search with concurrent evaluation
- try:
- self._progressive_search_with_concurrent_eval()
- finally:
- # Clean up thread pool
- self.evaluation_executor.shutdown(wait=False)
-
- # Return best candidates
- self.candidates = [
- c
- for c, _ in sorted(
- self.state.good_candidates, key=lambda x: x[1], reverse=True
- )[: self.max_candidates]
- ]
-
- logger.info(
- f"Found {len(self.candidates)} candidates after concurrent search"
- )
-
- def _classify_constraint_difficulty(self):
- """Rate constraints by how difficult they are to search for."""
- for constraint in self.state.remaining_constraints:
- difficulty = 0.5 # Default medium difficulty
-
- # Constraint type affects difficulty
- if constraint.type == ConstraintType.EVENT:
- difficulty = max(difficulty, 0.7)
-
- constraint.search_difficulty = difficulty
-
- # Sort constraints by difficulty (hardest first, so we can drop them first)
- self.state.remaining_constraints.sort(
- key=lambda c: getattr(c, "search_difficulty", 0.5), reverse=True
- )
-
- def _progressive_search_with_concurrent_eval(self):
- """Main search loop with concurrent evaluation."""
- iteration = 0
-
- while (
- not self.state.stop_search.is_set()
- and self.state.remaining_constraints
- ):
- iteration += 1
-
- # Build query from current constraints
- query = self._build_combined_query(self.state.remaining_constraints)
-
- logger.info(
- f"Search iteration {iteration}: {len(self.state.remaining_constraints)} constraints"
- )
-
- if self.progress_callback:
- self.progress_callback(
- f"Searching with {len(self.state.remaining_constraints)} constraints",
- min(20 + (iteration * 10), 80),
- {
- "phase": "concurrent_search",
- "iteration": iteration,
- "constraints": len(self.state.remaining_constraints),
- "good_candidates": len(self.state.good_candidates),
- },
- )
-
- # Execute search
- try:
- search_results = self._execute_search(query)
- new_candidates = self._extract_relevant_candidates(
- search_results,
- self.state.remaining_constraints[
- 0
- ], # Use most important constraint
- )
-
- logger.info(
- f"Found {len(new_candidates)} candidates in iteration {iteration}"
- )
-
- # Spawn evaluation threads for each candidate
- for candidate in new_candidates:
- if self.state.stop_search.is_set():
- break
-
- if self.state.total_evaluated >= self.max_evaluations:
- logger.info("Reached maximum evaluations limit")
- self.state.stop_search.set()
- break
-
- # Check if we already evaluated this candidate
- if self._is_candidate_evaluated(candidate):
- continue
-
- # Submit for evaluation
- future = self.evaluation_executor.submit(
- self._evaluate_candidate_thread, candidate
- )
- self.state.evaluation_futures.append(future)
- self.state.total_evaluated += 1
-
- except Exception:
- logger.exception(f"Search error in iteration {iteration}")
-
- # Check completed evaluations
- self._check_evaluation_results()
-
- # Determine if we should stop
- if self._should_stop_search():
- logger.info("Stopping criteria met")
- break
-
- # Drop hardest constraint if we haven't found enough
- if len(self.state.good_candidates) < self.min_good_candidates:
- if len(self.state.remaining_constraints) > 1:
- dropped = self.state.remaining_constraints.pop(
- 0
- ) # Remove hardest
- logger.info(
- f"Dropping constraint: {dropped.value} (difficulty: {getattr(dropped, 'search_difficulty', 0.5):.2f})"
- )
- else:
- logger.info("No more constraints to drop")
- break
-
- # Wait for remaining evaluations
- self._finalize_evaluations()
-
- def _build_combined_query(self, constraints: List[Constraint]) -> str:
- """Build a query combining all constraints with AND logic."""
- terms = []
-
- for constraint in constraints:
- value = constraint.value
-
- # Quote multi-word values only if they don't already have quotes
- if " " in value and '"' not in value:
- value = f'"{value}"'
-
- terms.append(value)
-
- return " ".join(
- terms
- ) # Use space instead of AND for more natural queries
-
- @thread_cleanup
- def _evaluate_candidate_thread(
- self, candidate: Candidate
- ) -> Tuple[Candidate, float]:
- """Evaluate a candidate in a separate thread."""
- try:
- thread_name = threading.current_thread().name
- logger.info(
- f"[{thread_name}] Starting evaluation of {candidate.name}"
- )
-
- # Use parent's evaluation with early rejection
- score = self._evaluate_candidate_immediately(candidate)
-
- # Log result
- if score >= self.min_score_threshold:
- logger.info(
- f"[{thread_name}] ✓ {candidate.name} passed (score: {score:.3f})"
- )
-
- # Add to good candidates
- with self.state.candidates_lock:
- self.state.good_candidates.append((candidate, score))
-
- # Check if we should stop
- if self._should_stop_search():
- logger.info("Stopping criteria met after evaluation")
- self.state.stop_search.set()
- else:
- logger.info(
- f"[{thread_name}] ❌ {candidate.name} rejected (score: {score:.3f})"
- )
-
- return (candidate, score)
-
- except Exception:
- logger.exception("Error evaluating candidate")
- return (candidate, 0.0)
-
- def _check_evaluation_results(self):
- """Check completed evaluation futures without blocking."""
- completed = []
-
- for future in self.state.evaluation_futures:
- if future.done():
- completed.append(future)
- try:
- future.result()
- # Result is already processed in the thread
- except Exception:
- logger.exception("Failed to get future result")
-
- # Remove completed futures
- for future in completed:
- self.state.evaluation_futures.remove(future)
-
- def _should_stop_search(self) -> bool:
- """Determine if we should stop searching based on multiple criteria."""
- # Always respect the stop flag
- if self.state.stop_search.is_set():
- return True
-
- num_good = len(self.state.good_candidates)
-
- # 1. Maximum candidates reached
- if num_good >= self.max_candidates:
- logger.info(f"Maximum candidates reached ({self.max_candidates})")
- return True
-
- # 2. Target reached with good quality
- if num_good >= self.target_candidates:
- avg_score = sum(s for _, s in self.state.good_candidates) / num_good
- if avg_score >= 0.8:
- logger.info(
- f"Target reached with high quality (avg: {avg_score:.3f})"
- )
- return True
-
- # 3. Minimum satisfied with exceptional candidates
- if num_good >= self.min_good_candidates:
- top_score = max(s for _, s in self.state.good_candidates)
- if top_score >= self.exceptional_score:
- logger.info(
- f"Exceptional candidate found (score: {top_score:.3f})"
- )
- return True
-
- # 4. Time limit reached
- elapsed = time.time() - self.state.start_time
- if elapsed > self.max_search_time:
- logger.info(f"Time limit reached ({elapsed:.1f}s)")
- return True
-
- # 5. Too many evaluations
- if self.state.total_evaluated >= self.max_evaluations:
- logger.info(f"Evaluation limit reached ({self.max_evaluations})")
- return True
-
- # 6. No more constraints and sufficient candidates
- if (
- not self.state.remaining_constraints
- and num_good >= self.min_good_candidates
- ):
- logger.info("No more constraints and minimum candidates found")
- return True
-
- # 7. Quality plateau detection
- if num_good >= 5:
- recent_scores = [s for _, s in self.state.good_candidates[-5:]]
- score_range = max(recent_scores) - min(recent_scores)
- if score_range < self.quality_plateau_threshold:
- logger.info(
- f"Quality plateau detected (range: {score_range:.3f})"
- )
- return True
-
- return False
-
- def _is_candidate_evaluated(self, candidate: Candidate) -> bool:
- """Check if we already evaluated this candidate."""
- with self.state.candidates_lock:
- return any(
- c.name == candidate.name for c, _ in self.state.good_candidates
- )
-
- def _finalize_evaluations(self):
- """Wait for or cancel remaining evaluations."""
- if self.state.evaluation_futures:
- logger.info(
- f"Finalizing {len(self.state.evaluation_futures)} remaining evaluations"
- )
-
- # Give them a short time to complete
- wait_time = min(
- 5.0,
- self.max_search_time - (time.time() - self.state.start_time),
- )
- if wait_time > 0:
- concurrent.futures.wait(
- self.state.evaluation_futures,
- timeout=wait_time,
- return_when=concurrent.futures.FIRST_COMPLETED,
- )
-
- # Cancel any still running
- for future in self.state.evaluation_futures:
- if not future.done():
- future.cancel()
-
- # Final report
- logger.info(
- f"""
-Search completed:
-- Total evaluated: {self.state.total_evaluated}
-- Good candidates found: {len(self.state.good_candidates)}
-- Time taken: {time.time() - self.state.start_time:.1f}s
-- Final constraints: {len(self.state.remaining_constraints)}
-"""
- )
diff --git a/src/local_deep_research/advanced_search_system/strategies/constrained_search_strategy.py b/src/local_deep_research/advanced_search_system/strategies/constrained_search_strategy.py
deleted file mode 100644
index feb9dccfc6..0000000000
--- a/src/local_deep_research/advanced_search_system/strategies/constrained_search_strategy.py
+++ /dev/null
@@ -1,1335 +0,0 @@
-"""
-Constrained search strategy that progressively narrows down candidates.
-
-This strategy mimics human problem-solving by:
-1. Starting with the most restrictive constraints
-2. Finding candidates that match those constraints
-3. Progressively checking additional constraints
-4. Narrowing down the candidate pool step by step
-"""
-
-from datetime import datetime, UTC
-from typing import Any, Dict, List
-
-from langchain_core.language_models import BaseChatModel
-from loguru import logger
-
-from ...utilities.search_utilities import remove_think_tags
-from ..candidates.base_candidate import Candidate
-from ..constraints.base_constraint import Constraint, ConstraintType
-from ..evidence.base_evidence import Evidence, EvidenceType
-from .evidence_based_strategy import EvidenceBasedStrategy
-
-
-class ConstrainedSearchStrategy(EvidenceBasedStrategy):
- """
- Strategy that progressively narrows down candidates using constraints.
-
- Key approach:
- 1. Rank constraints by restrictiveness
- 2. Start with most restrictive constraint
- 3. Find candidates matching that constraint
- 4. Progressively filter using additional constraints
- 5. Gather evidence only for promising candidates
- """
-
- def __init__(
- self,
- model: BaseChatModel,
- search: Any,
- all_links_of_system: List[Any],
- max_iterations: int = 20,
- confidence_threshold: float = 0.85,
- candidate_limit: int = 100, # Increased to get more candidates
- evidence_threshold: float = 0.6,
- max_search_iterations: int = 2,
- questions_per_iteration: int = 3,
- min_candidates_per_stage: int = 20, # Need more candidates before filtering
- settings_snapshot=None,
- ):
- """Initialize the constrained search strategy."""
- super().__init__(
- model=model,
- search=search,
- all_links_of_system=all_links_of_system,
- max_iterations=max_iterations,
- confidence_threshold=confidence_threshold,
- candidate_limit=candidate_limit,
- evidence_threshold=evidence_threshold,
- max_search_iterations=max_search_iterations,
- questions_per_iteration=questions_per_iteration,
- settings_snapshot=settings_snapshot,
- )
-
- self.min_candidates_per_stage = min_candidates_per_stage
- self.constraint_ranking: List[Constraint] = []
- self.stage_candidates: Dict[int, List[Candidate]] = {}
-
- # Enable direct search optimization for entity identification
- # Note: parent class already sets this, but we ensure it's True
- self.use_direct_search = True
- logger.info(
- f"ConstrainedSearchStrategy init: use_direct_search={self.use_direct_search}"
- )
-
- def analyze_topic(self, query: str) -> Dict:
- """Analyze topic using progressive constraint narrowing."""
- # Initialize
- self.all_links_of_system.clear()
- self.questions_by_iteration = []
- self.findings = []
- self.iteration = 0
-
- if self.progress_callback:
- self.progress_callback(
- "Analyzing query to identify constraints and rank by restrictiveness",
- 2,
- {"phase": "initialization", "strategy": "constrained_search"},
- )
-
- # Extract and rank constraints
- self.constraints = self.constraint_analyzer.extract_constraints(query)
- self.constraint_ranking = self._rank_constraints_by_restrictiveness()
-
- if self.progress_callback:
- ranking_summary = ", ".join(
- [
- f"{i + 1}. {c.description[:30]}..."
- for i, c in enumerate(self.constraint_ranking[:3])
- ]
- )
- self.progress_callback(
- f"Found {len(self.constraints)} constraints. Order: {ranking_summary}",
- 5,
- {
- "phase": "constraint_ranking",
- "constraint_count": len(self.constraints),
- "ranking": [
- (c.description, c.type.value)
- for c in self.constraint_ranking
- ],
- },
- )
-
- # Add initial analysis finding
- initial_finding = {
- "phase": "Constraint Analysis",
- "content": self._format_constraint_analysis(),
- "timestamp": self._get_timestamp(),
- }
- self.findings.append(initial_finding)
-
- # Progressive constraint search
- self._progressive_constraint_search()
-
- # Add search summary finding
- search_finding = {
- "phase": "Progressive Search Summary",
- "content": self._format_search_summary(),
- "timestamp": self._get_timestamp(),
- }
- self.findings.append(search_finding)
-
- # Evidence gathering for final candidates
- self._focused_evidence_gathering()
-
- # Add evidence summary finding
- evidence_finding = {
- "phase": "Evidence Summary",
- "content": self._format_evidence_summary(),
- "timestamp": self._get_timestamp(),
- }
- self.findings.append(evidence_finding)
-
- # Add comprehensive debug summary
- debug_finding = {
- "phase": "Debug Summary",
- "content": self._format_debug_summary(),
- "timestamp": self._get_timestamp(),
- "metadata": {
- "total_searches": (
- len(self.search_history)
- if hasattr(self, "search_history")
- else 0
- ),
- "final_candidates": len(self.candidates),
- "constraints_used": len(self.constraints),
- "stages_completed": len(self.stage_candidates),
- },
- }
- self.findings.append(debug_finding)
-
- # Final synthesis
- return self._synthesize_final_answer(query)
-
- def _rank_constraints_by_restrictiveness(self) -> List[Constraint]:
- """Rank constraints from most to least restrictive."""
- # Scoring system for restrictiveness
- restrictiveness_scores = []
-
- for constraint in self.constraints:
- score = 0
-
- # Type-based scoring
- if constraint.type == ConstraintType.STATISTIC:
- score += 10 # Numbers are usually very restrictive
- elif constraint.type == ConstraintType.EVENT:
- score += 8 # Events/time periods are restrictive
- elif constraint.type == ConstraintType.LOCATION:
- score += 6 # Locations are moderately restrictive
- elif constraint.type == ConstraintType.PROPERTY:
- score += 4 # Properties are less restrictive
-
- # NOTE: constraint.value is always a str from
- # ConstraintAnalyzer. The truthiness guard is intentional.
- if constraint.value:
- # Check for specific markers
- if any(char.isdigit() for char in constraint.value):
- score += 5 # Contains numbers
- if len(constraint.value.split()) > 3:
- score += 3 # Longer, more specific
- if any(
- term in constraint.value.lower()
- for term in ["specific", "exact", "only", "must"]
- ):
- score += 2 # Explicit specificity
-
- restrictiveness_scores.append((constraint, score))
-
- # Sort by score (highest first)
- ranked = sorted(
- restrictiveness_scores, key=lambda x: x[1], reverse=True
- )
- return [constraint for constraint, _ in ranked]
-
- def _progressive_constraint_search(self):
- """Progressively search using constraints from most to least restrictive."""
- current_candidates = []
-
- for stage, constraint in enumerate(self.constraint_ranking):
- self.current_stage = stage # Track current stage for logging
- if self.progress_callback:
- stage_desc = f"[{constraint.type.value}] {constraint.value} ({len(current_candidates)} candidates)"
- self.progress_callback(
- f"Stage {stage + 1}/{len(self.constraint_ranking)}: {stage_desc}",
- 10 + (stage * 15),
- {
- "phase": "progressive_search",
- "stage": stage + 1,
- "total_stages": len(self.constraint_ranking),
- "constraint": constraint.description,
- "constraint_type": constraint.type.value,
- "constraint_value": constraint.value,
- "current_candidates": len(current_candidates),
- "search_intent": f"Finding entities matching: {constraint.value}",
- },
- )
-
- if stage == 0:
- # First stage - find initial candidates
- current_candidates = self._search_with_single_constraint(
- constraint
- )
- else:
- # Subsequent stages - filter existing candidates
- current_candidates = self._filter_candidates_with_constraint(
- current_candidates, constraint
- )
-
- # Store stage results
- self.stage_candidates[stage] = current_candidates.copy()
-
- if self.progress_callback:
- candidate_names = ", ".join(
- [c.name for c in current_candidates[:3]]
- )
- more = (
- f" (+{len(current_candidates) - 3})"
- if len(current_candidates) > 3
- else ""
- )
- change = len(current_candidates) - len(
- self.stage_candidates.get(stage - 1, [])
- )
- change_str = f" (Δ{change:+d})" if stage > 0 else ""
-
- self.progress_callback(
- f"Stage {stage + 1} complete: {len(current_candidates)} candidates{change_str}. {candidate_names}{more}",
- None,
- {
- "phase": "stage_complete",
- "stage": stage + 1,
- "candidates_found": len(current_candidates),
- "candidates_delta": change if stage > 0 else 0,
- "sample": [c.name for c in current_candidates[:10]],
- },
- )
-
- # Add stage finding
- stage_finding = {
- "phase": f"Stage {stage + 1} - {constraint.type.value}",
- "content": self._format_stage_results(
- stage, constraint, current_candidates
- ),
- "timestamp": self._get_timestamp(),
- }
- self.findings.append(stage_finding)
-
- # Continue applying constraints unless we have very few candidates
- if len(current_candidates) <= 3:
- if self.progress_callback:
- self.progress_callback(
- f"Too few candidates ({len(current_candidates)}) - stopping constraint application",
- None,
- {
- "phase": "early_stop",
- "candidates_remaining": len(current_candidates),
- },
- )
- break
-
- # Stop if no candidates remain
- if not current_candidates:
- # Backtrack to previous stage if possible
- if stage > 0:
- current_candidates = self.stage_candidates[stage - 1]
- break
-
- self.candidates = current_candidates[: self.candidate_limit]
-
- def _search_with_single_constraint(
- self, constraint: Constraint
- ) -> List[Candidate]:
- """Search for candidates using a single constraint."""
- candidates = []
-
- # Generate targeted queries for this constraint
- queries = self._generate_constraint_specific_queries(constraint)
-
- # Add more diverse query patterns
- additional_queries = self._generate_additional_queries(constraint)
- queries.extend(additional_queries)
-
- # Diversify query execution order
- import random
-
- # Security: random.shuffle for query order diversity, not security-sensitive
- random.shuffle(queries)
-
- for i, query in enumerate(queries[:20]): # Increased query limit
- if self.progress_callback:
- # Show query and what we're looking for
- self.progress_callback(
- f"Q{i + 1}/{min(20, len(queries))}: '{query}' | Found: {len(candidates)} candidates",
- None,
- {
- "phase": "constraint_search",
- "query": query,
- "query_index": i + 1,
- "total_queries": min(20, len(queries)),
- "constraint_type": constraint.type.value,
- "constraint_value": constraint.value,
- "candidates_so_far": len(candidates),
- "search_context": f"Stage {getattr(self, 'current_stage', 0) + 1}: {constraint.value}",
- },
- )
-
- results = self._execute_search(query)
-
- # Validate search results before extraction
- if self._validate_search_results(results, constraint):
- extracted = self._extract_relevant_candidates(
- results, constraint
- )
- candidates.extend(extracted)
-
- # Track stage information in search history
- if self.search_history:
- self.search_history[-1]["stage"] = getattr(
- self, "current_stage", 0
- )
- self.search_history[-1]["results_count"] = len(extracted)
- self.search_history[-1]["results_preview"] = results.get(
- "current_knowledge", ""
- )[:200]
- else:
- logger.info(f"Skipping invalid results for query: {query}")
-
- # Continue searching to build a comprehensive list
- # Don't stop too early - we want diversity
- if len(candidates) >= self.candidate_limit * 2:
- break
-
- return self._deduplicate_candidates(candidates)
-
- def _generate_additional_queries(self, constraint: Constraint) -> List[str]:
- """Generate additional diverse queries for better coverage."""
- queries = []
- base_value = constraint.value
-
- # Add reference source queries
- queries.extend(
- [
- f"reference {base_value}",
- f"authoritative {base_value}",
- f"official {base_value}",
- ]
- )
-
- # Add structured data queries
- if constraint.type == ConstraintType.STATISTIC:
- queries.extend(
- [
- f"spreadsheet {base_value}",
- f"dataset {base_value}",
- f"statistical analysis {base_value}",
- f"quantitative {base_value}",
- ]
- )
- elif constraint.type == ConstraintType.PROPERTY:
- queries.extend(
- [
- f"characterized by {base_value}",
- f"known for {base_value}",
- f"featuring {base_value}",
- ]
- )
- else:
- # Generic comprehensive queries
- queries.extend(
- [
- f"exhaustive {base_value}",
- f"thorough {base_value}",
- f"detailed {base_value}",
- ]
- )
-
- return queries
-
- def _generate_constraint_specific_queries(
- self, constraint: Constraint
- ) -> List[str]:
- """Generate queries specific to a constraint type."""
- queries = []
- base_value = constraint.value
-
- # Add context from other constraints for more targeted searches
- context_parts = []
- if hasattr(self, "constraints") and self.constraints:
- for other_constraint in self.constraints[
- :2
- ]: # Use top 2 constraints for context
- if other_constraint.id != constraint.id:
- context_parts.append(other_constraint.value)
-
- # Base queries using the constraint description
- if hasattr(constraint, "description") and constraint.description:
- queries.append(constraint.description)
- if context_parts:
- queries.append(f"{constraint.description} {context_parts[0]}")
-
- # Type-specific patterns
- if constraint.type == ConstraintType.STATISTIC:
- # Numeric constraints - look for quantitative information
- queries.extend(
- [
- f"list {base_value}",
- f"complete {base_value}",
- f"all {base_value}",
- f"comprehensive {base_value}",
- f"database {base_value}",
- f"statistics {base_value}",
- f"data {base_value}",
- f"comparison {base_value}",
- ]
- )
-
- elif constraint.type == ConstraintType.EVENT or (
- hasattr(constraint.type, "value")
- and constraint.type.value == "temporal"
- ):
- # Time-based constraints
- queries.extend(
- [
- f"during {base_value}",
- f"in {base_value}",
- f"list {base_value}",
- f"comprehensive {base_value}",
- f"all from {base_value}",
- f"complete list {base_value}",
- f"history {base_value}",
- f"timeline {base_value}",
- ]
- )
-
- elif constraint.type == ConstraintType.PROPERTY:
- # Property constraints - characteristics and attributes
- queries.extend(
- [
- f"with {base_value}",
- f"having {base_value}",
- f"characterized by {base_value}",
- f"examples {base_value}",
- f"instances {base_value}",
- f"who {base_value}",
- f"which {base_value}",
- f"known for {base_value}",
- ]
- )
- else:
- # Generic queries
- queries.extend(
- [
- f"{base_value}",
- f"list {base_value}",
- f"examples {base_value}",
- f"all {base_value}",
- f"complete {base_value}",
- ]
- )
-
- # Add combined queries with other constraints
- if context_parts:
- queries.extend(
- [
- f"{base_value} {context_parts[0]}",
- f"list {base_value} with {context_parts[0]}",
- f"{base_value} and {context_parts[0]}",
- ]
- )
-
- return queries
-
- def _filter_candidates_with_constraint(
- self, candidates: List[Candidate], constraint: Constraint
- ) -> List[Candidate]:
- """Filter existing candidates using an additional constraint."""
- filtered = []
-
- for candidate in candidates:
- # Check if candidate matches the constraint
- query = f"{candidate.name} {constraint.value}"
-
- results = self._execute_search(query)
-
- # Quick evidence check
- evidence = self._quick_evidence_check(
- results, candidate, constraint
- )
-
- if evidence.confidence >= 0.5: # Lower threshold for filtering
- candidate.add_evidence(constraint.id, evidence)
- filtered.append(candidate)
-
- return filtered
-
- def _extract_relevant_candidates(
- self, results: Dict, constraint: Constraint
- ) -> List[Candidate]:
- """Extract candidates relevant to a specific constraint."""
- content = results.get("current_knowledge", "")
-
- # If no content, return empty list
- if not content or "Error" in content or "No results found" in content:
- logger.warning(
- f"No valid content to extract candidates from for constraint: {constraint.description}"
- )
- return []
-
- # Determine what type of entity we're looking for
- entity_type = getattr(self, "entity_type", "entity")
-
- # Use LLM to extract entities matching the constraint
- prompt = f"""Analyze these search results and extract {entity_type} names that could satisfy this constraint:
-
-Constraint: {constraint.description}
-Type: {constraint.type.value}
-Value: {constraint.value}
-
-Search Results:
-{content}
-
-Your task:
-1. Understand what the constraint is asking for
-2. Identify mentions of specific {entity_type} names in the search results
-3. Extract only those names that could potentially satisfy the constraint
-4. Focus on proper nouns and specific names
-
-Important:
-- Extract actual {entity_type} names, not descriptions or categories
-- If the search results mention a specific {entity_type} that matches the constraint criteria, extract it
-- Be thorough - don't miss names that are mentioned in passing
-- Consider the context to determine if a name is relevant to the constraint
-
-Return one {entity_type} name per line. Only include names that could satisfy the constraint."""
-
- try:
- response = self.model.invoke(prompt)
- extracted_text = remove_think_tags(str(response.content))
-
- candidates = []
- seen_names = set() # Track unique names
-
- for line in extracted_text.strip().split("\n"):
- name = line.strip()
- # Remove common list markers and clean up
- name = name.lstrip("- •·*0123456789.").strip()
-
- # Skip empty lines or very short names
- if not name or len(name) <= 2:
- continue
-
- # Normalize for deduplication
- normalized_name = name.lower()
- if normalized_name in seen_names:
- continue
-
- # Exclude meta-commentary patterns
- exclude_patterns = [
- "search result",
- "based on",
- "provided",
- "found",
- "does not",
- "doesn't",
- "cannot",
- "there are no",
- "according to",
- "mentions",
- "discusses",
- "shows that",
- "indicates",
- "suggests",
- "appears",
- "seems",
- "search",
- "constraint",
- "extract",
- "entity",
- ]
-
- # Check if it's meta-commentary
- is_meta = any(
- pattern in name.lower() for pattern in exclude_patterns
- )
- is_too_long = (
- len(name.split()) > 10
- ) # Very long strings are usually explanations
- is_sentence = name.endswith(".") and len(name.split()) > 5
-
- if not is_meta and not is_too_long and not is_sentence:
- # Accept various name formats
- if (
- name[0].isupper() # Capitalized
- or any(c.isupper() for c in name) # Has capitals
- or any(c.isdigit() for c in name) # Contains numbers
- or any(
- c in name
- for c in ["-", "&", "/", ":", "(", ")", '"', "'"]
- ) # Special chars
- or len(name.split()) <= 6
- ): # Reasonable length phrases
- candidate = Candidate(name=name)
- candidates.append(candidate)
- seen_names.add(normalized_name)
-
- # Log extraction results for debugging
- logger.info(
- f"Extracted {len(candidates)} candidates for constraint: {constraint.description}"
- )
- if candidates:
- logger.debug(
- f"Sample candidates: {[c.name for c in candidates[:5]]}"
- )
-
- return candidates[:50] # Limit per search
-
- except Exception:
- logger.exception("Error extracting candidates")
- return []
-
- def _quick_evidence_check(
- self, results: Dict, candidate: Candidate, constraint: Constraint
- ) -> Evidence:
- """Quick evidence check for filtering with enhanced scoring."""
- content = results.get("current_knowledge", "")
- search_results = results.get("search_results", [])
-
- # Initialize confidence components
- name_presence = 0.0
- constraint_presence = 0.0
- co_occurrence = 0.0
- context_quality = 0.0
-
- candidate_lower = candidate.name.lower()
- # NOTE: constraint.value is always a str from ConstraintAnalyzer.
- # The truthiness guard handles empty strings correctly. Do NOT
- # change to "is not None" — for hypothetical value=0, "0"
- # would match nearly all content and inflate scores.
- value_lower = str(constraint.value).lower() if constraint.value else ""
- content_lower = content.lower()
-
- # Check candidate name presence
- if candidate_lower in content_lower:
- name_count = content_lower.count(candidate_lower)
- name_presence = min(
- 0.3 + (name_count * 0.05), 0.4
- ) # More occurrences = higher confidence
-
- # Check constraint value presence
- if value_lower and value_lower in content_lower:
- value_count = content_lower.count(value_lower)
- constraint_presence = min(0.3 + (value_count * 0.05), 0.4)
-
- # Check co-occurrence and proximity
- if name_presence > 0 and constraint_presence > 0:
- # Find all positions
- name_positions = []
- start = 0
- while start < len(content_lower):
- pos = content_lower.find(candidate_lower, start)
- if pos == -1:
- break
- name_positions.append(pos)
- start = pos + 1
-
- value_positions = []
- start = 0
- while start < len(content_lower):
- pos = content_lower.find(value_lower, start)
- if pos == -1:
- break
- value_positions.append(pos)
- start = pos + 1
-
- # Calculate minimum distance
- if name_positions and value_positions:
- min_distance = min(
- abs(n - v) for n in name_positions for v in value_positions
- )
-
- if min_distance < 100: # Very close proximity
- co_occurrence = 0.2
- elif min_distance < 200: # Close proximity
- co_occurrence = 0.15
- elif min_distance < 500: # Moderate proximity
- co_occurrence = 0.1
- else: # Same document
- co_occurrence = 0.05
-
- # Check result quality
- if search_results:
- # Count how many results mention both candidate and constraint
- relevant_results = 0
- for result in search_results[:10]:
- title = result.get("title", "").lower()
- snippet = result.get("snippet", "").lower()
-
- if (
- (candidate_lower in title or candidate_lower in snippet)
- and value_lower
- and (value_lower in title or value_lower in snippet)
- ):
- relevant_results += 1
-
- context_quality = min(relevant_results * 0.05, 0.2)
-
- # Calculate final confidence
- confidence = (
- name_presence
- + constraint_presence
- + co_occurrence
- + context_quality
- )
-
- # Apply constraint type weight
- if constraint.type == ConstraintType.STATISTIC:
- confidence *= 1.1 # Numeric constraints need precise matching
- elif constraint.type == ConstraintType.PROPERTY:
- confidence *= 0.95 # Properties can be more flexible
-
- return Evidence(
- claim=f"Evidence for {candidate.name} matching {constraint.description}",
- confidence=min(confidence, 1.0),
- type=EvidenceType.INFERENCE,
- source="quick_evidence_check",
- metadata={
- "name_presence": name_presence,
- "constraint_presence": constraint_presence,
- "co_occurrence": co_occurrence,
- "context_quality": context_quality,
- },
- )
-
- def _focused_evidence_gathering(self):
- """Gather detailed evidence for the narrowed candidates."""
- if self.progress_callback:
- constraint_count = len(self.constraints)
- evidence_needed = len(self.candidates) * constraint_count
- self.progress_callback(
- f"Verifying {len(self.candidates)} candidates against {constraint_count} constraints ({evidence_needed} checks)",
- 80,
- {
- "phase": "evidence_gathering",
- "candidate_count": len(self.candidates),
- "constraint_count": constraint_count,
- "total_evidence_needed": evidence_needed,
- },
- )
-
- for i, candidate in enumerate(self.candidates):
- for j, constraint in enumerate(self.constraints):
- # Skip if we already have evidence from filtering
- if constraint.id in candidate.evidence:
- continue
-
- # Detailed evidence search
- query = f'"{candidate.name}" {constraint.value} verification'
- results = self._execute_search(query)
-
- evidence = self.evidence_evaluator.extract_evidence(
- results.get("current_knowledge", ""),
- candidate.name,
- constraint,
- )
-
- candidate.add_evidence(constraint.id, evidence)
-
- if (
- self.progress_callback and i < 5
- ): # Report progress for top candidates
- conf_emoji = (
- "✓"
- if evidence.confidence >= self.evidence_threshold
- else "○"
- )
- self.progress_callback(
- f"{conf_emoji} {candidate.name} | {constraint.type.value}: {evidence.confidence:.0%}",
- None,
- {
- "phase": "evidence_detail",
- "candidate": candidate.name,
- "constraint": constraint.description,
- "constraint_type": constraint.type.value,
- "confidence": evidence.confidence,
- "evidence_type": evidence.type.value,
- "meets_threshold": evidence.confidence
- >= self.evidence_threshold,
- },
- )
-
- # Final scoring
- for candidate in self.candidates:
- candidate.calculate_score(self.constraints)
-
- # Sort by score
- self.candidates.sort(key=lambda c: c.score, reverse=True)
-
- def _deduplicate_candidates(
- self, candidates: List[Candidate]
- ) -> List[Candidate]:
- """Remove duplicate candidates."""
- seen = {}
- unique = []
-
- for candidate in candidates:
- key = candidate.name.lower().strip()
- if key not in seen:
- seen[key] = candidate
- unique.append(candidate)
-
- return unique
-
- def _format_constraint_analysis(self) -> str:
- """Format initial constraint analysis."""
- analysis = "**Query Constraint Analysis**\n\n"
- analysis += f"Total constraints identified: {len(self.constraints)}\n\n"
- analysis += "**Constraint Ranking (by restrictiveness):**\n"
-
- for i, constraint in enumerate(self.constraint_ranking):
- score = self._calculate_restrictiveness_score(constraint)
- analysis += (
- f"{i + 1}. [{constraint.type.value}] {constraint.description}\n"
- )
- analysis += f" Restrictiveness score: {score}\n"
- analysis += f" Value: {constraint.value}\n\n"
-
- return analysis
-
- def _format_debug_summary(self) -> str:
- """Format comprehensive debug summary."""
- summary = "**Debug Summary**\n\n"
-
- # Constraint analysis
- summary += "**Constraint Processing:**\n"
- for i, constraint in enumerate(self.constraint_ranking):
- score = self._calculate_restrictiveness_score(constraint)
- summary += f"{i + 1}. [{constraint.type.value}] {constraint.value} (score: {score})\n"
-
- # Search progression
- summary += "\n**Search Progression:**\n"
- if hasattr(self, "stage_candidates"):
- for stage, candidates in self.stage_candidates.items():
- summary += f"Stage {stage + 1}: {len(candidates)} candidates\n"
-
- # Evidence coverage
- summary += "\n**Evidence Coverage:**\n"
-
- for i, candidate in enumerate(self.candidates[:5]):
- evidence_count = len(candidate.evidence)
- satisfied = sum(
- 1
- for c in self.constraints
- if c.id in candidate.evidence
- and candidate.evidence[c.id].confidence
- >= self.evidence_threshold
- )
-
- summary += f"{i + 1}. {candidate.name}: {evidence_count} evidence, "
- summary += f"{satisfied}/{len(self.constraints)} constraints\n"
-
- # Search statistics
- summary += "\n**Search Statistics:**\n"
- total_discovered = (
- sum(len(c) for c in self.stage_candidates.values())
- if hasattr(self, "stage_candidates")
- else 0
- )
- summary += f"Total candidates discovered: {total_discovered}\n"
- summary += f"Final candidates: {len(self.candidates)}\n"
- summary += f"Constraints: {len(self.constraints)}\n"
-
- return summary
-
- def _calculate_restrictiveness_score(self, constraint: Constraint) -> int:
- """Calculate restrictiveness score for a constraint."""
- score = 0
-
- # Type-based scoring
- if constraint.type == ConstraintType.STATISTIC:
- score += 10
- elif constraint.type == ConstraintType.EVENT:
- score += 8
- elif constraint.type == ConstraintType.LOCATION:
- score += 6
- elif constraint.type == ConstraintType.PROPERTY:
- score += 4
-
- # NOTE: constraint.value is always a str from
- # ConstraintAnalyzer. The truthiness guard is intentional.
- if constraint.value:
- if any(char.isdigit() for char in constraint.value):
- score += 5
- if len(constraint.value.split()) > 3:
- score += 3
- if any(
- term in constraint.value.lower()
- for term in ["specific", "exact", "only", "must"]
- ):
- score += 2
-
- return score
-
- def _format_stage_results(
- self, stage: int, constraint: Constraint, candidates: List[Candidate]
- ) -> str:
- """Format results for a search stage with detailed information."""
- result = f"**Search Stage {stage + 1}**\n\n"
- result += f"Constraint: {constraint.description}\n"
- result += f"Type: {constraint.type.value}\n"
- result += f"Search Value: {constraint.value}\n"
- result += f"Candidates found: {len(candidates)}\n\n"
-
- # Add search statistics
- result += "**Search Statistics:**\n"
- if hasattr(self, "search_history"):
- stage_searches = [
- s for s in self.search_history if s.get("stage", -1) == stage
- ]
- result += f"- Queries executed: {len(stage_searches)}\n"
- result += f"- Total results analyzed: {getattr(self, f'stage_{stage}_results_count', 0)}\n"
-
- result += f"- Candidates before filtering: {getattr(self, f'stage_{stage}_raw_candidates', len(candidates))}\n"
- result += f"- Candidates after deduplication: {len(candidates)}\n\n"
-
- if candidates:
- result += "**Top Candidates:**\n"
- # Group candidates to show variety
- grouped = self._group_similar_candidates(candidates[:20])
- for group_name, group_items in grouped.items():
- result += f"\n{group_name} ({len(group_items)} items):\n"
- for i, candidate in enumerate(group_items[:5]):
- result += f" {i + 1}. {candidate.name}\n"
- if len(group_items) > 5:
- result += f" ... and {len(group_items) - 5} more\n"
- else:
- result += "No candidates found for this constraint.\n"
-
- # Add sample search results for debugging
- if hasattr(self, "search_history") and candidates:
- result += "\n**Sample Search Results:**\n"
- recent_searches = [
- s
- for s in self.search_history[-3:]
- if s.get("stage", -1) == stage
- ]
- for search in recent_searches[:2]:
- result += f"- Query: '{search.get('query', '')}'\n"
- if "results_preview" in search:
- result += (
- f" Preview: {search['results_preview'][:100]}...\n"
- )
-
- return result
-
- def _format_search_summary(self) -> str:
- """Format progressive search summary."""
- summary = "**Progressive Search Summary**\n\n"
-
- # Show search progression
- summary += "**Stage-by-Stage Filtering:**\n"
- prev_count = 0
-
- for stage, candidates in self.stage_candidates.items():
- constraint = (
- self.constraint_ranking[stage]
- if stage < len(self.constraint_ranking)
- else None
- )
- if constraint:
- count = len(candidates)
- change = count - prev_count if stage > 0 else count
- change_str = f" ({change:+d})" if stage > 0 else ""
-
- summary += f"\nStage {stage + 1} [{constraint.type.value}]: {str(constraint.value)[:40]}\n"
- summary += f" Results: {count} candidates{change_str}\n"
-
- if candidates:
- # Group candidates by type
- grouped = self._group_similar_candidates(candidates[:20])
- for group_name, group_items in grouped.items():
- summary += f" {group_name}: {len(group_items)} items\n"
- for item in group_items[:3]:
- summary += f" • {item.name}\n"
- if len(group_items) > 3:
- summary += (
- f" ... and {len(group_items) - 3} more\n"
- )
-
- prev_count = count
-
- summary += (
- f"\n**Final Result: {len(self.candidates)} candidates selected**\n"
- )
-
- return summary
-
- def _format_evidence_summary(self) -> str:
- """Format evidence gathering summary."""
- summary = "**Evidence Gathering Summary**\n\n"
-
- for i, candidate in enumerate(self.candidates[:5]):
- summary += f"**{i + 1}. {candidate.name}**\n"
-
- for constraint in self.constraints:
- evidence = candidate.evidence.get(constraint.id)
- if evidence:
- conf_str = f"{evidence.confidence:.0%}"
- summary += (
- f" • {constraint.description[:40]}...: {conf_str}\n"
- )
- else:
- summary += (
- f" • {constraint.description[:40]}...: No evidence\n"
- )
-
- summary += f" Overall Score: {candidate.score:.2f}\n\n"
-
- return summary
-
- # Commented out to use the parent's optimized _execute_search method
- '''def _execute_search(self, search_query: str) -> Dict:
- """Execute a comprehensive search using source-based strategy for complex queries."""
- if not hasattr(self, "search_history"):
- self.search_history = []
-
- self.search_history.append(
- {
- "query": search_query,
- "timestamp": self._get_timestamp(),
- "iteration": getattr(self, "iteration", 0),
- }
- )
-
- # Debug: Check if search engine is available
- if not hasattr(self, "search") or self.search is None:
- logger.error(f"No search engine configured for query: {search_query}")
- logger.error(f"Strategy attributes: {list(self.__dict__.keys())}")
- return {"current_knowledge": "", "search_results": []}
-
- try:
- # Log that we're attempting to use source-based strategy
- logger.info(f"Attempting source-based search for: {search_query}")
-
- # For complex queries, use source-based strategy with multiple iterations
- if hasattr(self, "source_strategy"):
- source_strategy = self.source_strategy
- else:
- logger.info("Creating new SourceBasedSearchStrategy instance")
- source_strategy = SourceBasedSearchStrategy(
- model=self.model,
- search=self.search,
- all_links_of_system=self.all_links_of_system,
- include_text_content=True,
- use_cross_engine_filter=False, # We'll handle filtering ourselves
- use_atomic_facts=False,
- )
- source_strategy.max_iterations = (
- 1 # More efficient with single iteration
- )
- source_strategy.questions_per_iteration = (
- 9 # More questions for broader coverage
- )
-
- # Use source-based strategy for complex search
- try:
- # Set a simple progress callback if we have one
- if self.progress_callback:
-
- def sub_callback(msg, prog, data):
- # Don't propagate all sub-progress updates
- if "phase" in data and data["phase"] in [
- "search_complete",
- "final_results",
- ]:
- self.progress_callback(f"Sub-search: {msg}", None, data)
-
- source_strategy.set_progress_callback(sub_callback)
-
- logger.info("Executing source-based search...")
- # Run the search
- result = source_strategy.analyze_topic(search_query)
-
- if (
- result
- and "current_knowledge" in result
- and "all_links_of_system" in result
- ):
- search_results = result.get("all_links_of_system", [])
-
- # Extract the most relevant information from the findings
- knowledge_parts = []
- if "findings" in result:
- for finding in result["findings"]:
- if "content" in finding and finding["content"]:
- knowledge_parts.append(finding["content"])
-
- # Also include search results summaries
- for i, link in enumerate(search_results[:15]): # More results
- if isinstance(link, dict):
- title = link.get("title", "")
- snippet = link.get("snippet", "")
- content = link.get("content", "")
- url = link.get("link", link.get("url", ""))
-
- if title or snippet:
- result_text = f"\nResult {i+1}: {title}"
- if url:
- result_text += f"\nURL: {url}"
- if snippet:
- result_text += f"\nSnippet: {snippet}"
- if content and content != snippet:
- result_text += f"\nContent: {content[:500]}..."
- knowledge_parts.append(result_text)
-
- current_knowledge = "\n\n".join(knowledge_parts)
-
- return {
- "current_knowledge": current_knowledge,
- "search_results": search_results,
- "detailed_findings": result.get("findings", []),
- }
- else:
- # Fallback to simple search
- logger.warning(
- "Source-based search returned empty results, falling back to simple search"
- )
- return self._simple_search(search_query)
-
- except Exception as e:
- logger.exception("Source-based search failed")
- logger.warning("Falling back to simple search")
- return self._simple_search(search_query)
-
- except Exception as e:
- logger.error(f"Error during search for '{search_query}': {str(e)}")
- return {
- "current_knowledge": f"Error during search: {str(e)}",
- "search_results": [],
- }'''
-
- def _simple_search(self, search_query: str) -> Dict:
- """Fallback simple search using search engine directly."""
- try:
- # Use the search engine directly for simple queries
- search_results = self.search.run(search_query)
-
- if search_results and isinstance(search_results, list):
- # Format search results into a knowledge string
- content_parts = []
-
- for i, result in enumerate(search_results[:15]): # More results
- title = result.get("title", "Untitled")
- snippet = result.get("snippet", "")
- content = result.get("content", "")
- url = result.get("link", result.get("url", ""))
-
- content_parts.append(f"Result {i + 1}: {title}")
- if url:
- content_parts.append(f"URL: {url}")
- if snippet:
- content_parts.append(f"Snippet: {snippet}")
- if content and content != snippet:
- content_parts.append(
- f"Content preview: {content[:300]}..."
- )
- content_parts.append("") # Empty line between results
-
- current_knowledge = "\n".join(content_parts)
-
- return {
- "current_knowledge": current_knowledge,
- "search_results": search_results,
- }
- # Return empty knowledge if no results
- return {
- "current_knowledge": f"No results found for query: {search_query}",
- "search_results": [],
- }
- except Exception as e:
- logger.exception("Simple search error")
- return {
- "current_knowledge": f"Search error: {e!s}",
- "search_results": [],
- }
-
- def _validate_search_results(
- self, results: Dict, constraint: Constraint
- ) -> bool:
- """Validate that search results contain relevant information."""
- if not results:
- return False
-
- content = results.get("current_knowledge", "")
- search_results = results.get("search_results", [])
-
- # Basic validation checks
- if not content or len(content) < 50: # Too short to be meaningful
- logger.debug(f"Content too short: {len(content)} characters")
- return False
-
- if "Error" in content and len(content) < 100:
- logger.debug(f"Error in results: {content[:100]}")
- return False
-
- if "No results found" in content:
- logger.debug("No results found")
- return False
-
- # NOTE: constraint.value is always a str from ConstraintAnalyzer
- # (constraint_analyzer.py:91). Do NOT change this to
- # "is not None" — for hypothetical non-string falsy values
- # like 0.0, that would reject content missing the literal
- # string "0.0". The truthiness guard correctly skips empty
- # values, falling through to the quality check below.
- if constraint.value:
- value_str = str(constraint.value).lower()
- constraint_terms = [
- term
- for term in value_str.split()
- if len(term) > 2
- and term
- not in ["the", "and", "with", "for", "had", "his", "her"]
- ]
- content_lower = content.lower()
-
- # Count how many meaningful terms appear
- if constraint_terms:
- term_matches = sum(
- 1 for term in constraint_terms if term in content_lower
- )
- relevance_ratio = term_matches / len(constraint_terms)
-
- # Require at least one term match
- if relevance_ratio < 0.2:
- logger.debug(
- f"Low relevance: {relevance_ratio:.0%} term matches"
- )
- return False
-
- # Check search results quality
- if search_results and isinstance(search_results, list):
- valid_results = sum(
- 1
- for r in search_results
- if isinstance(r, dict) and (r.get("title") or r.get("snippet"))
- )
- if valid_results < 1:
- logger.debug("No valid search results with title/snippet")
- return False
-
- return True
-
- def _get_timestamp(self) -> str:
- """Get current timestamp."""
- return datetime.now(UTC).isoformat()
-
- def _group_similar_candidates(
- self, candidates: List[Candidate]
- ) -> Dict[str, List[Candidate]]:
- """Group candidates by similar characteristics."""
- grouped = {}
-
- for candidate in candidates:
- # Try to determine group type based on name patterns
- name = candidate.name.lower()
-
- if any(
- keyword in name
- for keyword in ["model", "llm", "gpt", "claude", "gemini"]
- ):
- group = "AI Models"
- elif any(
- keyword in name
- for keyword in ["country", "nation", "republic", "kingdom"]
- ):
- group = "Countries"
- elif any(
- keyword in name for keyword in ["city", "town", "village"]
- ):
- group = "Cities"
- elif any(
- keyword in name for keyword in ["year", "century", "decade"]
- ):
- group = "Time Periods"
- elif any(
- keyword in name
- for keyword in ["person", "mr", "ms", "dr", "prof"]
- ):
- group = "People"
- elif any(c.isdigit() for c in name):
- group = "Numeric Items"
- else:
- # Default grouping based on first word
- first_word = (
- candidate.name.split()[0]
- if candidate.name.split()
- else "Other"
- )
- group = f"{first_word} Items"
-
- if group not in grouped:
- grouped[group] = []
- grouped[group].append(candidate)
-
- return grouped
diff --git a/src/local_deep_research/advanced_search_system/strategies/constraint_parallel_strategy.py b/src/local_deep_research/advanced_search_system/strategies/constraint_parallel_strategy.py
deleted file mode 100644
index b2040e69f6..0000000000
--- a/src/local_deep_research/advanced_search_system/strategies/constraint_parallel_strategy.py
+++ /dev/null
@@ -1,547 +0,0 @@
-"""
-Constraint Parallel Strategy for search optimization.
-
-Key features:
-1. Runs separate searches for each constraint in parallel
-2. Uses entity type detection to focus all searches
-3. Collects candidates from all constraint-specific searches
-4. Evaluates candidates using the existing evaluation system
-5. Early rejection of poor candidates for efficiency
-"""
-
-import concurrent.futures
-import threading
-import time
-from dataclasses import dataclass, field
-from typing import Dict, List, Optional, Tuple
-
-from loguru import logger
-
-from ...database.thread_local_session import thread_cleanup
-from ..candidates.base_candidate import Candidate
-from ..constraints.base_constraint import Constraint
-from .dual_confidence_with_rejection import DualConfidenceWithRejectionStrategy
-
-
-@dataclass
-class ConstraintSearchState:
- """Tracks the state of parallel constraint-specific searches."""
-
- all_candidates: List[Candidate] = field(default_factory=list)
- evaluated_candidates: List[Tuple[Candidate, float]] = field(
- default_factory=list
- )
- total_evaluated: int = 0
- start_time: float = field(default_factory=time.time)
- constraint_searches: Dict[str, List[Candidate]] = field(
- default_factory=dict
- )
- candidates_lock: threading.Lock = field(default_factory=threading.Lock)
- stop_search: threading.Event = field(default_factory=threading.Event)
- evaluation_futures: List[concurrent.futures.Future] = field(
- default_factory=list
- )
- entity_type: str = "unknown entity"
-
-
-class ConstraintParallelStrategy(DualConfidenceWithRejectionStrategy):
- """
- Strategy that runs parallel searches for each constraint independently.
-
- Rather than combining constraints in queries, this approach:
- 1. Runs a separate search for each constraint in parallel
- 2. Uses entity type to focus all searches
- 3. Collects candidates from all constraint searches
- 4. Evaluates candidates as they're found
- 5. Identifies candidates that match multiple constraints
- """
-
- def __init__(
- self,
- *args,
- # Concurrent execution settings
- max_workers: int = 10,
- # Candidate targets
- min_good_candidates: int = 3,
- target_candidates: int = 5,
- max_candidates: int = 10,
- # Quality thresholds
- min_score_threshold: float = 0.65,
- exceptional_score: float = 0.95,
- quality_plateau_threshold: float = 0.1,
- # Time and resource limits
- max_search_time: float = 30.0,
- max_evaluations: int = 30,
- # Search behavior
- initial_search_timeout: float = 5.0,
- **kwargs,
- ):
- super().__init__(*args, **kwargs)
-
- # Thread pool for concurrent operations
- self.search_executor = concurrent.futures.ThreadPoolExecutor(
- max_workers=max_workers
- )
- self.evaluation_executor = concurrent.futures.ThreadPoolExecutor(
- max_workers=max_workers
- )
-
- # Candidate thresholds
- self.min_good_candidates = min_good_candidates
- self.target_candidates = target_candidates
- self.max_candidates = max_candidates
-
- # Quality settings
- self.min_score_threshold = min_score_threshold
- self.exceptional_score = exceptional_score
- self.quality_plateau_threshold = quality_plateau_threshold
-
- # Resource limits
- self.max_search_time = max_search_time
- self.max_evaluations = max_evaluations
- self.initial_search_timeout = initial_search_timeout
-
- # Search state
- self.state: Optional[ConstraintSearchState] = None
-
- def close(self):
- """Shut down persistent thread pool executors.
-
- These executors are also shut down in find_relevant_information()'s
- finally block, but this close() handles the edge case where the
- strategy is instantiated but find_relevant_information() is never
- called (or raises before reaching its finally block).
-
- Uses wait=False because wait=True would block the research thread
- waiting for all submitted tasks to complete. This is safe because
- the double-cleanup pattern (finally block + this close()) ensures
- shutdown is called at least once; calling it twice is idempotent.
- """
- if hasattr(self, "search_executor"):
- try:
- self.search_executor.shutdown(wait=False)
- except Exception:
- logger.exception("Error shutting down search executor")
- if hasattr(self, "evaluation_executor"):
- try:
- self.evaluation_executor.shutdown(wait=False)
- except Exception:
- logger.exception("Error shutting down evaluation executor")
-
- def find_relevant_information(self):
- """Override to use parallel constraint-specific searches."""
- # Initialize state
- self.state = ConstraintSearchState(start_time=time.time())
-
- # Detect entity type first to guide all searches
- self.state.entity_type = self._detect_entity_type()
- logger.info(f"Detected entity type: {self.state.entity_type}")
-
- if self.progress_callback:
- self.progress_callback(
- f"Starting parallel searches for {self.state.entity_type}",
- 10,
- {
- "phase": "entity_detection",
- "entity_type": self.state.entity_type,
- },
- )
-
- # Start parallel constraint searches with concurrent evaluation
- try:
- self._run_parallel_constraint_searches()
- finally:
- # Clean up thread pools
- self.search_executor.shutdown(wait=False)
- self.evaluation_executor.shutdown(wait=False)
-
- # Return best candidates
- self.candidates = [
- c
- for c, _ in sorted(
- self.state.evaluated_candidates,
- key=lambda x: x[1],
- reverse=True,
- )[: self.max_candidates]
- ]
-
- logger.info(
- f"Found {len(self.candidates)} candidates after parallel constraint searches"
- )
-
- def _detect_entity_type(self) -> str:
- """Use LLM to detect what type of entity we're searching for."""
- # Build context from constraints
- constraint_text = "\n".join(
- [f"- {c.value}" for c in self.constraint_ranking]
- )
-
- prompt = f"""
- Analyze these search constraints and determine what type of entity is being searched for:
-
- Constraints:
- {constraint_text}
-
- What is the primary entity type being searched for? Be specific.
-
- Examples of entity types (but you can choose any appropriate type):
- - fictional character
- - TV show
- - movie
- - actor/actress
- - historical figure
- - company
- - product
- - location
- - event
-
- Respond with just the entity type.
- """
-
- try:
- entity_type = self.model.invoke(prompt).content.strip()
- logger.info(f"LLM determined entity type: {entity_type}")
- return entity_type
- except Exception:
- logger.exception("Failed to detect entity type")
- return "unknown entity"
-
- def _run_parallel_constraint_searches(self):
- """Run separate searches for each constraint in parallel."""
- # Submit a search for each constraint
- search_futures = {}
-
- for i, constraint in enumerate(self.constraint_ranking):
- if self.state.stop_search.is_set():
- break
-
- logger.info(
- f"Scheduling search for constraint {i + 1}/{len(self.constraint_ranking)}: {constraint.value}"
- )
-
- # Submit search task
- future = self.search_executor.submit(
- self._run_constraint_search,
- constraint,
- i,
- len(self.constraint_ranking),
- )
- search_futures[future] = constraint
-
- # Process results as they complete
- for future in concurrent.futures.as_completed(search_futures):
- if self.state.stop_search.is_set():
- break
-
- constraint = search_futures[future]
- try:
- candidates = future.result()
-
- # Store results by constraint
- with self.state.candidates_lock:
- self.state.constraint_searches[constraint.id] = candidates
- # Add to overall candidate pool
- self.state.all_candidates.extend(candidates)
-
- logger.info(
- f"Constraint '{constraint.value[:30]}...' found {len(candidates)} candidates"
- )
-
- # Submit candidates for evaluation
- self._submit_candidates_for_evaluation(candidates)
-
- except Exception:
- logger.exception(
- f"Search failed for constraint {constraint.value}"
- )
-
- # Wait for evaluations to complete
- self._finalize_evaluations()
-
- @thread_cleanup
- def _run_constraint_search(
- self, constraint: Constraint, index: int, total: int
- ) -> List[Candidate]:
- """Execute search for a specific constraint."""
- try:
- # Build a query combining entity type and constraint
- query = self._build_constraint_query(constraint)
-
- if self.progress_callback:
- self.progress_callback(
- f"Searching for constraint {index + 1}/{total}: {constraint.value[:30]}...",
- 20 + int(30 * (index / total)),
- {
- "phase": "constraint_search",
- "constraint_index": index,
- "constraint_total": total,
- "constraint_value": constraint.value,
- },
- )
-
- # Execute search
- search_results = self._execute_search(query)
-
- # Extract candidates
- candidates = self._extract_relevant_candidates(
- search_results, constraint
- )
-
- logger.info(
- f"Found {len(candidates)} candidates for constraint: {constraint.value[:30]}..."
- )
- return candidates
-
- except Exception:
- logger.exception("Error in constraint search")
- return []
-
- def _build_constraint_query(self, constraint: Constraint) -> str:
- """Build a query combining entity type and constraint."""
- # Get entity type
- entity_type = self.state.entity_type
- query_parts = []
-
- # Always include entity type if known
- if entity_type and entity_type != "unknown entity":
- # Add entity type as a search term
- if " " in entity_type and not entity_type.startswith('"'):
- query_parts.append(f'"{entity_type}"')
- else:
- query_parts.append(entity_type)
-
- # Add constraint
- value = constraint.value
- if " " in value and not value.startswith('"'):
- query_parts.append(f'"{value}"')
- else:
- query_parts.append(value)
-
- # Convert constraint to search-friendly terms based on type
- search_terms = constraint.to_search_terms()
- if search_terms and search_terms != value:
- query_parts.append(search_terms)
-
- return " ".join(query_parts)
-
- def _submit_candidates_for_evaluation(self, candidates: List[Candidate]):
- """Submit candidates for concurrent evaluation."""
- for candidate in candidates:
- if self.state.stop_search.is_set():
- break
-
- if self.state.total_evaluated >= self.max_evaluations:
- logger.info("Reached maximum evaluations limit")
- self.state.stop_search.set()
- break
-
- # Check if we already evaluated this candidate
- if self._is_candidate_evaluated(candidate):
- continue
-
- # Submit for evaluation
- future = self.evaluation_executor.submit(
- self._evaluate_candidate_thread, candidate
- )
- self.state.evaluation_futures.append(future)
- self.state.total_evaluated += 1
-
- @thread_cleanup
- def _evaluate_candidate_thread(
- self, candidate: Candidate
- ) -> Tuple[Candidate, float]:
- """Evaluate a candidate in a separate thread."""
- try:
- thread_name = threading.current_thread().name
- logger.info(
- f"[{thread_name}] Starting evaluation of {candidate.name}"
- )
-
- # FIRST CHECK: Verify that candidate matches the expected entity type
- entity_match_score = self._verify_entity_type_match(candidate)
- if entity_match_score < 0.5: # Threshold for entity type match
- logger.info(
- f"[{thread_name}] ❌ {candidate.name} rejected - Not a {self.state.entity_type} (score: {entity_match_score:.3f})"
- )
- return (candidate, 0.0)
-
- # Continue with parent's evaluation with early rejection
- score = self._evaluate_candidate_immediately(candidate)
-
- # Log result
- if score >= self.min_score_threshold:
- logger.info(
- f"[{thread_name}] ✓ {candidate.name} passed (score: {score:.3f})"
- )
-
- # Add to good candidates
- with self.state.candidates_lock:
- self.state.evaluated_candidates.append((candidate, score))
-
- # Check if we should stop
- if self._should_stop_search():
- logger.info("Stopping criteria met after evaluation")
- self.state.stop_search.set()
- else:
- logger.info(
- f"[{thread_name}] ❌ {candidate.name} rejected (score: {score:.3f})"
- )
-
- return (candidate, score)
-
- except Exception:
- logger.exception(f"Error evaluating {candidate.name}")
- return (candidate, 0.0)
-
- def _verify_entity_type_match(self, candidate: Candidate) -> float:
- """Verify that the candidate matches the expected entity type.
-
- Returns:
- float: Score between 0.0 and 1.0 indicating confidence that candidate matches the entity type
- """
- entity_type = self.state.entity_type
- candidate_name = candidate.name
-
- # Skip check if entity type is unknown
- if not entity_type or entity_type == "unknown entity":
- return 1.0
-
- # Use LLM to verify entity type match
- try:
- prompt = f"""
- Determine whether "{candidate_name}" is a specific {entity_type} or a general category/collection.
-
- Rules:
- 1. A specific {entity_type} refers to a single, identifiable instance (e.g., "Mount Rainier" is a specific mountain)
- 2. A general category refers to a group or collection (e.g., "U.S. national parks" is a category, not a specific location)
- 3. Be strict - answer must be a single, concrete {entity_type}
-
- Return ONLY a score from 0.0 to 1.0 where:
- - 1.0 = Definitely a specific {entity_type}
- - 0.5 = Unclear or partially matches
- - 0.0 = Definitely NOT a specific {entity_type} (too general or wrong type)
-
- Score:
- """
-
- response = self.model.invoke(prompt).content.strip()
-
- # Extract numeric score from response
- try:
- score = float(response.split()[0].strip())
- # Ensure score is in valid range
- score = max(0.0, min(score, 1.0))
- logger.info(
- f"Entity type check for {candidate_name}: {score:.2f} (entity type: {entity_type})"
- )
- return score
- except (ValueError, IndexError):
- logger.warning(
- f"Could not parse entity type score from: {response}"
- )
- return 0.5 # Default to middle value on parsing error
-
- except Exception:
- logger.exception(
- f"Error verifying entity type for {candidate_name}"
- )
- return 0.5 # Default to middle value on error
-
- def _is_candidate_evaluated(self, candidate: Candidate) -> bool:
- """Check if we already evaluated this candidate."""
- with self.state.candidates_lock:
- return any(
- c.name == candidate.name
- for c, _ in self.state.evaluated_candidates
- )
-
- def _should_stop_search(self) -> bool:
- """Determine if we should stop searching based on multiple criteria."""
- # Always respect the stop flag
- if self.state.stop_search.is_set():
- return True
-
- num_good = len(self.state.evaluated_candidates)
-
- # 1. Maximum candidates reached
- if num_good >= self.max_candidates:
- logger.info(f"Maximum candidates reached ({self.max_candidates})")
- return True
-
- # 2. Target reached with good quality
- if num_good >= self.target_candidates:
- avg_score = (
- sum(s for _, s in self.state.evaluated_candidates) / num_good
- )
- if avg_score >= 0.8:
- logger.info(
- f"Target reached with high quality (avg: {avg_score:.3f})"
- )
- return True
-
- # 3. Minimum satisfied with exceptional candidates
- if num_good >= self.min_good_candidates:
- top_score = max(s for _, s in self.state.evaluated_candidates)
- if top_score >= self.exceptional_score:
- logger.info(
- f"Exceptional candidate found (score: {top_score:.3f})"
- )
- return True
-
- # 4. Time limit reached
- elapsed = time.time() - self.state.start_time
- if elapsed > self.max_search_time:
- logger.info(f"Time limit reached ({elapsed:.1f}s)")
- return True
-
- # 5. Too many evaluations
- if self.state.total_evaluated >= self.max_evaluations:
- logger.info(f"Evaluation limit reached ({self.max_evaluations})")
- return True
-
- # 6. Quality plateau detection
- if num_good >= 5:
- recent_scores = [s for _, s in self.state.evaluated_candidates[-5:]]
- score_range = max(recent_scores) - min(recent_scores)
- if score_range < self.quality_plateau_threshold:
- logger.info(
- f"Quality plateau detected (range: {score_range:.3f})"
- )
- return True
-
- return False
-
- def _finalize_evaluations(self):
- """Wait for or cancel remaining evaluations."""
- if self.state.evaluation_futures:
- logger.info(
- f"Finalizing {len(self.state.evaluation_futures)} remaining evaluations"
- )
-
- # Give them a short time to complete
- wait_time = min(
- 5.0,
- self.max_search_time - (time.time() - self.state.start_time),
- )
- if wait_time > 0:
- concurrent.futures.wait(
- self.state.evaluation_futures,
- timeout=wait_time,
- return_when=concurrent.futures.FIRST_COMPLETED,
- )
-
- # Cancel any still running
- for future in self.state.evaluation_futures:
- if not future.done():
- future.cancel()
-
- # Final report
- logger.info(
- f"""
-Search completed:
-- Total evaluated: {self.state.total_evaluated}
-- Good candidates found: {len(self.state.evaluated_candidates)}
-- Time taken: {time.time() - self.state.start_time:.1f}s
-- Constraint searches: {len(self.state.constraint_searches)}
-"""
- )
diff --git a/src/local_deep_research/advanced_search_system/strategies/dual_confidence_strategy.py b/src/local_deep_research/advanced_search_system/strategies/dual_confidence_strategy.py
deleted file mode 100644
index 50f4f2bb5b..0000000000
--- a/src/local_deep_research/advanced_search_system/strategies/dual_confidence_strategy.py
+++ /dev/null
@@ -1,321 +0,0 @@
-"""
-Enhanced strategy with dual confidence scoring (positive/negative) for better accuracy.
-"""
-
-import re
-from dataclasses import dataclass
-from typing import Dict, List
-
-from loguru import logger
-
-from ..candidates.base_candidate import Candidate
-from ..constraints.base_constraint import Constraint
-from .smart_query_strategy import SmartQueryStrategy
-
-
-@dataclass
-class ConstraintEvidence:
- """Evidence for a constraint with dual confidence scores."""
-
- positive_confidence: float # How sure we are the constraint IS satisfied
- negative_confidence: (
- float # How sure we are the constraint is NOT satisfied
- )
- uncertainty: float # How uncertain we are (neither positive nor negative)
- evidence_text: str
- source: str
-
-
-class DualConfidenceStrategy(SmartQueryStrategy):
- """
- Enhanced strategy that uses dual confidence scoring:
- - Positive confidence: Evidence that constraint IS satisfied
- - Negative confidence: Evidence that constraint is NOT satisfied
- - Uncertainty: Lack of clear evidence either way
-
- This allows for more accurate scoring and better early stopping decisions.
- """
-
- def __init__(
- self,
- *args,
- uncertainty_penalty: float = 0.2,
- negative_weight: float = 0.5,
- **kwargs,
- ):
- super().__init__(*args, **kwargs)
- self.uncertainty_penalty = uncertainty_penalty
- self.negative_weight = negative_weight
-
- def _evaluate_evidence(
- self, evidence_list: List[Dict], constraint: Constraint
- ) -> float:
- """Enhanced evidence evaluation with dual confidence."""
- if not evidence_list:
- # No evidence means high uncertainty
- return 0.5 - self.uncertainty_penalty
-
- # Convert evidence to dual confidence format
- constraint_evidence = []
- for evidence in evidence_list:
- dual_evidence = self._analyze_evidence_dual_confidence(
- evidence, constraint
- )
- constraint_evidence.append(dual_evidence)
-
- # Calculate overall score
- total_positive = sum(e.positive_confidence for e in constraint_evidence)
- total_negative = sum(e.negative_confidence for e in constraint_evidence)
- total_uncertainty = sum(e.uncertainty for e in constraint_evidence)
-
- # Normalize
- evidence_count = len(constraint_evidence)
- avg_positive = total_positive / evidence_count
- avg_negative = total_negative / evidence_count
- avg_uncertainty = total_uncertainty / evidence_count
-
- # Calculate final score
- # High positive + low negative = high score
- # Low positive + high negative = low score
- # High uncertainty = penalty
- score = (
- avg_positive
- - (avg_negative * self.negative_weight)
- - (avg_uncertainty * self.uncertainty_penalty)
- )
-
- # Clamp to [0, 1]
- return max(0.0, min(1.0, score))
-
- def _analyze_evidence_dual_confidence(
- self, evidence: Dict, constraint: Constraint
- ) -> ConstraintEvidence:
- """Analyze evidence to extract dual confidence scores."""
- text = evidence.get("text", "")
-
- # Use LLM to analyze evidence with dual confidence
- prompt = f"""
-Analyze this evidence for the constraint "{constraint.value}" (type: {constraint.type.value}).
-
-Evidence:
-{text[:1000]}
-
-Provide three confidence scores (0-1):
-1. POSITIVE_CONFIDENCE: How confident are you that this constraint IS satisfied?
-2. NEGATIVE_CONFIDENCE: How confident are you that this constraint is NOT satisfied?
-3. UNCERTAINTY: How uncertain are you (lack of clear evidence)?
-
-The three scores should approximately sum to 1.0.
-
-Format:
-POSITIVE: [score]
-NEGATIVE: [score]
-UNCERTAINTY: [score]
-"""
-
- try:
- response = self.model.invoke(prompt).content
-
- # Extract scores
- positive = self._extract_score(response, "POSITIVE")
- negative = self._extract_score(response, "NEGATIVE")
- uncertainty = self._extract_score(response, "UNCERTAINTY")
-
- # Normalize if needed
- total = positive + negative + uncertainty
- if total > 0:
- positive /= total
- negative /= total
- uncertainty /= total
- else:
- # Default to high uncertainty
- uncertainty = 0.8
- positive = 0.1
- negative = 0.1
-
- return ConstraintEvidence(
- positive_confidence=positive,
- negative_confidence=negative,
- uncertainty=uncertainty,
- evidence_text=text[:500],
- source=evidence.get("source", "search"),
- )
-
- except Exception:
- logger.exception("Error analyzing evidence")
- # Default to high uncertainty
- return ConstraintEvidence(
- positive_confidence=0.1,
- negative_confidence=0.1,
- uncertainty=0.8,
- evidence_text=text[:500],
- source=evidence.get("source", "search"),
- )
-
- def _extract_score(self, text: str, label: str) -> float:
- """Extract confidence score from LLM response."""
- pattern = rf"{label}:\s*\[?(\d*\.?\d+)\]?"
- match = re.search(pattern, text, re.IGNORECASE)
- if match:
- try:
- return float(match.group(1))
- except (ValueError, TypeError):
- pass
- return 0.1 # Default low score
-
- def _gather_evidence_for_constraint(
- self, candidate: Candidate, constraint: Constraint
- ) -> List[Dict]:
- """Enhanced evidence gathering with targeted searches."""
- evidence = []
-
- # Build specific queries for this constraint
- queries = [
- f'"{candidate.name}" {constraint.value} verification',
- f'"{candidate.name}" {constraint.value} true or false',
- f"Is {candidate.name} {constraint.value}?",
- ]
-
- # For negative evidence, also search for contradictions
- if constraint.type.value == "property":
- queries.append(f'"{candidate.name}" NOT {constraint.value}')
- queries.append(f'"{candidate.name}" opposite of {constraint.value}')
-
- # Execute searches
- for query in queries[:3]: # Limit searches
- if query.lower() not in self.searched_queries:
- self.searched_queries.add(query.lower())
- try:
- results = self._execute_search(query)
- content = results.get("current_knowledge", "")
-
- if content:
- evidence.append(
- {
- "text": content,
- "source": f"search: {query}",
- "query": query,
- }
- )
- except Exception:
- logger.exception(f"Error gathering evidence for {query}")
-
- return evidence
-
- def _evaluate_candidate_immediately(self, candidate: Candidate) -> float:
- """Enhanced evaluation with detailed constraint scoring."""
- try:
- logger.info(
- f"Evaluating candidate: {candidate.name} with dual confidence"
- )
-
- total_score = 0.0
- constraint_scores = []
- detailed_results = []
-
- for i, constraint in enumerate(self.constraint_ranking):
- # Gather evidence
- evidence = self._gather_evidence_for_constraint(
- candidate, constraint
- )
-
- # Evaluate with dual confidence
- score = self._evaluate_evidence(evidence, constraint)
- constraint_scores.append(score)
-
- # Store detailed results
- if evidence:
- dual_evidence = [
- self._analyze_evidence_dual_confidence(e, constraint)
- for e in evidence
- ]
- avg_positive = sum(
- e.positive_confidence for e in dual_evidence
- ) / len(dual_evidence)
- avg_negative = sum(
- e.negative_confidence for e in dual_evidence
- ) / len(dual_evidence)
- avg_uncertainty = sum(
- e.uncertainty for e in dual_evidence
- ) / len(dual_evidence)
-
- detailed_results.append(
- {
- "constraint": constraint.value,
- "score": score,
- "positive": avg_positive,
- "negative": avg_negative,
- "uncertainty": avg_uncertainty,
- }
- )
-
- symbol = (
- "✓" if score >= 0.8 else "○" if score >= 0.5 else "✗"
- )
- logger.info(
- f"{symbol} {candidate.name} | {constraint.value}: {int(score * 100)}% "
- f"(+{int(avg_positive * 100)}% -{int(avg_negative * 100)}% ?{int(avg_uncertainty * 100)}%)"
- )
-
- # Early exit for critical failures with high negative confidence
- if score < 0.2 and constraint.weight > 0.8:
- logger.info(
- f"Critical constraint failed with high confidence: {constraint.value}"
- )
- break
-
- # Calculate weighted average
- if constraint_scores:
- weights = [
- c.weight
- for c in self.constraint_ranking[: len(constraint_scores)]
- ]
- total_score = sum(
- s * w
- for s, w in zip(constraint_scores, weights, strict=False)
- ) / sum(weights)
-
- # Log detailed breakdown
- logger.info(f"\nDetailed analysis for {candidate.name}:")
- for result in detailed_results:
- logger.info(
- f" {result['constraint']}: {result['score']:.2%} "
- f"(+{result['positive']:.0%} -{result['negative']:.0%} ?{result['uncertainty']:.0%})"
- )
-
- # Update best candidate if needed
- with self.evaluation_lock:
- self.evaluated_candidates[candidate.name] = total_score
-
- if total_score > self.best_score:
- self.best_score = total_score
- self.best_candidate = candidate.name
-
- logger.info(
- f"New best: {candidate.name} with {total_score:.2%}"
- )
-
- # Check for early stop
- if total_score >= self.early_stop_threshold:
- logger.info(
- f"EARLY STOP: {candidate.name} reached {total_score:.2%}!"
- )
- self.found_answer.set()
-
- if self.progress_callback:
- self.progress_callback(
- f"Found answer: {candidate.name} ({int(total_score * 100)}% confidence)",
- 95,
- {
- "phase": "early_stop",
- "final_answer": candidate.name,
- "confidence": total_score,
- "detailed_results": detailed_results,
- },
- )
-
- return total_score
-
- except Exception:
- logger.exception(f"Error evaluating candidate: {candidate.name}")
- return 0.0
diff --git a/src/local_deep_research/advanced_search_system/strategies/dual_confidence_with_rejection.py b/src/local_deep_research/advanced_search_system/strategies/dual_confidence_with_rejection.py
deleted file mode 100644
index a388e6aee0..0000000000
--- a/src/local_deep_research/advanced_search_system/strategies/dual_confidence_with_rejection.py
+++ /dev/null
@@ -1,220 +0,0 @@
-"""
-Enhanced dual confidence strategy with early rejection of candidates.
-"""
-
-from loguru import logger
-
-from ..constraint_checking import DualConfidenceChecker
-from .dual_confidence_strategy import DualConfidenceStrategy
-
-
-class DualConfidenceWithRejectionStrategy(DualConfidenceStrategy):
- """
- Enhanced dual confidence strategy that rejects candidates early when they have
- high negative evidence for any constraint.
- """
-
- def __init__(
- self,
- *args,
- rejection_threshold: float = 0.3, # If negative > 30% and positive < threshold
- positive_threshold: float = 0.2, # Minimum positive needed to overcome negative
- critical_constraint_rejection: float = 0.2, # Even stricter for critical constraints
- **kwargs,
- ):
- super().__init__(*args, **kwargs)
- self.rejection_threshold = rejection_threshold
- self.positive_threshold = positive_threshold
- self.critical_constraint_rejection = critical_constraint_rejection
-
- # Initialize constraint checker (using new inheritance-based system)
- self.constraint_checker = DualConfidenceChecker(
- model=self.model,
- evidence_gatherer=self._gather_evidence_for_constraint,
- negative_threshold=0.25, # 25% negative evidence threshold
- positive_threshold=0.4, # 40% minimum positive evidence
- uncertainty_penalty=self.uncertainty_penalty,
- negative_weight=self.negative_weight,
- )
-
- def _evaluate_candidate_immediately(self, candidate) -> float:
- """Enhanced evaluation with early rejection based on negative evidence."""
- try:
- logger.info(
- f"Evaluating candidate: {candidate.name} with early rejection"
- )
-
- total_score = 0.0
- constraint_scores = []
- detailed_results = []
-
- for i, constraint in enumerate(self.constraint_ranking):
- # Gather evidence for this constraint
- evidence = self._gather_evidence_for_constraint(
- candidate, constraint
- )
-
- if evidence:
- # Analyze evidence with dual confidence
- dual_evidence = [
- self._analyze_evidence_dual_confidence(e, constraint)
- for e in evidence
- ]
-
- # Calculate average scores
- avg_positive = sum(
- e.positive_confidence for e in dual_evidence
- ) / len(dual_evidence)
- avg_negative = sum(
- e.negative_confidence for e in dual_evidence
- ) / len(dual_evidence)
- avg_uncertainty = sum(
- e.uncertainty for e in dual_evidence
- ) / len(dual_evidence)
-
- # EARLY REJECTION LOGIC
- # Reject if negative evidence is above 25% - simplified approach
- if avg_negative > 0.25:
- logger.info(
- f"❌ EARLY REJECTION: {candidate.name} - Constraint '{constraint.value}' "
- f"has significant negative evidence ({avg_negative:.0%})"
- )
- return 0.0 # Immediate rejection
-
- # If high negative but also decent positive, continue but penalize
- if (
- avg_negative > self.rejection_threshold
- and avg_positive > self.positive_threshold
- ):
- logger.warning(
- f"⚠️ Mixed evidence for {candidate.name} - {constraint.value}: "
- f"+{avg_positive:.0%} -{avg_negative:.0%}"
- )
-
- # Calculate score using parent method
- score = self._evaluate_evidence(evidence, constraint)
- constraint_scores.append(score)
-
- detailed_results.append(
- {
- "constraint": constraint.value,
- "score": score,
- "positive": avg_positive,
- "negative": avg_negative,
- "uncertainty": avg_uncertainty,
- "weight": constraint.weight,
- }
- )
-
- # Visual feedback
- symbol = (
- "✓" if score >= 0.8 else "○" if score >= 0.5 else "✗"
- )
- logger.info(
- f"{symbol} {candidate.name} | {constraint.value}: {int(score * 100)}% "
- f"(+{int(avg_positive * 100)}% -{int(avg_negative * 100)}% ?{int(avg_uncertainty * 100)}%)"
- )
-
- # Skip remaining constraints if this one failed badly
- if score < 0.2 and constraint.weight > 0.5:
- logger.info(
- "⚠️ Skipping remaining constraints due to poor score on important constraint"
- )
- break
- else:
- # No evidence - high uncertainty
- score = 0.5 - self.uncertainty_penalty
- constraint_scores.append(score)
- logger.info(
- f"? {candidate.name} | {constraint.value}: No evidence found"
- )
-
- # Calculate weighted average
- if constraint_scores:
- weights = [
- c.weight
- for c in self.constraint_ranking[: len(constraint_scores)]
- ]
- total_score = sum(
- s * w
- for s, w in zip(constraint_scores, weights, strict=False)
- ) / sum(weights)
-
- # Log detailed breakdown
- logger.info(f"\nDetailed analysis for {candidate.name}:")
- for result in detailed_results:
- logger.info(
- f" {result['constraint']}: {result['score']:.2%} "
- f"(+{result['positive']:.0%} -{result['negative']:.0%} ?{result['uncertainty']:.0%}) "
- f"[weight: {result['weight']:.1f}]"
- )
-
- logger.info(f"Final score for {candidate.name}: {total_score:.2%}")
-
- # Store constraint evaluation results on the candidate object
- candidate.evaluation_results = detailed_results
- candidate.score = total_score
-
- # Update tracking
- with self.evaluation_lock:
- self.evaluated_candidates[candidate.name] = total_score
-
- if total_score > self.best_score:
- self.best_score = total_score
- self.best_candidate = candidate
- logger.info(
- f"New best: {candidate.name} with {total_score:.2%}"
- )
-
- # Check for early stop
- if total_score >= self.early_stop_threshold:
- logger.info(
- f"🎯 EARLY STOP: {candidate.name} reached {total_score:.2%}!"
- )
- self.found_answer.set()
-
- return total_score
-
- except Exception:
- logger.exception(f"Error evaluating {candidate.name}")
- return 0.0
-
- def _evaluate_candidate_with_constraint_checker(self, candidate) -> float:
- """
- Evaluate candidate using the new modular constraint checking system.
-
- This method can be used as an alternative to the existing evaluation logic.
- """
- try:
- # Use the constraint checker
- result = self.constraint_checker.check_candidate(
- candidate, self.constraint_ranking
- )
-
- # Store results on candidate
- candidate.evaluation_results = result.detailed_results
- candidate.score = result.total_score
-
- # Update tracking
- with self.evaluation_lock:
- self.evaluated_candidates[candidate.name] = result.total_score
-
- if result.total_score > self.best_score:
- self.best_score = result.total_score
- self.best_candidate = candidate
- logger.info(
- f"New best: {candidate.name} with {result.total_score:.2%}"
- )
-
- # Check for early stop
- if result.total_score >= self.early_stop_threshold:
- logger.info(
- f"🎯 EARLY STOP: {candidate.name} reached {result.total_score:.2%}!"
- )
- self.found_answer.set()
-
- return result.total_score
-
- except Exception:
- logger.exception(f"Error evaluating {candidate.name}")
- return 0.0
diff --git a/src/local_deep_research/advanced_search_system/strategies/early_stop_constrained_strategy.py b/src/local_deep_research/advanced_search_system/strategies/early_stop_constrained_strategy.py
deleted file mode 100644
index f5f38719c5..0000000000
--- a/src/local_deep_research/advanced_search_system/strategies/early_stop_constrained_strategy.py
+++ /dev/null
@@ -1,371 +0,0 @@
-"""
-Early-stop constrained search strategy that evaluates candidates immediately
-and stops when finding a very high confidence match.
-"""
-
-import concurrent.futures
-import threading
-from typing import Dict, List
-
-from loguru import logger
-
-from ...database.thread_local_session import thread_cleanup
-from ..candidates.base_candidate import Candidate
-from ..constraints.base_constraint import Constraint
-from .parallel_constrained_strategy import ParallelConstrainedStrategy
-
-
-class EarlyStopConstrainedStrategy(ParallelConstrainedStrategy):
- """
- Enhanced constrained strategy that:
- 1. Evaluates candidates as soon as they're found
- 2. Stops early when finding a very high confidence match (99%+)
- 3. Runs evaluation and search concurrently
- """
-
- def __init__(
- self,
- *args,
- early_stop_threshold: float = 0.99,
- concurrent_evaluation: bool = True,
- **kwargs,
- ):
- super().__init__(*args, **kwargs)
- self.early_stop_threshold = early_stop_threshold
- self.concurrent_evaluation = concurrent_evaluation
-
- # Thread-safe tracking
- self.found_answer = threading.Event()
- self.best_candidate = None
- self.best_score = 0.0
- self.evaluation_lock = threading.Lock()
-
- # Track candidates being evaluated
- self.evaluating_candidates = set()
- self.evaluated_candidates = {}
-
- def _parallel_search(self, combinations: List) -> List[Candidate]:
- """Execute searches in parallel with immediate candidate evaluation."""
- all_candidates = []
- evaluation_futures = []
-
- with concurrent.futures.ThreadPoolExecutor(
- max_workers=self.parallel_workers
- ) as executor:
- # Submit all searches
- search_futures = {
- executor.submit(self._execute_combination_search, combo): combo
- for combo in combinations
- }
-
- # Process results as they complete
- for future in concurrent.futures.as_completed(search_futures):
- # Check if we should stop early
- if self.found_answer.is_set():
- logger.info(
- f"Early stop triggered - found answer: {self.best_candidate}"
- )
- break
-
- combo = search_futures[future]
- try:
- candidates = future.result()
- all_candidates.extend(candidates)
-
- # Start evaluating candidates immediately if concurrent evaluation is enabled
- if self.concurrent_evaluation:
- for candidate in candidates:
- if candidate.name not in self.evaluating_candidates:
- self.evaluating_candidates.add(candidate.name)
- eval_future = executor.submit(
- thread_cleanup(
- self._evaluate_candidate_immediately
- ),
- candidate,
- )
- evaluation_futures.append(eval_future)
-
- if self.progress_callback:
- self.progress_callback(
- f"Found {len(candidates)} candidates, evaluating...",
- None,
- {
- "phase": "parallel_search_with_eval",
- "candidates": len(all_candidates),
- "best_score": self.best_score,
- "best_candidate": self.best_candidate,
- },
- )
-
- except Exception:
- logger.exception(f"Search failed for {combo.query}")
-
- # Wait for evaluation futures to complete
- for future in concurrent.futures.as_completed(evaluation_futures):
- try:
- future.result()
- except Exception:
- logger.exception("Evaluation failed")
-
- return all_candidates
-
- def _evaluate_candidate_immediately(self, candidate: Candidate) -> float:
- """Evaluate a candidate against all constraints immediately."""
- try:
- logger.info(f"Immediately evaluating candidate: {candidate.name}")
-
- # Calculate overall score across all constraints
- total_score = 0.0
- constraint_scores = []
-
- for constraint in self.constraint_ranking:
- # Get evidence for this constraint
- evidence = self._gather_evidence_for_constraint(
- candidate, constraint
- )
- score = self._evaluate_evidence(evidence, constraint)
- constraint_scores.append(score)
-
- # Update progress
- if self.progress_callback:
- symbol = "✓" if score >= 0.8 else "○"
- self.progress_callback(
- f"{symbol} {candidate.name} | {constraint.type.value}: {int(score * 100)}%",
- None,
- {
- "phase": "immediate_evaluation",
- "candidate": candidate.name,
- "constraint": constraint.value,
- "score": score,
- },
- )
-
- # If this candidate fails a critical constraint badly, skip remaining checks
- if score < 0.3 and constraint.weight > 0.8:
- logger.info(
- f"Candidate {candidate.name} failed critical constraint early"
- )
- break
-
- # Calculate average score
- if constraint_scores:
- total_score = sum(constraint_scores) / len(constraint_scores)
-
- # Thread-safe update of best candidate
- with self.evaluation_lock:
- self.evaluated_candidates[candidate.name] = total_score
-
- if total_score > self.best_score:
- self.best_score = total_score
- self.best_candidate = candidate.name
-
- logger.info(
- f"New best candidate: {candidate.name} with score {total_score:.2f}"
- )
-
- # Check for early stop
- if total_score >= self.early_stop_threshold:
- logger.info(
- f"EARLY STOP: Found {candidate.name} with {total_score:.2f} confidence!"
- )
- self.found_answer.set()
-
- if self.progress_callback:
- self.progress_callback(
- f"Found answer: {candidate.name} ({int(total_score * 100)}% confidence)",
- 95,
- {
- "phase": "early_stop",
- "final_answer": candidate.name,
- "confidence": total_score,
- },
- )
-
- return total_score
-
- except Exception:
- logger.exception(f"Error evaluating candidate {candidate.name}")
- return 0.0
-
- def _progressive_constraint_search(self):
- """Override to implement early stopping."""
- current_candidates = []
- search_iterations = 0
- max_search_iterations = 3
-
- # Detect entity type
- self.entity_type = self._detect_entity_type()
- logger.info(f"Detected entity type: {self.entity_type}")
-
- while (
- search_iterations < max_search_iterations
- and not self.found_answer.is_set()
- ):
- search_iterations += 1
-
- # Create search combinations based on iteration
- if search_iterations == 1:
- combinations = self._create_strict_combinations()
- strictness = "strict"
- elif search_iterations == 2:
- combinations = self._create_relaxed_combinations()
- strictness = "relaxed"
- else:
- combinations = self._create_individual_combinations()
- strictness = "individual"
-
- logger.info(
- f"Iteration {search_iterations}: {strictness} mode with {len(combinations)} combinations"
- )
-
- # Run searches in parallel with immediate evaluation
- new_candidates = self._parallel_search(combinations)
- current_candidates.extend(new_candidates)
-
- # Check if we have enough results or found the answer
- unique_candidates = self._deduplicate_candidates(current_candidates)
-
- if self.found_answer.is_set():
- logger.info(f"Early stop - found answer: {self.best_candidate}")
- break
-
- if len(unique_candidates) >= self.min_results_threshold:
- logger.info(
- f"Found {len(unique_candidates)} candidates - checking if we need more"
- )
- # Continue only if best score is below threshold
- if self.best_score >= 0.9:
- logger.info(
- f"Best score {self.best_score:.2f} is high enough - stopping search"
- )
- break
-
- # Set final candidates
- self.candidates = [
- c for c in unique_candidates if c.name == self.best_candidate
- ]
- if not self.candidates and unique_candidates:
- # If best candidate wasn't in the list somehow, use top scored candidates
- scored_candidates = sorted(
- unique_candidates,
- key=lambda c: self.evaluated_candidates.get(c.name, 0),
- reverse=True,
- )
- self.candidates = scored_candidates[: self.candidate_limit]
-
- self.final_answer = self.best_candidate
- self.confidence = self.best_score
-
- def analyze_topic(self, topic: str) -> Dict:
- """Analyze topic with early stopping."""
- # Call parent's analyze_topic to handle constraint extraction
- result = super().analyze_topic(topic)
-
- # Add our early stopping information
- result["early_stopped"] = self.found_answer.is_set()
- result["evaluated_candidates"] = self.evaluated_candidates
- result["best_candidate"] = self.best_candidate
- result["best_score"] = self.best_score
-
- return result
-
- def _gather_evidence_for_constraint(
- self, candidate: Candidate, constraint: Constraint
- ) -> List:
- """Gather evidence for a specific candidate-constraint pair."""
- # Run targeted search for this specific combination
- query = f'"{candidate.name}" {constraint.value} verification'
-
- try:
- results = self._execute_search(query)
- return self._extract_evidence_from_results(
- results, candidate, constraint
- )
- except Exception:
- logger.exception(f"Error gathering evidence for {candidate.name}")
- return []
-
- def _extract_evidence_from_results(
- self, results: Dict, candidate: Candidate, constraint: Constraint
- ) -> List:
- """Extract relevant evidence from search results."""
- evidence = []
- content = results.get("current_knowledge", "")
-
- if content:
- # Use LLM to extract evidence
- prompt = f"""
- Extract evidence regarding whether "{candidate.name}" satisfies this constraint:
-
- Constraint: {constraint.value}
- Constraint Type: {constraint.type.value}
-
- Search Results:
- {content[:3000]}
-
- Extract specific evidence that either supports or refutes the constraint.
- Return a confidence score from 0 to 1.
- """
-
- try:
- response = self.model.invoke(prompt).content
- evidence.append(
- {
- "text": response,
- "source": "search_results",
- "confidence": self._extract_confidence_from_response(
- response
- ),
- }
- )
- except Exception:
- logger.exception("Error extracting evidence")
-
- return evidence
-
- def _extract_confidence_from_response(self, response: str) -> float:
- """Extract confidence score from LLM response."""
- # Simple extraction - look for number between 0 and 1
- import re
-
- pattern = r"\b0?\.\d+\b|\b1\.0\b|\b1\b"
- matches = re.findall(pattern, response)
-
- if matches:
- try:
- return float(matches[-1]) # Use last number found
- except ValueError:
- pass
-
- # Default confidence based on keywords
- if any(
- word in response.lower()
- for word in ["definitely", "certainly", "absolutely"]
- ):
- return 0.9
- if any(
- word in response.lower()
- for word in ["likely", "probably", "appears"]
- ):
- return 0.7
- if any(
- word in response.lower() for word in ["possibly", "maybe", "might"]
- ):
- return 0.5
- if any(
- word in response.lower() for word in ["unlikely", "doubtful", "not"]
- ):
- return 0.3
-
- return 0.5
-
- def _evaluate_evidence(
- self, evidence: List, constraint: Constraint
- ) -> float:
- """Evaluate evidence to determine constraint satisfaction score."""
- if not evidence:
- return 0.0
-
- # Average confidence across all evidence
- confidences = [e.get("confidence", 0.5) for e in evidence]
- return sum(confidences) / len(confidences) if confidences else 0.0
diff --git a/src/local_deep_research/advanced_search_system/strategies/evidence_based_strategy.py b/src/local_deep_research/advanced_search_system/strategies/evidence_based_strategy.py
deleted file mode 100644
index d634cddbca..0000000000
--- a/src/local_deep_research/advanced_search_system/strategies/evidence_based_strategy.py
+++ /dev/null
@@ -1,1248 +0,0 @@
-"""
-Evidence-based search strategy for complex query resolution.
-
-This strategy decomposes queries into constraints, finds candidates,
-and systematically gathers evidence to score each candidate.
-"""
-
-from datetime import datetime, UTC
-from typing import Any, Dict, List
-
-from langchain_core.language_models import BaseChatModel
-from loguru import logger
-
-from ...utilities.search_utilities import format_findings, remove_think_tags
-from ..candidates.base_candidate import Candidate
-from ..constraints.base_constraint import Constraint, ConstraintType
-from ..constraints.constraint_analyzer import ConstraintAnalyzer
-from ..evidence.evaluator import EvidenceEvaluator
-from ..findings.repository import FindingsRepository
-from .base_strategy import BaseSearchStrategy
-from .source_based_strategy import SourceBasedSearchStrategy
-
-
-class EvidenceBasedStrategy(BaseSearchStrategy):
- """
- Evidence-based strategy for solving complex queries.
-
- Key features:
- 1. Decomposes queries into verifiable constraints
- 2. Finds candidates that might satisfy constraints
- 3. Gathers specific evidence for each candidate-constraint pair
- 4. Scores candidates based on evidence quality
- 5. Progressively refines the search
- """
-
- def __init__(
- self,
- model: BaseChatModel,
- search: Any,
- all_links_of_system: List[str],
- max_iterations: int = 20,
- confidence_threshold: float = 0.85,
- candidate_limit: int = 10,
- evidence_threshold: float = 0.6,
- max_search_iterations: int = 2, # For source-based sub-searches
- questions_per_iteration: int = 3,
- settings_snapshot=None,
- ):
- """Initialize the evidence-based strategy."""
- super().__init__(all_links_of_system, settings_snapshot)
- self.model = model
- self.search = search
- self.max_iterations = max_iterations
- self.confidence_threshold = confidence_threshold
- self.candidate_limit = candidate_limit
- self.evidence_threshold = evidence_threshold
- self.max_search_iterations = max_search_iterations
- self.questions_per_iteration = questions_per_iteration
-
- # Enable direct search by default for performance
- self.use_direct_search = True
- logger.info(
- f"EvidenceBasedStrategy init: use_direct_search={self.use_direct_search}"
- )
-
- # Initialize components
- self.constraint_analyzer = ConstraintAnalyzer(model)
- self.evidence_evaluator = EvidenceEvaluator(model)
- self.findings_repository = FindingsRepository(model)
-
- # State tracking
- self.constraints: List[Constraint] = []
- self.candidates: List[Candidate] = []
- self.search_history: List[Dict] = []
- self.iteration: int = 0
-
- def analyze_topic(self, query: str) -> Dict:
- """Analyze a topic using evidence-based approach."""
- # Initialize
- self.all_links_of_system.clear()
- self.questions_by_iteration = []
- self.findings = []
- self.iteration = 0
-
- # Step 1: Extract constraints from query
- if self.progress_callback:
- self.progress_callback(
- "Analyzing query to extract constraints...",
- 2,
- {
- "phase": "constraint_analysis",
- "status": "starting",
- "query_length": len(query),
- },
- )
-
- self.constraints = self.constraint_analyzer.extract_constraints(query)
-
- if self.progress_callback:
- constraint_summary = {}
- for c in self.constraints:
- type_name = c.type.name
- if type_name not in constraint_summary:
- constraint_summary[type_name] = 0
- constraint_summary[type_name] += 1
-
- self.progress_callback(
- f"Extracted {len(self.constraints)} constraints ({len([c for c in self.constraints if c.weight >= 0.9])} critical)",
- 5,
- {
- "phase": "constraint_extraction",
- "constraints_count": len(self.constraints),
- "constraint_types": constraint_summary,
- "high_priority": len(
- [c for c in self.constraints if c.weight >= 0.9]
- ),
- },
- )
-
- # Add initial analysis finding
- initial_finding = {
- "phase": "Initial Analysis",
- "content": self._format_initial_analysis(query),
- "timestamp": self._get_timestamp(),
- }
- self.findings.append(initial_finding)
-
- # Step 2: Find initial candidates
- self._find_initial_candidates()
-
- # Step 3: Main evidence-gathering loop
- while (
- self.iteration < self.max_iterations
- and not self._has_sufficient_answer()
- ):
- self.iteration += 1
-
- if self.progress_callback:
- progress = 15 + int((self.iteration / self.max_iterations) * 70)
-
- # Calculate detailed metrics
- evidence_coverage = self._calculate_evidence_coverage()
- top_score = self.candidates[0].score if self.candidates else 0
-
- # Calculate constraint satisfaction
- satisfied_constraints = 0
- if self.candidates:
- top_candidate = self.candidates[0]
- satisfied_constraints = len(
- [
- c
- for c in self.constraints
- if c.id in top_candidate.evidence
- and top_candidate.evidence[c.id].confidence
- >= self.evidence_threshold
- ]
- )
-
- confidence_level = (
- "HIGH"
- if top_score >= self.confidence_threshold
- else "MEDIUM"
- if top_score >= 0.6
- else "LOW"
- )
- self.progress_callback(
- f"Iteration {self.iteration}/{self.max_iterations} - {self._get_iteration_status()} [{confidence_level}]",
- progress,
- {
- "phase": "iteration_start",
- "iteration": self.iteration,
- "max_iterations": self.max_iterations,
- "candidates_count": len(self.candidates),
- "evidence_coverage": f"{evidence_coverage:.0%}",
- "top_score": f"{top_score:.0%}",
- "status": self._get_iteration_status(),
- "constraints_satisfied": f"{satisfied_constraints}/{len(self.constraints)}",
- "search_count": len(self.search_history),
- "confidence_level": confidence_level,
- },
- )
-
- # Gather evidence for each candidate
- self._gather_evidence_round()
-
- # Score and prune candidates
- self._score_and_prune_candidates()
-
- # Add iteration finding
- iteration_finding = {
- "phase": f"Iteration {self.iteration}",
- "content": self._format_iteration_summary(),
- "timestamp": self._get_timestamp(),
- "metadata": {
- "candidates": len(self.candidates),
- "evidence_collected": sum(
- len(c.evidence) for c in self.candidates
- ),
- "top_score": self.candidates[0].score
- if self.candidates
- else 0,
- },
- }
- self.findings.append(iteration_finding)
-
- # Check if we need more candidates
- if len(self.candidates) < 3:
- if self.iteration <= 2:
- # Early iterations - try different search strategies
- self._find_initial_candidates()
- elif self.iteration < self.max_iterations / 2:
- # Mid iterations - look for additional candidates
- self._find_additional_candidates()
-
- # Step 4: Final verification of top candidates
- self._final_verification()
-
- # Step 5: Generate final answer
- final_result = self._synthesize_final_answer(query)
-
- if self.progress_callback:
- self.progress_callback(
- f"Analysis complete - evaluated {len(self.candidates)} candidates",
- 100,
- {
- "phase": "complete",
- "strategy": "evidence_based",
- "total_iterations": self.iteration,
- "final_candidates": len(self.candidates),
- },
- )
-
- return final_result
-
- def _find_initial_candidates(self):
- """Find initial candidates based on key constraints."""
- # Try multiple search strategies to find candidates
- all_candidates = []
-
- # Strategy 1: Use the most distinctive constraints
- distinctive_constraints = self._get_distinctive_constraints()
-
- if self.progress_callback:
- self.progress_callback(
- f"Prioritizing {len(distinctive_constraints)} key constraints from {len(self.constraints)} total",
- 7,
- {
- "phase": "constraint_prioritization",
- "total_constraints": len(self.constraints),
- "selected_constraints": len(distinctive_constraints),
- "key_constraint_types": [
- c.type.value for c in distinctive_constraints
- ],
- },
- )
-
- # Try first query with distinctive constraints
- search_query = self._create_candidate_search_query(
- distinctive_constraints
- )
-
- if self.progress_callback:
- self.progress_callback(
- f"Creating search query: {search_query[:50]}...",
- 8,
- {
- "phase": "query_generation",
- "search_query": (
- search_query[:100] + "..."
- if len(search_query) > 100
- else search_query
- ),
- "query_length": len(search_query),
- "constraint_count": len(distinctive_constraints),
- },
- )
-
- if self.progress_callback:
- self.progress_callback(
- f"Searching for candidates using {type(self.search).__name__ if self.search else 'Unknown'}",
- 9,
- {
- "phase": "candidate_search",
- "status": "searching",
- "search_engine": (
- type(self.search).__name__ if self.search else "Unknown"
- ),
- },
- )
-
- results = self._execute_search(search_query)
- candidates = self._extract_candidates_from_results(
- results, search_query
- )
- all_candidates.extend(candidates)
-
- # If no candidates found, try a different approach
- if not all_candidates:
- if self.progress_callback:
- self.progress_callback(
- "Primary search found 0 candidates - trying alternative search strategies",
- 10,
- {"phase": "alternative_search", "status": "searching"},
- )
-
- # Strategy 2: Focus on name pattern constraints if available
- pattern_constraints = [
- c
- for c in self.constraints
- if c.type == ConstraintType.NAME_PATTERN
- ]
- location_constraints = [
- c for c in self.constraints if c.type == ConstraintType.LOCATION
- ]
-
- if pattern_constraints or location_constraints:
- combined_constraints = (
- pattern_constraints + location_constraints
- )[:3]
- search_query = self._create_candidate_search_query(
- combined_constraints
- )
- results = self._execute_search(search_query)
- candidates = self._extract_candidates_from_results(
- results, search_query
- )
- all_candidates.extend(candidates)
-
- # Remove duplicates while preserving order
- seen = set()
- unique_candidates = []
- for c in all_candidates:
- if c.name.lower() not in seen:
- seen.add(c.name.lower())
- unique_candidates.append(c)
-
- self.candidates.extend(unique_candidates[: self.candidate_limit])
-
- if self.progress_callback:
- status_msg = (
- f"Found {len(self.candidates)} candidates"
- if self.candidates
- else "No candidates found - will retry in next iteration"
- )
- self.progress_callback(
- status_msg,
- 15,
- {
- "phase": "candidates_found",
- "count": len(self.candidates),
- "candidates": [
- {"name": c.name, "initial_score": 0}
- for c in self.candidates[:5]
- ],
- "status": (
- "ready_for_evidence_gathering"
- if self.candidates
- else "no_candidates_found"
- ),
- },
- )
-
- logger.info(f"Found {len(self.candidates)} initial candidates")
-
- def _gather_evidence_round(self):
- """Gather evidence for candidates in this round."""
- evidence_gathered = 0
- total_candidates = min(5, len(self.candidates))
-
- if self.progress_callback:
- evidence_msg = f"Gathering evidence for {total_candidates} candidates x {len(self.constraints)} constraints"
- if total_candidates == 0:
- evidence_msg = (
- "No candidates to process - skipping evidence gathering"
- )
- self.progress_callback(
- evidence_msg,
- None,
- {
- "phase": "evidence_round_start",
- "candidates_to_process": total_candidates,
- "iteration": self.iteration,
- "total_evidence_needed": total_candidates
- * len(self.constraints),
- },
- )
-
- for i, candidate in enumerate(
- self.candidates[:5]
- ): # Focus on top candidates
- unverified = candidate.get_unverified_constraints(self.constraints)
-
- if not unverified:
- if self.progress_callback:
- self.progress_callback(
- f"All constraints verified for {candidate.name}",
- None,
- {
- "phase": "candidate_complete",
- "candidate": candidate.name,
- "evidence_count": len(candidate.evidence),
- },
- )
- continue
-
- # Pick the most important unverified constraint
- constraint = max(unverified, key=lambda c: c.weight)
-
- if self.progress_callback:
- current_evidence = sum(
- len(c.evidence) for c in self.candidates[:total_candidates]
- )
- total_possible = total_candidates * len(self.constraints)
- evidence_percentage = (
- (current_evidence / total_possible * 100)
- if total_possible > 0
- else 0
- )
-
- self.progress_callback(
- f"Processing {candidate.name} [{i + 1}/{total_candidates}] - verifying {constraint.type.value}",
- None,
- {
- "phase": "evidence_search",
- "candidate": candidate.name,
- "constraint": constraint.description,
- "constraint_type": constraint.type.value,
- "constraint_weight": constraint.weight,
- "candidate_rank": i + 1,
- "evidence_progress": f"{evidence_percentage:.0f}%",
- "unverified_count": len(unverified),
- },
- )
-
- # Create a targeted search query for evidence
- evidence_query_prompt = f"""Create a search query to verify if "{candidate.name}" satisfies this constraint:
-Constraint: {constraint.description}
-Type: {constraint.type.value}
-
-Create a specific search query that would find evidence about whether this candidate meets this constraint.
-Return only the search query, no explanation."""
-
- query_response = self.model.invoke(evidence_query_prompt)
- search_query = remove_think_tags(query_response.content).strip()
-
- # Fallback to simple query if needed
- if not search_query or len(search_query) < 5:
- search_query = (
- f"{candidate.name} {constraint.to_search_terms()}"
- )
-
- results = self._execute_search(search_query)
-
- # Extract evidence
- evidence = self.evidence_evaluator.extract_evidence(
- results.get("current_knowledge", ""), candidate.name, constraint
- )
-
- candidate.add_evidence(constraint.id, evidence)
- evidence_gathered += 1
-
- if self.progress_callback:
- self.progress_callback(
- f"Evidence found: {evidence.confidence:.0%} confidence",
- None,
- {
- "phase": "evidence_found",
- "candidate": candidate.name,
- "constraint": constraint.description,
- "confidence": evidence.confidence,
- "evidence_type": evidence.type.value,
- "evidence_claim": (
- evidence.claim[:100] + "..."
- if len(evidence.claim) > 100
- else evidence.claim
- ),
- "constraint_satisfied": evidence.confidence
- >= self.evidence_threshold,
- },
- )
-
- logger.info(
- f"Added evidence for {candidate.name} - {constraint.id}: "
- f"{evidence.confidence:.2f} confidence"
- )
-
- if self.progress_callback and evidence_gathered > 0:
- self.progress_callback(
- f"Gathered {evidence_gathered} pieces of evidence",
- None,
- {
- "phase": "evidence_round_complete",
- "evidence_count": evidence_gathered,
- },
- )
-
- def _score_and_prune_candidates(self):
- """Score candidates and remove low-scoring ones."""
- if self.progress_callback:
- self.progress_callback(
- "Scoring candidates based on evidence",
- None,
- {
- "phase": "scoring_start",
- "candidate_count": len(self.candidates),
- },
- )
-
- for i, candidate in enumerate(self.candidates):
- old_score = candidate.score
- candidate.calculate_score(self.constraints)
-
- if self.progress_callback and i < 5: # Report top 5
- self.progress_callback(
- f"Scored {candidate.name}",
- None,
- {
- "phase": "candidate_scored",
- "candidate": candidate.name,
- "old_score": old_score,
- "new_score": candidate.score,
- "evidence_count": len(candidate.evidence),
- "satisfied_constraints": len(
- [
- c
- for c in self.constraints
- if c.id in candidate.evidence
- ]
- ),
- "score_change": candidate.score - old_score,
- },
- )
-
- # Sort by score
- self.candidates.sort(key=lambda c: c.score, reverse=True)
-
- # Prune low-scoring candidates
- old_count = len(self.candidates)
- min_score = (
- max(0.2, self.candidates[0].score * 0.3) if self.candidates else 0.2
- )
- self.candidates = [c for c in self.candidates if c.score >= min_score]
-
- # Keep only top candidates
- self.candidates = self.candidates[: self.candidate_limit]
-
- if self.progress_callback:
- removed = old_count - len(self.candidates)
- self.progress_callback(
- f"Pruned {removed} low-scoring candidates - keeping top {len(self.candidates)}",
- None,
- {
- "phase": "pruning_complete",
- "candidates_removed": removed,
- "min_score_threshold": min_score,
- "top_score": self.candidates[0].score
- if self.candidates
- else 0,
- "remaining_candidates": [
- {"name": c.name, "score": c.score, "rank": i + 1}
- for i, c in enumerate(self.candidates[:5])
- ],
- },
- )
-
- def _has_sufficient_answer(self) -> bool:
- """Check if we have a sufficiently confident answer."""
- if not self.candidates:
- return False
-
- top_candidate = self.candidates[0]
-
- # Check if top candidate has high score
- if top_candidate.score >= self.confidence_threshold:
- # Verify it has evidence for all critical constraints
- critical_constraints = [
- c for c in self.constraints if c.weight >= 0.8
- ]
- critical_evidence = [
- c.id
- for c in critical_constraints
- if c.id in top_candidate.evidence
- and top_candidate.evidence[c.id].confidence
- >= self.evidence_threshold
- ]
-
- if len(critical_evidence) == len(critical_constraints):
- return True
-
- return False
-
- def _final_verification(self):
- """Perform final verification on top candidates."""
- if not self.candidates:
- return
-
- if self.progress_callback:
- self.progress_callback(
- "Starting final verification of top candidates",
- 85,
- {
- "phase": "final_verification_start",
- "top_candidates": [c.name for c in self.candidates[:3]],
- },
- )
-
- # Get top 3 candidates
- top_candidates = self.candidates[:3]
-
- for candidate in top_candidates:
- # Find weak evidence or missing critical constraints
- weak_evidence = candidate.get_weak_evidence(self.evidence_threshold)
- critical_missing = [
- c
- for c in self.constraints
- if c.weight >= 0.8 and c.id not in candidate.evidence
- ]
-
- # Search for better evidence
- for constraint_id in weak_evidence[:2] + [
- c.id for c in critical_missing[:2]
- ]:
- constraint = next(
- (c for c in self.constraints if c.id == constraint_id), None
- )
- if constraint:
- search_query = f"{candidate.name} {constraint.value} exact verification"
- results = self._execute_search(search_query)
-
- evidence = self.evidence_evaluator.extract_evidence(
- results.get("current_knowledge", ""),
- candidate.name,
- constraint,
- )
-
- # Update if better evidence
- if (
- constraint_id not in candidate.evidence
- or evidence.confidence
- > candidate.evidence[constraint_id].confidence
- ):
- candidate.add_evidence(constraint.id, evidence)
-
- # Final scoring
- self._score_and_prune_candidates()
-
- def _execute_search(self, search_query: str) -> Dict:
- """Execute a search - optimized for direct queries."""
- self.search_history.append(
- {
- "query": search_query,
- "timestamp": self._get_timestamp(),
- "iteration": self.iteration,
- }
- )
-
- # For candidate searches and verification queries, use direct search
- # This avoids the overhead of full source-based strategy
- logger.info(
- f"_execute_search called with use_direct_search={self.use_direct_search} for query: {search_query[:50]}..."
- )
- if self.use_direct_search: # Always use direct search when flag is True
- # Direct search without question generation or iterations
- search_results = self.search.run(search_query)
-
- # Simple synthesis for knowledge extraction
- if search_results:
- content = "\n\n".join(
- [
- f"Result {i + 1}:\n{result.get('snippet', '')}"
- for i, result in enumerate(search_results[:10])
- ]
- )
- else:
- content = "No results found."
-
- return {
- "current_knowledge": content,
- "findings": [],
- "iterations": 1,
- "questions_by_iteration": [[search_query]],
- "all_links_of_system": search_results or [],
- }
-
- # Use source-based strategy for complex searches if needed
- source_strategy = SourceBasedSearchStrategy(
- model=self.model,
- search=self.search, # Pass the existing search instance
- all_links_of_system=self.all_links_of_system,
- include_text_content=True,
- use_cross_engine_filter=True,
- use_atomic_facts=True,
- )
-
- source_strategy.max_iterations = self.max_search_iterations
- source_strategy.questions_per_iteration = self.questions_per_iteration
-
- if self.progress_callback:
-
- def wrapped_callback(message, progress, data):
- # Add parent context
- data["parent_iteration"] = self.iteration
- data["parent_strategy"] = "evidence_based"
- data["search_query"] = search_query[:100]
-
- # Don't override parent progress percentage
- parent_progress = None
-
- # Make messages very short for frontend visibility, but keep query visible
- clean_message = message
- if "Generating questions" in message:
- clean_message = f"Q: {search_query[:500]}"
- elif "Searching" in message:
- clean_message = f"S: {search_query[:500]}"
- elif "Processing" in message:
- clean_message = f"P: {search_query[:500]}"
- elif "Completed search" in message:
- # Extract the actual search query from the message
- parts = message.split(":", 2)
- if len(parts) > 2:
- query_part = parts[2].strip()
- clean_message = f"✓ {query_part}" # Show full query
- else:
- clean_message = f"✓ {search_query[:500]}"
- elif "iteration" in message.lower():
- clean_message = (
- f"I{data.get('iteration', '?')}: {search_query[:500]}"
- )
- elif "Filtered" in message:
- results = data.get("result_count", "?")
- filtered = (
- len(data.get("links_count", []))
- if "links_count" in data
- else "?"
- )
- clean_message = f"Filter: {results}→{filtered}"
-
- self.progress_callback(
- clean_message,
- parent_progress, # Let parent manage overall progress
- data,
- )
-
- source_strategy.set_progress_callback(wrapped_callback)
-
- results = source_strategy.analyze_topic(search_query)
-
- if "questions_by_iteration" in results:
- self.questions_by_iteration.extend(
- results["questions_by_iteration"]
- )
-
- return results
-
- def _create_candidate_search_query(
- self, constraints: List[Constraint]
- ) -> str:
- """Create a search query to find candidates."""
- # Use an LLM to create effective search queries from constraints
- constraint_descriptions = []
- for c in constraints[:5]: # Limit to top 5 constraints
- constraint_descriptions.append(
- f"- {c.type.value}: {c.value} (weight: {c.weight})"
- )
-
- prompt = f"""Given these constraints for finding a specific answer, create an effective search query.
-
-Constraints:
-{chr(10).join(constraint_descriptions)}
-
-Your task is to create a search query that finds SPECIFIC NAMED ENTITIES that satisfy these constraints.
-
-Key principle: Focus on finding actual names of things, not general information.
-
-Guidelines:
-1. If the constraints describe properties, search for entities that have those properties
-2. If the constraints describe patterns, search for entities whose names match those patterns
-3. Combine the most distinctive constraints to narrow the search
-4. Use query operators (AND, OR, quotes) effectively
-
-Important: The query should be designed to surface specific names/entities in the search results, not explanations or general information about the constraints.
-
-Return only the search query, no explanation."""
-
- response = self.model.invoke(prompt)
- search_query = remove_think_tags(str(response.content)).strip()
-
- # Fallback if the query is too generic
- if len(search_query.split()) < 3:
- # Combine the most important constraint values
- key_terms = []
- for c in sorted(constraints, key=lambda x: x.weight, reverse=True)[
- :3
- ]:
- key_terms.append(f'"{c.value}"')
- search_query = " AND ".join(key_terms)
-
- return search_query
-
- def _get_distinctive_constraints(self) -> List[Constraint]:
- """Get the most distinctive constraints for initial search."""
- # Prioritize constraints that are most likely to identify specific entities
- priority_order = [
- ConstraintType.NAME_PATTERN,
- ConstraintType.LOCATION,
- ConstraintType.EVENT,
- ConstraintType.STATISTIC,
- ConstraintType.COMPARISON,
- ConstraintType.PROPERTY,
- ConstraintType.TEMPORAL,
- ConstraintType.EXISTENCE,
- ]
-
- # Sort constraints by priority and weight
- sorted_constraints = sorted(
- self.constraints,
- key=lambda c: (priority_order.index(c.type), -c.weight),
- )
-
- # Take top 3 constraints, ensuring we have at least one name/location constraint if available
- distinctive = sorted_constraints[:3]
-
- # Ensure we have at least one naming constraint if available
- has_naming = any(
- c.type in [ConstraintType.NAME_PATTERN, ConstraintType.LOCATION]
- for c in distinctive
- )
- if not has_naming:
- for c in sorted_constraints[3:]:
- if c.type in [
- ConstraintType.NAME_PATTERN,
- ConstraintType.LOCATION,
- ]:
- distinctive[-1] = c # Replace the least important
- break
-
- return distinctive
-
- def _extract_candidates_from_results(
- self, results: Dict, search_query: str
- ) -> List[Candidate]:
- """Extract potential candidates from search results."""
- knowledge = results.get("current_knowledge", "")
-
- # Also check the raw findings
- findings = results.get("findings", [])
- all_content = knowledge
-
- for finding in findings:
- if isinstance(finding, dict) and "content" in finding:
- all_content += "\n" + finding["content"]
-
- # First, understand what type of entity we're looking for
- type_prompt = f"""Based on this search query, what type of entity are we looking for?
-Search Query: {search_query}
-
-Common types include: location, person, organization, product, concept, event, etc.
-Answer with just the entity type, no explanation."""
-
- type_response = self.model.invoke(type_prompt)
- entity_type = remove_think_tags(type_response.content).strip().lower()
-
- # Now extract candidates based on the entity type
- prompt = f"""Extract potential {entity_type} candidates from these search results.
-
-Search Query: {search_query}
-
-Search Results:
-{all_content[:4000]}
-
-CRITICAL: Extract ONLY specific named entities that could answer the query.
-
-For example:
-- If looking for a character: extract "Sherlock Holmes", NOT "detective" or "fictional character"
-- If looking for a place: extract "Mount Everest", NOT "mountain" or "high peak"
-- If looking for a person: extract "Albert Einstein", NOT "scientist" or "physicist"
-
-Extract ONLY:
-1. Proper nouns and specific names
-2. Individual entities that could be the answer
-3. Concrete names mentioned in the text
-
-DO NOT extract:
-- Sources or websites (e.g., "Wikipedia", "IMDb")
-- General descriptions (e.g., "TV show", "fictional character")
-- Categories or types (e.g., "mountain", "scientist")
-- Meta-information about search results
-
-If the text mentions a work (book, movie, TV show) when looking for a character,
-extract CHARACTER NAMES from that work, not the work's title.
-
-Format each candidate as:
-CANDIDATE_1: [specific name]
-CANDIDATE_2: [specific name]
-...
-
-Limit to the 10 most relevant candidates."""
-
- response = self.model.invoke(prompt)
- content = remove_think_tags(str(response.content))
-
- candidates = []
- for line in content.strip().split("\n"):
- if line.startswith("CANDIDATE_"):
- name = line.split(":", 1)[1].strip().strip("\"'")
- # Basic validation - must be non-empty and reasonable length
- if name and 2 < len(name) < 100:
- # Additional validation based on entity type
- if entity_type in [
- "location",
- "place",
- "person",
- "organization",
- ]:
- # Should start with capital letter for these types
- if name[0].isupper():
- candidate = Candidate(name=name)
- candidates.append(candidate)
- else:
- # Other types might not need capital letters
- candidate = Candidate(name=name)
- candidates.append(candidate)
-
- return candidates[: self.candidate_limit]
-
- def _find_additional_candidates(self):
- """Find additional candidates if we don't have enough."""
- # Use different constraint combinations
- unused_constraints = [
- c
- for c in self.constraints
- if not any(c.id in cand.evidence for cand in self.candidates)
- ]
-
- if unused_constraints:
- search_query = self._create_candidate_search_query(
- unused_constraints[:3]
- )
- results = self._execute_search(search_query)
- new_candidates = self._extract_candidates_from_results(
- results, search_query
- )
-
- # Add only truly new candidates
- existing_names = {c.name.lower() for c in self.candidates}
- for candidate in new_candidates:
- if candidate.name.lower() not in existing_names:
- self.candidates.append(candidate)
- existing_names.add(candidate.name.lower())
-
- def _format_initial_analysis(self, query: str) -> str:
- """Format initial analysis summary."""
- # Group constraints by type
- constraint_groups = {}
- for c in self.constraints:
- type_name = c.type.name.replace("_", " ").title()
- if type_name not in constraint_groups:
- constraint_groups[type_name] = []
- constraint_groups[type_name].append(c)
-
- constraints_formatted = ""
- for type_name, constraints in constraint_groups.items():
- constraints_formatted += f"\n**{type_name}**:\n"
- for c in constraints:
- constraints_formatted += (
- f" • {c.description} (importance: {c.weight:.0%})\n"
- )
-
- return f"""
-**Research Query**: {query}
-
-**Strategy**: Evidence-Based Search
-**Approach**: Systematically identify candidates and verify each constraint
-
-**Identified Constraints**: {len(self.constraints)}
-{constraints_formatted}
-
-**Next Steps**:
-1. Search for candidates matching key constraints
-2. Gather evidence for each candidate-constraint pair
-3. Score candidates based on evidence quality
-4. Progressively refine until confident answer found
-
-**Starting Research...**
-""".strip()
-
- def _format_iteration_summary(self) -> str:
- """Format iteration summary."""
- top_candidates = self.candidates[:3]
-
- # Calculate overall progress
- total_evidence_needed = (
- len(self.candidates[:5]) * len(self.constraints)
- if self.candidates
- else 0
- )
- evidence_collected = sum(len(c.evidence) for c in self.candidates[:5])
- evidence_progress = (
- evidence_collected / total_evidence_needed
- if total_evidence_needed > 0
- else 0
- )
-
- summary = f"""
-**Iteration {self.iteration}**
-
-**Top Candidates**:
-{chr(10).join(f"{i + 1}. {c.name} (score: {c.score:.0%})" for i, c in enumerate(top_candidates)) if top_candidates else "No candidates found yet"}
-
-**Evidence Collection Progress**:
-- Total candidates: {len(self.candidates)}
-- Evidence gathered: {evidence_collected}/{total_evidence_needed} ({evidence_progress:.0%})
-- Constraints verified: {len([c for c in self.constraints if any(cand.evidence.get(c.id) for cand in self.candidates[:3])])}/{len(self.constraints)}
-
-**Current Search Focus**:
-"""
-
- if top_candidates:
- for candidate in top_candidates[:2]:
- satisfied = len(
- [
- c
- for c in self.constraints
- if c.id in candidate.evidence
- and candidate.evidence[c.id].confidence
- >= self.evidence_threshold
- ]
- )
- summary += f"\n{candidate.name} - {satisfied}/{len(self.constraints)} constraints satisfied:\n"
-
- for constraint in self.constraints[:3]:
- evidence = candidate.evidence.get(constraint.id)
- if evidence:
- summary += f" ✓ {constraint.description}: {evidence.confidence:.0%} confidence\n"
- else:
- summary += (
- f" ? {constraint.description}: Searching...\n"
- )
- else:
- summary += "\nSearching for initial candidates..."
- summary += "\nFocus: " + ", ".join(
- [c.type.value for c in self.constraints[:3]]
- )
-
- summary += f"\n**Overall Progress**: {self.iteration}/{self.max_iterations} iterations ({self.iteration / self.max_iterations:.0%})"
-
- # Add recent searches
- if self.search_history:
- recent_searches = self.search_history[-3:]
- summary += "\n\n**Recent Searches**:\n"
- summary += chr(10).join(
- f"- {s['query'][:60]}..." for s in recent_searches
- )
-
- return summary.strip()
-
- def _synthesize_final_answer(self, original_query: str) -> Dict:
- """Generate final answer based on evidence."""
- if not self.candidates:
- answer = "Unable to determine"
- confidence = 0
- else:
- top_candidate = self.candidates[0]
- answer = top_candidate.name
- confidence = int(top_candidate.score * 100)
-
- # Generate detailed explanation
- prompt = f"""
-Based on our evidence-based research, provide a final answer to:
-{original_query}
-
-Top Answer: {answer}
-Confidence: {confidence}%
-
-Evidence Summary:
-{self._format_evidence_summary()}
-
-Provide a clear, concise answer with justification based on the evidence.
-Include which constraints were satisfied and which weren't.
-"""
-
- response = self.model.invoke(prompt)
- final_answer = remove_think_tags(str(response.content))
-
- # Add final synthesis finding
- synthesis_finding = {
- "phase": "Final Synthesis",
- "content": self._format_final_synthesis(answer, confidence),
- "timestamp": self._get_timestamp(),
- }
- self.findings.append(synthesis_finding)
-
- # Compile questions
- questions_dict = {}
- for i, questions in enumerate(self.questions_by_iteration):
- if isinstance(questions, list):
- questions_dict[i + 1] = questions
- elif isinstance(questions, dict):
- questions_dict.update(questions)
-
- # Format findings
- formatted_findings = format_findings(
- self.findings, final_answer, questions_dict
- )
-
- return {
- "current_knowledge": final_answer,
- "formatted_findings": formatted_findings,
- "findings": self.findings,
- "iterations": self.iteration,
- "questions_by_iteration": questions_dict,
- "all_links_of_system": self.all_links_of_system,
- "sources": self.all_links_of_system,
- "candidates": [
- {
- "name": c.name,
- "score": c.score,
- "evidence": {
- k: {
- "claim": e.claim,
- "confidence": e.confidence,
- "type": e.type.value,
- }
- for k, e in c.evidence.items()
- },
- }
- for c in self.candidates[:5]
- ],
- "constraints": [
- {
- "id": c.id,
- "description": c.description,
- "weight": c.weight,
- "type": c.type.value,
- }
- for c in self.constraints
- ],
- "strategy": "evidence_based",
- }
-
- def _format_evidence_summary(self) -> str:
- """Format evidence summary for top candidates."""
- if not self.candidates:
- return "No candidates found"
-
- summary = ""
- for candidate in self.candidates[:2]:
- summary += f"\n{candidate.name} (score: {candidate.score:.2f}):\n"
- for constraint in self.constraints:
- evidence = candidate.evidence.get(constraint.id)
- if evidence:
- summary += (
- f" - {constraint.description}: {evidence.claim} "
- )
- summary += f"(confidence: {evidence.confidence:.2f}, type: {evidence.type.value})\n"
- else:
- summary += f" - {constraint.description}: No evidence\n"
-
- return summary
-
- def _format_final_synthesis(self, answer: str, confidence: int) -> str:
- """Format final synthesis summary."""
- if not self.candidates:
- evidence_summary = "No candidates found"
- constraint_breakdown = "Unable to verify constraints"
- else:
- top_candidate = self.candidates[0]
- satisfied = len(
- [
- c
- for c in self.constraints
- if c.id in top_candidate.evidence
- and top_candidate.evidence[c.id].confidence
- >= self.evidence_threshold
- ]
- )
- evidence_summary = (
- f"Satisfied {satisfied}/{len(self.constraints)} constraints"
- )
-
- # Create constraint satisfaction breakdown
- constraint_breakdown = "\n**Constraint Satisfaction**:\n"
- for constraint in self.constraints:
- evidence = top_candidate.evidence.get(constraint.id)
- if evidence and evidence.confidence >= self.evidence_threshold:
- constraint_breakdown += f"✓ {constraint.description} - {evidence.confidence:.0%} confidence\n"
- elif evidence:
- constraint_breakdown += f"⚠ {constraint.description} - {evidence.confidence:.0%} confidence (below threshold)\n"
- else:
- constraint_breakdown += (
- f"✗ {constraint.description} - No evidence found\n"
- )
-
- return f"""
-**Final Answer**: {answer} ({confidence}% confidence)
-
-**Research Summary**:
-- Strategy: Evidence-Based Search
-- Iterations completed: {self.iteration}/{self.max_iterations}
-- Candidates evaluated: {len(self.candidates)}
-- Evidence pieces collected: {sum(len(c.evidence) for c in self.candidates)}
-- {evidence_summary}
-
-**Top Candidates**:
-{chr(10).join(f"{i + 1}. {c.name} (score: {c.score:.0%})" for i, c in enumerate(self.candidates[:3]))}
-
-{constraint_breakdown}
-
-**Evidence Details**:
-{self._format_evidence_summary()}
-
-**Search Strategy**:
-- Total searches performed: {len(self.search_history)}
-- Constraint-focused searches: {len([s for s in self.search_history if any(c.description in s["query"] for c in self.constraints)])}
-- Candidate verification searches: {len([s for s in self.search_history if any(c.name in s["query"] for c in self.candidates)])}
-
-**Recent Search Queries**:
-{chr(10).join(f"{i + 1}. {s['query'][:80]}..." for i, s in enumerate(self.search_history[-5:]))}
-""".strip()
-
- def _get_timestamp(self) -> str:
- """Get current timestamp for findings."""
- return datetime.now(UTC).isoformat()
-
- def _calculate_evidence_coverage(self) -> float:
- """Calculate how much evidence we've collected across all candidates."""
- if not self.candidates or not self.constraints:
- return 0.0
-
- total_possible = len(self.candidates[:5]) * len(self.constraints)
- total_collected = sum(len(c.evidence) for c in self.candidates[:5])
-
- return total_collected / total_possible if total_possible > 0 else 0.0
-
- def _get_iteration_status(self) -> str:
- """Get a human-readable status for the current iteration."""
- if not self.candidates:
- return "Searching for initial candidates"
-
- top_score = self.candidates[0].score if self.candidates else 0
-
- if top_score >= self.confidence_threshold:
- return "Verifying top candidate"
- if top_score >= 0.7:
- return "Gathering final evidence"
- if top_score >= 0.5:
- return "Refining candidate scores"
- return "Exploring candidate evidence"
diff --git a/src/local_deep_research/advanced_search_system/strategies/evidence_based_strategy_v2.py b/src/local_deep_research/advanced_search_system/strategies/evidence_based_strategy_v2.py
deleted file mode 100644
index ec381c5323..0000000000
--- a/src/local_deep_research/advanced_search_system/strategies/evidence_based_strategy_v2.py
+++ /dev/null
@@ -1,1334 +0,0 @@
-"""
-Enhanced evidence-based search strategy for complex query resolution.
-
-This strategy addresses common issues with candidate discovery and evidence gathering:
-1. Multi-stage candidate discovery with fallback mechanisms
-2. Adaptive query generation based on past performance
-3. Cross-constraint search capabilities
-4. Source diversity management
-"""
-
-import math
-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 loguru import logger
-
-from ...utilities.search_utilities import remove_think_tags
-from ..candidates.base_candidate import Candidate
-from ..constraints.base_constraint import Constraint, ConstraintType
-from ..evidence.base_evidence import Evidence
-from .evidence_based_strategy import EvidenceBasedStrategy
-
-
-@dataclass
-class QueryPattern:
- """Pattern for generating search queries."""
-
- pattern: str
- success_rate: float = 0.0
- usage_count: int = 0
- constraint_types: List[ConstraintType] = field(default_factory=list)
-
-
-@dataclass
-class SourceProfile:
- """Profile for tracking source effectiveness."""
-
- source_name: str
- success_rate: float = 0.0
- usage_count: int = 0
- specialties: List[str] = field(default_factory=list)
- last_used: Optional[datetime] = None
-
-
-class EnhancedEvidenceBasedStrategy(EvidenceBasedStrategy):
- """
- Enhanced evidence-based strategy with improved candidate discovery.
-
- Key improvements:
- 1. Multi-stage candidate discovery
- 2. Adaptive query patterns
- 3. Cross-constraint capabilities
- 4. Source diversity tracking
- """
-
- def __init__(
- self,
- model: BaseChatModel,
- search: Any,
- all_links_of_system: List[Any],
- max_iterations: int = 20,
- confidence_threshold: float = 0.85,
- candidate_limit: int = 20, # Increased for better candidate variety
- evidence_threshold: float = 0.6,
- max_search_iterations: int = 2,
- questions_per_iteration: int = 3,
- min_candidates_threshold: int = 10, # Increased to ensure we have enough candidates
- enable_pattern_learning: bool = True,
- settings_snapshot: dict | None = None,
- ):
- """Initialize the enhanced evidence-based strategy."""
- # Call parent initializer with required arguments
- super().__init__(
- model=model,
- search=search,
- all_links_of_system=all_links_of_system,
- max_iterations=max_iterations,
- confidence_threshold=confidence_threshold,
- candidate_limit=candidate_limit,
- evidence_threshold=evidence_threshold,
- max_search_iterations=max_search_iterations,
- questions_per_iteration=questions_per_iteration,
- settings_snapshot=settings_snapshot,
- )
-
- # Enhanced-specific attributes
- self.min_candidates_threshold = min_candidates_threshold
- self.enable_pattern_learning = enable_pattern_learning
-
- # Pattern learning
- self.query_patterns: Dict[str, QueryPattern] = (
- self._initialize_patterns()
- )
- self.source_profiles: Dict[str, SourceProfile] = (
- self._initialize_sources()
- )
-
- # Failure tracking
- self.failed_queries: Set[str] = set()
- self.constraint_relationships: Dict[str, List[str]] = {}
-
- def _initialize_patterns(self) -> Dict[str, QueryPattern]:
- """Initialize query patterns for different constraint types."""
- return {
- "property_basic": QueryPattern(
- pattern="{value} {constraint_type}",
- constraint_types=[ConstraintType.PROPERTY],
- ),
- "property_character": QueryPattern(
- pattern="character with {value}",
- constraint_types=[ConstraintType.PROPERTY],
- ),
- "event_show": QueryPattern(
- pattern="TV show {value}",
- constraint_types=[ConstraintType.EVENT],
- ),
- "statistic_episodes": QueryPattern(
- pattern="{value} episodes series",
- constraint_types=[ConstraintType.STATISTIC],
- ),
- "cross_constraint": QueryPattern(
- pattern="{value1} AND {value2}", constraint_types=[]
- ),
- "semantic_expansion": QueryPattern(
- pattern='"{value}" OR "{synonym1}" OR "{synonym2}"',
- constraint_types=[],
- ),
- }
-
- def _initialize_sources(self) -> Dict[str, SourceProfile]:
- """Initialize source profiles for diversity tracking."""
- return {
- "wikipedia": SourceProfile(
- source_name="wikipedia",
- specialties=["characters", "properties", "general"],
- ),
- "imdb": SourceProfile(
- source_name="imdb",
- specialties=["tv_shows", "episodes", "statistics"],
- ),
- "fandom": SourceProfile(
- source_name="fandom",
- specialties=["characters", "properties", "backstory"],
- ),
- "tv_databases": SourceProfile(
- source_name="tv_databases",
- specialties=["shows", "episodes", "statistics"],
- ),
- "web": SourceProfile(source_name="web", specialties=["general"]),
- }
-
- def analyze_topic(self, query: str) -> Dict:
- """Analyze a topic using enhanced evidence-based approach."""
- # Initialize
- self.all_links_of_system.clear()
- self.questions_by_iteration = []
- self.findings = []
- self.iteration = 0
-
- if self.progress_callback:
- self.progress_callback(
- "Enhanced Evidence-Based Strategy initialized - beginning analysis",
- 1,
- {
- "phase": "initialization",
- "strategy": "enhanced_evidence_based",
- },
- )
-
- # Extract constraints
- if self.progress_callback:
- self.progress_callback(
- "Extracting verifiable constraints from query...",
- 3,
- {"phase": "constraint_extraction", "query_length": len(query)},
- )
-
- self.constraints = self.constraint_analyzer.extract_constraints(query)
-
- if self.progress_callback:
- self.progress_callback(
- f"Found {len(self.constraints)} constraints - analyzing relationships",
- 5,
- {
- "phase": "constraint_analysis",
- "constraint_count": len(self.constraints),
- "constraint_types": {
- c.type.name: c.weight for c in self.constraints[:5]
- },
- },
- )
-
- # Analyze constraint relationships
- self._analyze_constraint_relationships()
-
- # Find initial candidates with enhanced discovery
- if self.progress_callback:
- self.progress_callback(
- "Starting enhanced candidate discovery (multi-stage)",
- 8,
- {"phase": "candidate_discovery_start", "stages": 5},
- )
-
- self._enhanced_candidate_discovery()
-
- # Main evidence-gathering loop
- while (
- self.iteration < self.max_iterations
- and not self._has_sufficient_answer()
- ):
- self.iteration += 1
-
- # Progress for iteration
- if self.progress_callback:
- base_progress = 40
- iteration_progress = base_progress + int(
- (self.iteration / self.max_iterations) * 50
- )
-
- self.progress_callback(
- f"Iteration {self.iteration}/{self.max_iterations} - gathering evidence",
- iteration_progress,
- {
- "phase": "iteration_start",
- "iteration": self.iteration,
- "max_iterations": self.max_iterations,
- "candidates_count": len(self.candidates),
- "top_candidate": (
- self.candidates[0].name
- if self.candidates
- else "None"
- ),
- },
- )
-
- # Adaptive evidence gathering
- self._adaptive_evidence_gathering()
-
- # Score and prune with pattern learning
- if self.progress_callback:
- self.progress_callback(
- f"Scoring {len(self.candidates)} candidates based on evidence",
- None,
- {
- "phase": "scoring_start",
- "candidate_count": len(self.candidates),
- },
- )
-
- self._score_and_prune_adaptive()
-
- # Add iteration finding
- iteration_finding = {
- "phase": f"Iteration {self.iteration}",
- "content": self._format_iteration_summary(),
- "timestamp": self._get_timestamp(),
- "metadata": {
- "candidates": len(self.candidates),
- "patterns_used": len(self.query_patterns),
- "source_diversity": self._calculate_source_diversity(),
- },
- }
- self.findings.append(iteration_finding)
-
- # Adaptive candidate discovery if needed
- if len(self.candidates) < self.min_candidates_threshold:
- if self.progress_callback:
- self.progress_callback(
- f"Too few candidates ({len(self.candidates)}) - searching for more",
- None,
- {
- "phase": "adaptive_discovery",
- "current_candidates": len(self.candidates),
- "threshold": self.min_candidates_threshold,
- },
- )
- self._adaptive_candidate_discovery()
-
- # Final verification with source diversity
- if self.progress_callback:
- self.progress_callback(
- "Starting final verification of top candidates",
- 90,
- {
- "phase": "final_verification_start",
- "top_candidates": [c.name for c in self.candidates[:3]],
- },
- )
-
- self._enhanced_final_verification()
-
- # Generate final answer
- if self.progress_callback:
- self.progress_callback(
- "Synthesizing final answer based on evidence",
- 95,
- {
- "phase": "synthesis_start",
- "candidates_evaluated": len(self.candidates),
- "evidence_pieces": sum(
- len(c.evidence) for c in self.candidates
- ),
- },
- )
-
- result = self._synthesize_final_answer(query)
-
- if self.progress_callback:
- top_candidate = self.candidates[0] if self.candidates else None
- self.progress_callback(
- f"Analysis complete - {top_candidate.name if top_candidate else 'No answer found'}",
- 100,
- {
- "phase": "complete",
- "final_answer": (
- top_candidate.name
- if top_candidate
- else "Unable to determine"
- ),
- "confidence": top_candidate.score if top_candidate else 0,
- "candidates_evaluated": len(self.candidates),
- "evidence_pieces": sum(
- len(c.evidence) for c in self.candidates
- ),
- "iterations_used": self.iteration,
- },
- )
-
- return result
-
- def _enhanced_candidate_discovery(self):
- """Enhanced multi-stage candidate discovery."""
- all_candidates = []
- discovery_stages = [
- ("broad", "Broad discovery", self._broad_discovery_search),
- ("focused", "Focused constraints", self._focused_constraint_search),
- ("cross", "Cross-constraint", self._cross_constraint_search),
- ("semantic", "Semantic expansion", self._semantic_expansion_search),
- ("fallback", "Fallback search", self._fallback_search),
- ]
-
- stage_progress_base = 10
- stage_progress_increment = 5
- total_stages = len(discovery_stages)
-
- for i, (stage_name, stage_desc, stage_func) in enumerate(
- discovery_stages
- ):
- if self.progress_callback:
- progress = stage_progress_base + (i * stage_progress_increment)
- self.progress_callback(
- f"{stage_desc} search - looking for candidates [{i + 1}/{total_stages}]",
- progress,
- {
- "phase": f"discovery_{stage_name}",
- "stage": i + 1,
- "total_stages": total_stages,
- "candidates_found": len(all_candidates),
- "stage_description": stage_desc,
- },
- )
-
- stage_candidates = stage_func()
- new_candidates = len(stage_candidates)
- all_candidates.extend(stage_candidates)
-
- if self.progress_callback and new_candidates > 0:
- self.progress_callback(
- f"Found {new_candidates} candidates in {stage_desc} stage",
- None,
- {
- "phase": f"discovery_{stage_name}_results",
- "new_candidates": new_candidates,
- "total_candidates": len(all_candidates),
- },
- )
-
- # Early exit if we have enough candidates
- if len(all_candidates) >= self.min_candidates_threshold * 2:
- if self.progress_callback:
- self.progress_callback(
- f"Found sufficient candidates ({len(all_candidates)}) - ending discovery",
- 30,
- {
- "phase": "discovery_complete",
- "total_candidates": len(all_candidates),
- },
- )
- break
-
- # Deduplicate and add candidates
- self._add_unique_candidates(all_candidates)
-
- # If still not enough candidates, try more aggressive discovery
- if (
- len(self.candidates) < self.min_candidates_threshold
- and all_candidates
- ):
- if self.progress_callback:
- self.progress_callback(
- f"Only {len(self.candidates)} candidates - trying more aggressive search",
- None,
- {"phase": "aggressive_discovery"},
- )
- self._aggressive_supplemental_search()
-
- if self.progress_callback:
- self.progress_callback(
- f"Candidate discovery complete - {len(self.candidates)} unique candidates found",
- 35,
- {
- "phase": "discovery_complete",
- "unique_candidates": len(self.candidates),
- "candidate_names": [c.name for c in self.candidates[:10]],
- },
- )
-
- def _broad_discovery_search(self) -> List[Candidate]:
- """Initial broad search to discover potential candidates."""
- candidates = []
-
- # Extended patterns for broader discovery
- extended_patterns = [
- "{value}",
- "character {value}",
- "TV character {value}",
- "fictional character {value}",
- "{value} television",
- "{value} TV show",
- "{value} series",
- ]
-
- # Apply patterns to constraints
- for constraint in self.constraints[:4]: # Increased from 3
- for pattern_template in extended_patterns:
- query = pattern_template.replace("{value}", constraint.value)
-
- if query not in self.failed_queries and len(query) > 3:
- if self.progress_callback:
- self.progress_callback(
- f"Broad search: {query[:50]}...",
- None,
- {
- "phase": "broad_search_query",
- "query": query,
- "constraint_type": constraint.type.value,
- },
- )
-
- results = self._execute_adaptive_search(query)
- extracted = (
- self._extract_candidates_with_enhanced_validation(
- results, query
- )
- )
- candidates.extend(extracted)
-
- if not extracted:
- self.failed_queries.add(query)
-
- return candidates
-
- def _focused_constraint_search(self) -> List[Candidate]:
- """Focused search using specific constraint values."""
- candidates = []
-
- # Get high-weight constraints
- high_weight_constraints = sorted(
- self.constraints, key=lambda c: c.weight, reverse=True
- )[:5]
-
- for i, constraint in enumerate(high_weight_constraints):
- # Generate adaptive queries based on past performance
- queries = self._generate_adaptive_queries(constraint)
-
- if self.progress_callback:
- self.progress_callback(
- f"Focused search: {constraint.description[:40]}... [{i + 1}/{len(high_weight_constraints)}]",
- None,
- {
- "phase": "focused_constraint",
- "constraint": constraint.description,
- "constraint_weight": constraint.weight,
- "constraint_rank": i + 1,
- },
- )
-
- for query in queries[:3]: # Limit queries per constraint
- if query not in self.failed_queries:
- results = self._execute_adaptive_search(query)
- extracted = self._extract_candidates_from_results(
- results, query
- )
-
- if extracted:
- candidates.extend(extracted)
- # Learn from successful query
- self._learn_query_pattern(
- query, constraint, success=True
- )
- else:
- self.failed_queries.add(query)
-
- return candidates
-
- def _cross_constraint_search(self) -> List[Candidate]:
- """Search using combinations of constraints."""
- candidates = []
-
- # Find related constraint pairs
- constraint_pairs = self._find_related_constraint_pairs()
-
- if self.progress_callback and constraint_pairs:
- self.progress_callback(
- f"Cross-constraint search - {len(constraint_pairs)} pairs identified",
- None,
- {
- "phase": "cross_constraint_start",
- "pair_count": len(constraint_pairs),
- },
- )
-
- for i, (constraint1, constraint2) in enumerate(
- constraint_pairs[:5]
- ): # Limit combinations
- query = self._build_cross_constraint_query(constraint1, constraint2)
-
- if self.progress_callback:
- self.progress_callback(
- f"Combining: {constraint1.type.value} + {constraint2.type.value}",
- None,
- {
- "phase": "cross_constraint_pair",
- "pair": i + 1,
- "constraint1": constraint1.description[:30],
- "constraint2": constraint2.description[:30],
- },
- )
-
- if query not in self.failed_queries:
- results = self._execute_adaptive_search(query)
- extracted = self._extract_candidates_from_results(
- results, query
- )
-
- if extracted:
- candidates.extend(extracted)
- # Update constraint relationships
- self._update_constraint_relationships(
- constraint1, constraint2, True
- )
- else:
- self.failed_queries.add(query)
-
- return candidates
-
- def _semantic_expansion_search(self) -> List[Candidate]:
- """Search using semantic variations of constraints."""
- candidates = []
-
- # Use general semantic variations without specific terms
- for constraint in self.constraints[:4]:
- variations = self._generate_semantic_variations(constraint)
-
- for variation in variations[:3]: # Limit variations
- if variation not in self.failed_queries:
- results = self._execute_adaptive_search(variation)
- extracted = (
- self._extract_candidates_with_enhanced_validation(
- results, variation
- )
- )
-
- if extracted:
- candidates.extend(extracted)
- else:
- self.failed_queries.add(variation)
-
- return candidates
-
- def _fallback_search(self) -> List[Candidate]:
- """Fallback search with relaxed constraints."""
- candidates = []
-
- # Relax constraints by combining fewer requirements
- relaxed_queries = self._generate_relaxed_queries()
-
- for query in relaxed_queries[:3]:
- if query not in self.failed_queries:
- results = self._execute_adaptive_search(query)
- extracted = self._extract_candidates_from_results(
- results, query
- )
- candidates.extend(extracted)
-
- return candidates
-
- def _adaptive_evidence_gathering(self):
- """Enhanced evidence gathering with source diversity."""
- evidence_gathered = 0
- source_usage = {}
- total_to_gather = (
- min(5, len(self.candidates)) * 2
- ) # Max 2 constraints per candidate
-
- if self.progress_callback:
- self.progress_callback(
- f"Gathering evidence for top {min(5, len(self.candidates))} candidates",
- None,
- {
- "phase": "evidence_gathering_start",
- "candidates_to_process": min(5, len(self.candidates)),
- "total_evidence_needed": total_to_gather,
- },
- )
-
- for i, candidate in enumerate(self.candidates[:5]):
- unverified = candidate.get_unverified_constraints(self.constraints)
-
- if self.progress_callback:
- self.progress_callback(
- f"Processing {candidate.name} [{i + 1}/{min(5, len(self.candidates))}]",
- None,
- {
- "phase": "candidate_evidence",
- "candidate": candidate.name,
- "candidate_rank": i + 1,
- "unverified_constraints": len(unverified),
- },
- )
-
- for j, constraint in enumerate(
- unverified[:2]
- ): # Limit per candidate
- # Select diverse source
- source = self._select_diverse_source(
- source_usage, constraint.type
- )
-
- # Generate evidence query
- query = self._generate_evidence_query(candidate, constraint)
-
- if self.progress_callback:
- self.progress_callback(
- f"Searching {source} for: {query[:40]}...",
- None,
- {
- "phase": "evidence_search",
- "candidate": candidate.name,
- "constraint": constraint.description[:50],
- "source": source,
- "query": query,
- },
- )
-
- # Execute search with selected source
- results = self._execute_search_with_source(query, source)
-
- # Extract and evaluate evidence
- evidence = self.evidence_evaluator.extract_evidence(
- results.get("current_knowledge", ""),
- candidate.name,
- constraint,
- )
-
- candidate.add_evidence(constraint.id, evidence)
- evidence_gathered += 1
-
- if self.progress_callback:
- self.progress_callback(
- f"Evidence found: {evidence.confidence:.0%} confidence",
- None,
- {
- "phase": "evidence_result",
- "candidate": candidate.name,
- "constraint": constraint.description[:50],
- "confidence": evidence.confidence,
- "evidence_type": evidence.type.value,
- "progress": f"{evidence_gathered}/{total_to_gather}",
- },
- )
-
- # Update source profile
- self._update_source_profile(source, evidence.confidence)
-
- if self.progress_callback:
- self.progress_callback(
- f"Evidence gathering complete - {evidence_gathered} pieces collected",
- None,
- {
- "phase": "evidence_complete",
- "evidence_count": evidence_gathered,
- "source_diversity": self._calculate_source_diversity(),
- "sources_used": len(
- [s for s in source_usage.values() if s > 0]
- ),
- },
- )
-
- def _generate_adaptive_queries(self, constraint: Constraint) -> List[str]:
- """Generate queries based on past performance."""
- queries = []
-
- # Get successful patterns for this constraint type
- successful_patterns = sorted(
- [
- p
- for p in self.query_patterns.values()
- if constraint.type in p.constraint_types
- and p.success_rate > 0.3
- ],
- key=lambda p: p.success_rate,
- reverse=True,
- )
-
- # Apply patterns
- for pattern in successful_patterns[:3]:
- query = self._apply_pattern_to_constraint(pattern, constraint)
- queries.append(query)
-
- # Add semantic variations
- semantic_queries = self._generate_semantic_variations(constraint)
- queries.extend(semantic_queries[:2])
-
- # Add fallback basic query
- queries.append(f"{constraint.value} {constraint.type.value}")
-
- return queries
-
- def _apply_pattern_to_constraint(
- self, pattern: QueryPattern, constraint: Constraint
- ) -> str:
- """Apply a pattern to a constraint to create a query."""
- query = pattern.pattern
-
- # Replace placeholders
- query = query.replace("{value}", constraint.value)
- query = query.replace("{constraint_type}", constraint.type.value)
-
- # Add synonyms if pattern requires them
- if "{synonym" in query:
- synonyms = self._get_synonyms(constraint.value)
- for i, synonym in enumerate(synonyms[:2], 1):
- query = query.replace(f"{{synonym{i}}}", synonym)
-
- return query
-
- def _build_cross_constraint_query(
- self, constraint1: Constraint, constraint2: Constraint
- ) -> str:
- """Build query combining multiple constraints."""
- # Identify common terms
- common_terms = self._find_common_terms(constraint1, constraint2)
-
- if common_terms:
- base = " ".join(common_terms)
- query = f"{base} {constraint1.value} {constraint2.value}"
- else:
- query = f"{constraint1.value} AND {constraint2.value}"
-
- # Add type-specific context
- if (
- constraint1.type == ConstraintType.PROPERTY
- and constraint2.type == ConstraintType.EVENT
- ):
- query += " TV show character"
-
- return query
-
- def _select_diverse_source(
- self, source_usage: Dict[str, int], constraint_type: ConstraintType
- ) -> str:
- """Select source to ensure diversity."""
- # Get specialized sources for constraint type
- specialized = self._get_specialized_sources(constraint_type)
-
- # Sort by usage (least used first) and success rate
- available_sources = sorted(
- self.source_profiles.values(),
- key=lambda s: (source_usage.get(s.source_name, 0), -s.success_rate),
- )
-
- # Prefer specialized sources
- for source in available_sources:
- if source.source_name in specialized:
- source_usage[source.source_name] = (
- source_usage.get(source.source_name, 0) + 1
- )
- return source.source_name
-
- # Fallback to least used source
- selected = available_sources[0].source_name
- source_usage[selected] = source_usage.get(selected, 0) + 1
- return selected
-
- def _get_specialized_sources(
- self, constraint_type: ConstraintType
- ) -> List[str]:
- """Get specialized sources for constraint type."""
- specialization_map = {
- ConstraintType.PROPERTY: ["fandom", "wikipedia"],
- ConstraintType.EVENT: ["imdb", "tv_databases"],
- ConstraintType.STATISTIC: ["imdb", "tv_databases"],
- ConstraintType.LOCATION: ["wikipedia"],
- }
- return specialization_map.get(constraint_type, ["web"])
-
- def _update_pattern_success(self, pattern: QueryPattern, success: bool):
- """Update pattern success rate."""
- pattern.usage_count += 1
- if success:
- # Exponential moving average
- alpha = 0.3
- pattern.success_rate = (
- alpha * 1.0 + (1 - alpha) * pattern.success_rate
- )
- else:
- pattern.success_rate = (1 - 0.3) * pattern.success_rate
-
- def _update_source_profile(self, source_name: str, confidence: float):
- """Update source profile based on evidence quality."""
- if source_name in self.source_profiles:
- profile = self.source_profiles[source_name]
- profile.usage_count += 1
- profile.last_used = datetime.now(UTC)
-
- # Update success rate based on confidence
- alpha = 0.3
- success = 1.0 if confidence >= self.evidence_threshold else 0.0
- profile.success_rate = (
- alpha * success + (1 - alpha) * profile.success_rate
- )
-
- def _analyze_constraint_relationships(self):
- """Analyze relationships between constraints."""
- for i, constraint1 in enumerate(self.constraints):
- for constraint2 in self.constraints[i + 1 :]:
- # Check for common terms or semantic similarity
- common_terms = self._find_common_terms(constraint1, constraint2)
- if common_terms:
- self.constraint_relationships[constraint1.id] = (
- self.constraint_relationships.get(constraint1.id, [])
- + [constraint2.id]
- )
- self.constraint_relationships[constraint2.id] = (
- self.constraint_relationships.get(constraint2.id, [])
- + [constraint1.id]
- )
-
- def _find_related_constraint_pairs(
- self,
- ) -> List[Tuple[Constraint, Constraint]]:
- """Find constraint pairs that might work well together."""
- pairs = []
-
- # Use analyzed relationships
- for constraint_id, related_ids in self.constraint_relationships.items():
- constraint = next(
- (c for c in self.constraints if c.id == constraint_id), None
- )
- if constraint:
- for related_id in related_ids:
- related = next(
- (c for c in self.constraints if c.id == related_id),
- None,
- )
- if related and (constraint, related) not in pairs:
- pairs.append((constraint, related))
-
- # Add type-based pairs
- property_constraints = [
- c for c in self.constraints if c.type == ConstraintType.PROPERTY
- ]
- event_constraints = [
- c for c in self.constraints if c.type == ConstraintType.EVENT
- ]
-
- for prop in property_constraints[:2]:
- for event in event_constraints[:2]:
- if (prop, event) not in pairs:
- pairs.append((prop, event))
-
- return pairs
-
- def _calculate_source_diversity(self) -> float:
- """Calculate source diversity score."""
- if not self.source_profiles:
- return 0.0
-
- used_sources = [
- s for s in self.source_profiles.values() if s.usage_count > 0
- ]
- if not used_sources:
- return 0.0
-
- # Calculate entropy of source usage
- total_usage = sum(s.usage_count for s in used_sources)
- entropy = 0.0
-
- for source in used_sources:
- if source.usage_count > 0:
- p = source.usage_count / total_usage
- entropy -= p * (math.log2(p) if p > 0 else 0)
-
- # Normalize by maximum possible entropy
- max_entropy = -math.log2(1 / len(used_sources))
- return entropy / max_entropy if max_entropy > 0 else 0.0
-
- def _execute_adaptive_search(self, query: str) -> Dict:
- """Execute search with adaptive source selection."""
- # Simple wrapper for consistency - could be enhanced with source selection
- return self._execute_search(query)
-
- def _execute_search_with_source(self, query: str, source: str) -> Dict:
- """Execute search with specific source."""
- # For now, use the standard search - could be enhanced to use specific sources
- return self._execute_search(query)
-
- def _get_synonyms(self, term: str) -> List[str]:
- """Get synonyms for a term - generic implementation."""
- # Use LLM to generate synonyms dynamically
- try:
- prompt = f"List 3 synonyms or similar terms for '{term}'. Return only the synonyms, one per line."
- response = self.model.invoke(prompt)
- content = remove_think_tags(str(response.content))
- synonyms = [
- line.strip() for line in content.split("\n") if line.strip()
- ]
- return synonyms[:3]
- except Exception as e:
- logger.debug(f"Error getting synonyms for '{term}': {e}")
- return []
-
- def _find_common_terms(
- self, constraint1: Constraint, constraint2: Constraint
- ) -> List[str]:
- """Find common terms between constraints."""
- terms1 = set(constraint1.value.lower().split())
- terms2 = set(constraint2.value.lower().split())
- return list(terms1.intersection(terms2))
-
- def _generate_semantic_variations(
- self, constraint: Constraint
- ) -> List[str]:
- """Generate semantically similar queries"""
- variations = []
-
- # Basic variations based on constraint type
- base_value = (
- constraint.value
- if hasattr(constraint, "value")
- else constraint.description
- )
-
- # Add contextual variations based on type
- if constraint.type == ConstraintType.PROPERTY:
- variations.extend(
- [
- f"entity with {base_value}",
- f"subject {base_value}",
- f"thing {base_value}",
- f"{base_value} entity",
- ]
- )
- elif constraint.type == ConstraintType.EVENT:
- variations.extend(
- [
- f"event {base_value}",
- f"occurrence {base_value}",
- f"{base_value} happened",
- f"when {base_value}",
- ]
- )
- elif constraint.type == ConstraintType.STATISTIC:
- variations.extend(
- [
- f"number {base_value}",
- f"count {base_value}",
- f"{base_value} total",
- f"quantity {base_value}",
- ]
- )
- else:
- # Generic variations
- variations.extend(
- [
- f"{base_value}",
- f"specific {base_value}",
- f"about {base_value}",
- f"regarding {base_value}",
- ]
- )
-
- return variations[:5] # Limit variations
-
- def _generate_evidence_query(
- self, candidate: Candidate, constraint: Constraint
- ) -> str:
- """Generate evidence query for a candidate-constraint pair."""
- prompt = f"""Create a search query to verify if "{candidate.name}" satisfies this constraint:
-Constraint: {constraint.description}
-Type: {constraint.type.value}
-
-Create a specific search query that would find evidence about whether this candidate meets this constraint.
-Return only the search query, no explanation."""
-
- response = self.model.invoke(prompt)
- query = remove_think_tags(str(response.content)).strip()
-
- # Fallback to simple query if needed
- if not query or len(query) < 5:
- query = f"{candidate.name} {constraint.value}"
-
- return query
-
- def _add_unique_candidates(self, candidates: List[Candidate]):
- """Add unique candidates to the main list."""
- existing_names = {c.name.lower() for c in self.candidates}
-
- for candidate in candidates:
- if candidate.name.lower() not in existing_names:
- self.candidates.append(candidate)
- existing_names.add(candidate.name.lower())
-
- # Limit total candidates
- self.candidates = self.candidates[: self.candidate_limit]
-
- def _adaptive_candidate_discovery(self):
- """Adaptive candidate discovery when we have too few candidates."""
- # Use unused constraints or different strategies
- unused_constraints = [
- c
- for c in self.constraints
- if not any(c.id in cand.evidence for cand in self.candidates)
- ]
-
- if unused_constraints:
- # Try cross-constraint search with unused constraints
- candidates = self._cross_constraint_search()
- self._add_unique_candidates(candidates)
-
- # If still not enough, try semantic expansion
- if len(self.candidates) < self.min_candidates_threshold:
- candidates = self._semantic_expansion_search()
- self._add_unique_candidates(candidates)
-
- def _generate_relaxed_queries(self) -> List[str]:
- """Generate relaxed queries for fallback search."""
- queries = []
-
- # Take most important constraints and relax them
- important_constraints = sorted(
- self.constraints, key=lambda c: c.weight, reverse=True
- )[:3]
-
- for constraint in important_constraints:
- # Simple value-based query
- queries.append(constraint.value)
-
- # Type-based query
- queries.append(f"{constraint.type.value} {constraint.value}")
-
- return queries
-
- def _learn_query_pattern(
- self, query: str, constraint: Constraint, success: bool
- ):
- """Learn from query success/failure."""
- if not self.enable_pattern_learning:
- return
-
- # Extract pattern from query
- # This is a simplified version - could be enhanced with ML
- pattern_key = f"{constraint.type.value}_custom"
-
- if pattern_key not in self.query_patterns:
- self.query_patterns[pattern_key] = QueryPattern(
- pattern=query, constraint_types=[constraint.type]
- )
-
- self._update_pattern_success(self.query_patterns[pattern_key], success)
-
- def _update_constraint_relationships(
- self, constraint1: Constraint, constraint2: Constraint, success: bool
- ):
- """Update constraint relationship tracking."""
- if success:
- # Strengthen the relationship
- if constraint1.id not in self.constraint_relationships:
- self.constraint_relationships[constraint1.id] = []
- if (
- constraint2.id
- not in self.constraint_relationships[constraint1.id]
- ):
- self.constraint_relationships[constraint1.id].append(
- constraint2.id
- )
-
- if constraint2.id not in self.constraint_relationships:
- self.constraint_relationships[constraint2.id] = []
- if (
- constraint1.id
- not in self.constraint_relationships[constraint2.id]
- ):
- self.constraint_relationships[constraint2.id].append(
- constraint1.id
- )
-
- def _wikipedia_search(self) -> List[Candidate]:
- """Search Wikipedia for general information."""
- candidates = []
-
- # Generic Wikipedia searches based on constraints
- for constraint in self.constraints[:3]:
- queries = [
- f"Wikipedia {constraint.value}",
- f"Wikipedia list {constraint.value}",
- f"Wikipedia {constraint.type.value} {constraint.value}",
- ]
-
- for query in queries:
- if query not in self.failed_queries:
- results = self._execute_adaptive_search(query)
- extracted = (
- self._extract_candidates_with_enhanced_validation(
- results, query
- )
- )
- candidates.extend(extracted)
-
- if not extracted:
- self.failed_queries.add(query)
-
- return candidates
-
- def _domain_specific_search(self) -> List[Candidate]:
- """Search domain-specific sources based on constraint types."""
- candidates = []
-
- # Map constraint types to relevant domains
- domain_map = {
- ConstraintType.PROPERTY: ["database", "encyclopedia", "wiki"],
- ConstraintType.EVENT: ["timeline", "history", "archive"],
- ConstraintType.STATISTIC: ["data", "statistics", "numbers"],
- ConstraintType.LOCATION: ["geography", "places", "maps"],
- }
-
- for constraint in self.constraints[:3]:
- domains = domain_map.get(constraint.type, ["general"])
-
- for domain in domains:
- query = f"{domain} {constraint.value}"
-
- if query not in self.failed_queries:
- results = self._execute_adaptive_search(query)
- extracted = (
- self._extract_candidates_with_enhanced_validation(
- results, query
- )
- )
- candidates.extend(extracted)
-
- if not extracted:
- self.failed_queries.add(query)
-
- return candidates
-
- def _aggressive_supplemental_search(self):
- """Aggressive supplemental search when we need more candidates."""
- additional_candidates = []
-
- # Try different query formulations
- query_templates = [
- "list of {value}",
- "examples of {value}",
- "types of {value}",
- "{value} instances",
- "specific {value}",
- "named {value}",
- ]
-
- for constraint in self.constraints:
- for template in query_templates:
- query = template.replace("{value}", constraint.value)
-
- if query not in self.failed_queries:
- results = self._execute_adaptive_search(query)
- extracted = (
- self._extract_candidates_with_enhanced_validation(
- results, query
- )
- )
- additional_candidates.extend(extracted)
-
- if len(additional_candidates) > 50: # Enough candidates
- break
-
- if len(additional_candidates) > 50:
- break
-
- self._add_unique_candidates(additional_candidates)
-
- def _extract_candidates_with_enhanced_validation(
- self, results: Dict, query: str
- ) -> List[Candidate]:
- """Extract candidates with better validation."""
- candidates = self._extract_candidates_from_results(results, query)
-
- # Additional validation to filter out non-candidates
- validated = []
- for candidate in candidates:
- # Basic validation - not too short, not a common word
- if len(candidate.name) > 2 and not self._is_common_word(
- candidate.name
- ):
- validated.append(candidate)
-
- return validated[:15] # Limit per search
-
- def _is_common_word(self, name: str) -> bool:
- """Check if a name is likely a common word rather than a proper name."""
- common_words = {
- "the",
- "and",
- "or",
- "but",
- "in",
- "on",
- "at",
- "to",
- "for",
- "of",
- "with",
- "by",
- "from",
- "up",
- "about",
- "into",
- "it",
- "is",
- "was",
- "are",
- }
- return name.lower() in common_words
-
- def _score_and_prune_adaptive(self):
- """Score and prune candidates with adaptive thresholds."""
- old_count = len(self.candidates)
-
- # Use the parent's scoring method
- super()._score_and_prune_candidates()
-
- # Additional adaptive pruning based on iteration
- if self.iteration > self.max_iterations / 2:
- # Be more aggressive in later iterations
- min_score = (
- max(0.3, self.candidates[0].score * 0.4)
- if self.candidates
- else 0.3
- )
- self.candidates = [
- c for c in self.candidates if c.score >= min_score
- ]
-
- if self.progress_callback:
- pruned = old_count - len(self.candidates)
- self.progress_callback(
- f"Scored candidates - kept {len(self.candidates)}, pruned {pruned}",
- None,
- {
- "phase": "scoring_complete",
- "candidates_kept": len(self.candidates),
- "candidates_pruned": pruned,
- "top_score": self.candidates[0].score
- if self.candidates
- else 0,
- "min_score_threshold": (
- min_score
- if self.iteration > self.max_iterations / 2
- else "adaptive"
- ),
- },
- )
-
- def _enhanced_final_verification(self):
- """Enhanced final verification with source diversity."""
- # Use parent's verification as base
- super()._final_verification()
-
- # Additional verification with unused sources
- if self.candidates:
- top_candidate = self.candidates[0]
-
- # Find least-used sources
- unused_sources = [
- s for s in self.source_profiles.values() if s.usage_count < 2
- ]
-
- for source in unused_sources[:2]:
- weak_constraints = [
- c
- for c in self.constraints
- if c.id not in top_candidate.evidence
- or top_candidate.evidence[c.id].confidence
- < self.evidence_threshold
- ]
-
- if weak_constraints:
- constraint = weak_constraints[0]
- query = self._generate_evidence_query(
- top_candidate, constraint
- )
-
- # Use specific source
- results = self._execute_search_with_source(
- query, source.source_name
- )
- evidence = self.evidence_evaluator.extract_evidence(
- results.get("current_knowledge", ""),
- top_candidate.name,
- constraint,
- )
-
- if evidence.confidence > (
- top_candidate.evidence.get(
- constraint.id, Evidence(claim="", confidence=0)
- ).confidence
- ):
- top_candidate.add_evidence(constraint.id, evidence)
-
- # Final re-scoring
- self._score_and_prune_adaptive()
diff --git a/src/local_deep_research/advanced_search_system/strategies/iterative_reasoning_strategy.py b/src/local_deep_research/advanced_search_system/strategies/iterative_reasoning_strategy.py
deleted file mode 100644
index fdbdba0587..0000000000
--- a/src/local_deep_research/advanced_search_system/strategies/iterative_reasoning_strategy.py
+++ /dev/null
@@ -1,818 +0,0 @@
-"""
-Iterative Reasoning Strategy for step-by-step search and reasoning.
-
-This strategy maintains a persistent knowledge base and iteratively:
-1. Analyzes what we know so far
-2. Decides what to search next
-3. Performs the search
-4. Updates knowledge with findings
-5. Repeats until confident in answer
-"""
-
-from dataclasses import dataclass, field
-from datetime import datetime, UTC
-from typing import Any, Dict, List, Optional
-
-from langchain_core.language_models import BaseChatModel
-from loguru import logger
-
-from ...utilities.search_utilities import format_findings, remove_think_tags
-from ..findings.repository import FindingsRepository
-from .base_strategy import BaseSearchStrategy
-from .source_based_strategy import SourceBasedSearchStrategy
-
-
-@dataclass
-class KnowledgeState:
- """Current state of our knowledge about the query."""
-
- original_query: str
- key_facts: List[str] = field(default_factory=list)
- uncertainties: List[str] = field(default_factory=list)
- search_history: List[Dict] = field(default_factory=list)
- candidate_answers: List[Dict] = field(default_factory=list)
- confidence: float = 0.0
- iteration: int = 0
-
- def to_string(self) -> str:
- """Convert knowledge state to readable string for LLM."""
- return f"""
-Original Query: {self.original_query}
-
-What We Know:
-{
- chr(10).join(f"- {fact}" for fact in self.key_facts)
- if self.key_facts
- else "- Nothing yet"
- }
-
-What We're Uncertain About:
-{
- chr(10).join(
- f"- {uncertainty}" for uncertainty in self.uncertainties
- )
- if self.uncertainties
- else "- Nothing specific"
- }
-
-Search History ({len(self.search_history)} searches):
-{
- chr(10).join(
- f"- Search {i + 1}: {s['query']}"
- for i, s in enumerate(self.search_history[-3:])
- )
- if self.search_history
- else "- No searches yet"
- }
-
-Candidate Answers ({len(self.candidate_answers)} total):
-{
- chr(10).join(
- f"- {c['answer']} (confidence: {c['confidence']:.0%})"
- for c in sorted(
- self.candidate_answers,
- key=lambda x: x["confidence"],
- reverse=True,
- )
- )
- if self.candidate_answers
- else "- None yet"
- }
-
-Current Confidence: {self.confidence:.1%}
-"""
-
-
-class IterativeReasoningStrategy(BaseSearchStrategy):
- """
- A strategy that iteratively searches and reasons, maintaining persistent knowledge.
-
- Simple loop:
- 1. Assess current knowledge
- 2. Decide next search
- 3. Execute search
- 4. Update knowledge
- 5. Check if we have answer
- """
-
- def __init__(
- self,
- model: BaseChatModel,
- search: Any,
- all_links_of_system: List[Any],
- max_iterations: int = 10,
- confidence_threshold: float = 0.85,
- search_iterations_per_round: int = 1,
- questions_per_search: int = 15,
- settings_snapshot: dict | None = None,
- ):
- """Initialize the iterative reasoning strategy.
-
- Args:
- model: The language model to use
- search: The search engine instance
- all_links_of_system: List to store all encountered links
- max_iterations: Maximum reasoning iterations
- confidence_threshold: Confidence needed to stop
- search_iterations_per_round: Iterations per search round
- questions_per_search: Questions per search
- settings_snapshot: Optional settings snapshot for configuration
- """
- super().__init__(
- all_links_of_system, settings_snapshot=settings_snapshot
- )
- self.model = model
- self.search = search
- self.max_iterations = max_iterations
- self.confidence_threshold = confidence_threshold
- self.search_iterations_per_round = search_iterations_per_round
- self.questions_per_search = questions_per_search
- self.findings_repository = FindingsRepository(model)
- self.knowledge_state: Optional[KnowledgeState] = None
-
- def analyze_topic(self, query: str) -> Dict:
- """Analyze a topic using iterative reasoning.
-
- Args:
- query: The research query to analyze
-
- Returns:
- Dictionary containing analysis results
- """
- # Initialize
- self.all_links_of_system.clear()
- self.questions_by_iteration = []
- self.findings = []
- self.knowledge_state = KnowledgeState(original_query=query)
-
- # Progress callback
- if self.progress_callback:
- self.progress_callback(
- "Starting iterative reasoning - will build knowledge step by step",
- 1,
- {
- "phase": "init",
- "strategy": "iterative_reasoning",
- "reasoning_approach": "step-by-step",
- },
- )
-
- logger.info(f"Starting iterative reasoning for: {query}")
- logger.info(
- f"Max iterations: {self.max_iterations}, Confidence threshold: {self.confidence_threshold}"
- )
-
- # Add initial analysis to findings
- initial_finding = {
- "phase": "Initial Analysis",
- "content": f"""
-**Query**: {query}
-
-**Strategy**: Iterative Reasoning
-- Will build knowledge step-by-step
-- Continue until {self.confidence_threshold:.0%} confident or {self.max_iterations} steps
-- Each step will search, analyze findings, and update knowledge
-
-**Starting Analysis**...
-""".strip(),
- "timestamp": self._get_timestamp(),
- }
- self.findings.append(initial_finding)
-
- # Main reasoning loop
- while (
- self.knowledge_state.iteration < self.max_iterations
- and self.knowledge_state.confidence < self.confidence_threshold
- ):
- self.check_termination()
- self.knowledge_state.iteration += 1
- logger.info(
- f"Iteration {self.knowledge_state.iteration}/{self.max_iterations}, Current confidence: {self.knowledge_state.confidence:.1%}"
- )
-
- # Update progress
- if self.progress_callback:
- progress = (
- int(
- (self.knowledge_state.iteration / self.max_iterations)
- * 80
- )
- + 10
- )
- facts_count = len(self.knowledge_state.key_facts)
- candidates_count = len(self.knowledge_state.candidate_answers)
-
- # Format top candidates for display
- top_candidates = ""
- if self.knowledge_state.candidate_answers:
- sorted_candidates = sorted(
- self.knowledge_state.candidate_answers,
- key=lambda x: x["confidence"],
- reverse=True,
- )[:2]
- top_candidates = ", ".join(
- f"{c['answer']} ({c['confidence']:.0%})"
- for c in sorted_candidates
- )
-
- self.progress_callback(
- f"Step {self.knowledge_state.iteration}: {facts_count} facts, {candidates_count} candidates. Top: {top_candidates if top_candidates else 'none yet'}",
- progress,
- {
- "phase": "reasoning",
- "iteration": self.knowledge_state.iteration,
- "confidence": self.knowledge_state.confidence,
- "facts_found": facts_count,
- "uncertainties": len(
- self.knowledge_state.uncertainties
- ),
- "candidates_count": candidates_count,
- "top_candidates": top_candidates,
- },
- )
-
- # Step 1: Analyze current knowledge and decide next search
- if self.progress_callback:
- self.progress_callback(
- f"Step {self.knowledge_state.iteration}: Deciding what to search next",
- progress + 2,
- {"phase": "planning", "step": "deciding_search"},
- )
-
- next_search = self._decide_next_search()
-
- if not next_search:
- logger.info("No more searches needed")
- if self.progress_callback:
- self.progress_callback(
- "Sufficient information gathered - preparing final answer",
- progress + 5,
- {"phase": "synthesis", "reason": "no_more_searches"},
- )
- break
-
- # Step 2: Execute the search
- if self.progress_callback:
- self.progress_callback(
- f"Step {self.knowledge_state.iteration}: Searching: {next_search[:50]}...",
- progress + 5,
- {"phase": "searching", "query": next_search},
- )
-
- search_results = self._execute_search(next_search)
-
- # Step 3: Update knowledge with findings
- if self.progress_callback:
- self.progress_callback(
- f"Step {self.knowledge_state.iteration}: Processing search results",
- progress + 8,
- {"phase": "processing", "step": "updating_knowledge"},
- )
-
- # Store confidence before update
- prev_confidence = self.knowledge_state.confidence
- prev_facts_count = len(self.knowledge_state.key_facts)
-
- self._update_knowledge(search_results)
-
- # Step 4: Check if we have a confident answer
- self._assess_answer()
-
- # Check if we made progress
- confidence_change = (
- self.knowledge_state.confidence - prev_confidence
- )
- new_facts = len(self.knowledge_state.key_facts) - prev_facts_count
-
- if confidence_change < 0.01 and new_facts == 0:
- # No significant progress - add a finding about this
- self.findings.append(
- {
- "phase": f"Low Progress Alert (Step {self.knowledge_state.iteration})",
- "content": f"Search '{next_search[:50]}...' yielded limited new information. May need to adjust search approach.",
- "timestamp": self._get_timestamp(),
- }
- )
-
- # Add a flag to indicate we need a different approach
- if not hasattr(self.knowledge_state, "low_progress_count"):
- self.knowledge_state.low_progress_count = 0
- self.knowledge_state.low_progress_count += 1
-
- if self.progress_callback:
- candidates_count = len(self.knowledge_state.candidate_answers)
- self.progress_callback(
- f"Step {self.knowledge_state.iteration} complete: {len(self.knowledge_state.key_facts)} facts, {candidates_count} candidates, {self.knowledge_state.confidence:.0%} confident",
- progress + 10,
- {
- "phase": "step_complete",
- "iteration": self.knowledge_state.iteration,
- "facts": len(self.knowledge_state.key_facts),
- "candidates": candidates_count,
- "confidence": self.knowledge_state.confidence,
- },
- )
-
- # Create detailed iteration findings
- iteration_summary = f"""
-**Search Query**: {next_search}
-
-**New Facts Discovered**:
-{
- chr(10).join(
- f"- {fact}" for fact in self.knowledge_state.key_facts[-3:]
- )
- if self.knowledge_state.key_facts
- else "- No new facts in this iteration"
- }
-
-**Current Candidates** ({len(self.knowledge_state.candidate_answers)} total):
-{
- chr(10).join(
- f"- {c['answer']} (confidence: {c['confidence']:.0%})"
- for c in sorted(
- self.knowledge_state.candidate_answers,
- key=lambda x: x["confidence"],
- reverse=True,
- )[:5]
- )
- if self.knowledge_state.candidate_answers
- else "- No candidates yet"
- }
-
-**Remaining Questions**:
-{
- chr(10).join(
- f"- {u}" for u in self.knowledge_state.uncertainties[:3]
- )
- if self.knowledge_state.uncertainties
- else "- No specific uncertainties"
- }
-
-**Progress**: {self.knowledge_state.confidence:.0%} confident after {
- self.knowledge_state.iteration
- } steps
-"""
-
- # Add iteration summary to findings
- self.findings.append(
- {
- "phase": f"Iteration {self.knowledge_state.iteration}",
- "content": iteration_summary.strip(),
- "search_query": next_search,
- "key_findings": self.knowledge_state.key_facts[
- -3:
- ], # Last 3 facts
- "confidence": self.knowledge_state.confidence,
- "timestamp": self._get_timestamp(),
- }
- )
-
- # Final synthesis
- if self.progress_callback:
- self.progress_callback(
- f"Creating final answer based on {len(self.knowledge_state.key_facts)} facts discovered",
- 90,
- {
- "phase": "final_synthesis",
- "facts_count": len(self.knowledge_state.key_facts),
- "total_searches": len(self.knowledge_state.search_history),
- "final_confidence": self.knowledge_state.confidence,
- },
- )
-
- final_result = self._synthesize_final_answer()
-
- if self.progress_callback:
- self.progress_callback(
- f"Analysis complete - {self.knowledge_state.iteration} reasoning steps, {len(self.knowledge_state.key_facts)} facts found",
- 100,
- {
- "phase": "complete",
- "strategy": "iterative_reasoning",
- "total_iterations": self.knowledge_state.iteration,
- "facts_discovered": len(self.knowledge_state.key_facts),
- "final_confidence": self.knowledge_state.confidence,
- },
- )
-
- return final_result
-
- def _decide_next_search(self) -> Optional[str]:
- """Decide what to search next based on current knowledge.
-
- Returns:
- Next search query, or None if done
- """
- # Check for low progress
- low_progress_warning = ""
- if (
- hasattr(self.knowledge_state, "low_progress_count")
- and self.knowledge_state.low_progress_count > 1
- ):
- low_progress_warning = f"\nNOTE: {self.knowledge_state.low_progress_count} recent searches yielded limited new information. Try a significantly different search approach."
-
- prompt = f"""Based on our current knowledge, decide what to search next.
-
-{self.knowledge_state.to_string()}{low_progress_warning}
-
-Consider:
-1. What specific information would help answer the original query?
-2. What uncertainties should we resolve?
-3. Should we verify any candidate answers?
-4. Do we need more specific or broader information?
-5. Can we combine multiple constraints into a more targeted search?
-6. Are there multiple candidates with similar confidence? If so, what searches would help distinguish between them?
-7. If recent searches haven't been productive, what completely different approach could we try?
-
-For puzzle-like queries with specific clues, try to:
-- Search for locations that match multiple criteria at once
-- Use specific place names when possible
-- Include relevant statistics or dates mentioned
-- If multiple candidates exist, search for distinguishing features
-- If searches are repetitive, try broader regional searches or different constraint combinations
-
-If we have one clear candidate with high confidence and low uncertainty, respond with "DONE".
-If multiple candidates have similar confidence, continue searching to distinguish between them.
-
-Otherwise, provide:
-NEXT_SEARCH: [specific search query that targets the constraints]
-REASONING: [why this search will help]
-EXPECTED_OUTCOME: [what we hope to learn]
-"""
-
- response = self.model.invoke(prompt)
- content = remove_think_tags(str(response.content))
-
- logger.debug(f"LLM response for next search: {content[:200]}...")
-
- if "DONE" in content:
- logger.info("LLM decided no more searches needed")
- return None
-
- # Parse response
- lines = content.strip().split("\n")
- next_search = None
- reasoning = ""
-
- for line in lines:
- if line.startswith("NEXT_SEARCH:"):
- next_search = line.split(":", 1)[1].strip()
- elif line.startswith("REASONING:"):
- reasoning = line.split(":", 1)[1].strip()
-
- if next_search:
- logger.info(f"Next search: {next_search}")
- logger.info(f"Reasoning: {reasoning}")
- else:
- logger.warning("Could not extract next search from LLM response")
- # Try to extract any search-like query from the response
- for line in lines:
- if (
- len(line) > 10 and "?" not in line
- ): # Heuristic for search queries
- next_search = line.strip()
- logger.info(f"Extracted fallback search: {next_search}")
- break
-
- return next_search
-
- def _execute_search(self, search_query: str) -> Dict:
- """Execute a search using the source-based strategy.
-
- Args:
- search_query: The query to search
-
- Returns:
- Search results
- """
- logger.info(f"Executing search: {search_query}")
-
- # Use source-based strategy for actual search
- source_strategy = SourceBasedSearchStrategy(
- model=self.model,
- search=self.search,
- all_links_of_system=self.all_links_of_system,
- include_text_content=True,
- use_cross_engine_filter=True,
- use_atomic_facts=True,
- )
-
- source_strategy.max_iterations = self.search_iterations_per_round
- source_strategy.questions_per_iteration = self.questions_per_search
-
- if self.progress_callback:
- # Create a wrapped callback that includes our iteration info
- def wrapped_callback(message, progress, data):
- data["parent_iteration"] = self.knowledge_state.iteration
- data["parent_strategy"] = "iterative_reasoning"
- # Make the message clearer for the GUI
- if "Searching" in message:
- display_message = (
- f"Step {self.knowledge_state.iteration}: {message}"
- )
- elif "questions" in message.lower():
- display_message = f"Step {self.knowledge_state.iteration}: Generating follow-up questions"
- elif "findings" in message.lower():
- display_message = f"Step {self.knowledge_state.iteration}: Processing findings"
- else:
- display_message = (
- f"Step {self.knowledge_state.iteration}: {message}"
- )
-
- self.progress_callback(display_message, progress, data)
-
- source_strategy.set_progress_callback(wrapped_callback)
-
- results = source_strategy.analyze_topic(search_query)
-
- # Track search history
- self.knowledge_state.search_history.append(
- {
- "query": search_query,
- "timestamp": self._get_timestamp(),
- "findings_count": len(results.get("findings", [])),
- "sources_count": len(results.get("sources", [])),
- }
- )
-
- # Update our tracking
- if "questions_by_iteration" in results:
- self.questions_by_iteration.extend(
- results["questions_by_iteration"]
- )
-
- return results
-
- def _update_knowledge(self, search_results: Dict):
- """Update knowledge state with new findings.
-
- Args:
- search_results: Results from the search
- """
- current_knowledge = search_results.get("current_knowledge", "")
-
- if not current_knowledge:
- return
-
- prompt = f"""Update our knowledge based on new search results.
-
-Current Knowledge State:
-{self.knowledge_state.to_string()}
-
-New Information:
-{current_knowledge[:2000]} # Truncate if too long
-
-Extract:
-1. KEY_FACTS: Specific facts that help answer the original query
-2. NEW_UNCERTAINTIES: Questions that arose from this search
-3. CANDIDATE_ANSWERS: Possible answers to the original query with confidence (0-1)
-4. RESOLVED_UNCERTAINTIES: Which previous uncertainties were resolved
-
-Format:
-KEY_FACTS:
-- [fact 1]
-- [fact 2]
-
-NEW_UNCERTAINTIES:
-- [uncertainty 1]
-
-CANDIDATE_ANSWERS:
-- [answer]: [confidence]
-
-RESOLVED_UNCERTAINTIES:
-- [resolved uncertainty]
-"""
-
- response = self.model.invoke(prompt)
- content = remove_think_tags(str(response.content))
-
- # Parse response and update knowledge state
- lines = content.strip().split("\n")
- current_section = None
-
- for line in lines:
- line = line.strip()
- if not line:
- continue
-
- if line.startswith("KEY_FACTS:"):
- current_section = "facts"
- elif line.startswith("NEW_UNCERTAINTIES:"):
- current_section = "uncertainties"
- elif line.startswith("CANDIDATE_ANSWERS:"):
- current_section = "candidates"
- elif line.startswith("RESOLVED_UNCERTAINTIES:"):
- current_section = "resolved"
- elif line.startswith("-") and current_section:
- item = line[1:].strip()
-
- if current_section == "facts":
- if item not in self.knowledge_state.key_facts:
- self.knowledge_state.key_facts.append(item)
- elif current_section == "uncertainties":
- if item not in self.knowledge_state.uncertainties:
- self.knowledge_state.uncertainties.append(item)
- elif current_section == "candidates" and ":" in item:
- answer, confidence_str = item.split(":", 1)
- answer = answer.strip()
-
- # Skip invalid answers
- if (
- answer.lower() in ["none", "unknown", "n/a", ""]
- or len(answer) < 3
- ):
- continue
-
- try:
- confidence = float(confidence_str.strip())
- except ValueError:
- confidence = 0.5
-
- # Clean up answer text (remove duplicated confidence info)
- if "(confidence" in answer:
- answer = answer.split("(confidence")[0].strip()
-
- # Update or add candidate
- existing = False
- for candidate in self.knowledge_state.candidate_answers:
- if candidate["answer"].lower() == answer.lower():
- candidate["confidence"] = max(
- candidate["confidence"], confidence
- )
- existing = True
- break
-
- if not existing:
- self.knowledge_state.candidate_answers.append(
- {"answer": answer, "confidence": confidence}
- )
- elif current_section == "resolved":
- # Remove from uncertainties if present
- self.knowledge_state.uncertainties = [
- u
- for u in self.knowledge_state.uncertainties
- if item.lower() not in u.lower()
- ]
-
- logger.info(
- f"Knowledge updated: {len(self.knowledge_state.key_facts)} facts, "
- f"{len(self.knowledge_state.uncertainties)} uncertainties"
- )
-
- def _assess_answer(self):
- """Assess our confidence in the current answer."""
- if not self.knowledge_state.candidate_answers:
- self.knowledge_state.confidence = 0.0
- return
-
- # Sort candidates by confidence
- sorted_candidates = sorted(
- self.knowledge_state.candidate_answers,
- key=lambda x: x["confidence"],
- reverse=True,
- )
-
- best_candidate = sorted_candidates[0]
- base_confidence = best_candidate["confidence"]
-
- # Check if multiple candidates have similar confidence
- confidence_spread = 0.0
- if len(sorted_candidates) > 1:
- second_best = sorted_candidates[1]
- confidence_spread = (
- best_candidate["confidence"] - second_best["confidence"]
- )
-
- # If top two candidates are very close, reduce overall confidence
- if confidence_spread < 0.1: # Less than 10% difference
- base_confidence *= 0.8 # Reduce confidence by 20%
- logger.info(
- f"Multiple candidates with similar confidence: {best_candidate['answer']} ({best_candidate['confidence']:.0%}) vs {second_best['answer']} ({second_best['confidence']:.0%})"
- )
-
- # Consider multiple factors for overall confidence
- # Boost confidence if we have supporting facts
- fact_boost = min(len(self.knowledge_state.key_facts) * 0.05, 0.2)
-
- # Reduce confidence if we have many uncertainties
- uncertainty_penalty = min(
- len(self.knowledge_state.uncertainties) * 0.05, 0.2
- )
-
- # Boost if we've done multiple searches that confirm
- search_boost = min(len(self.knowledge_state.search_history) * 0.02, 0.1)
-
- # Penalty for too many candidates
- candidate_penalty = 0.0
- if len(self.knowledge_state.candidate_answers) > 3:
- candidate_penalty = min(
- (len(self.knowledge_state.candidate_answers) - 3) * 0.05, 0.15
- )
-
- self.knowledge_state.confidence = min(
- base_confidence
- + fact_boost
- + search_boost
- - uncertainty_penalty
- - candidate_penalty,
- 0.95, # Cap at 95% to leave room for synthesis
- )
-
- logger.info(
- f"Current confidence: {self.knowledge_state.confidence:.1%} (best: {best_candidate['answer']} at {best_candidate['confidence']:.0%}, spread: {confidence_spread:.1%})"
- )
-
- def _synthesize_final_answer(self) -> Dict:
- """Synthesize final answer from accumulated knowledge.
-
- Returns:
- Final results dictionary
- """
- # Get best answer (removed - not used anymore)
-
- # Create comprehensive answer
- prompt = f"""Provide a final answer to the original query based on our research.
-
-{self.knowledge_state.to_string()}
-
-Requirements:
-1. Directly answer the original query
-2. Reference the key facts that support the answer
-3. Acknowledge any remaining uncertainties
-4. Be concise but complete
-
-Final Answer:"""
-
- response = self.model.invoke(prompt)
- final_answer = remove_think_tags(str(response.content))
-
- # Add comprehensive final synthesis to findings
- synthesis_summary = f"""
-**Final Answer**:
-{final_answer}
-
-**Research Summary**:
-- Completed {self.knowledge_state.iteration} reasoning steps
-- Discovered {len(self.knowledge_state.key_facts)} key facts
-- Evaluated {len(self.knowledge_state.candidate_answers)} candidate answers
-- Final confidence: {self.knowledge_state.confidence:.0%}
-
-**Key Facts That Led to This Answer**:
-{chr(10).join(f"{i + 1}. {fact}" for i, fact in enumerate(self.knowledge_state.key_facts[:10]))}
-
-**Search History**:
-{chr(10).join(f"{i + 1}. {search['query']}" for i, search in enumerate(self.knowledge_state.search_history))}
-""".strip()
-
- self.findings.append(
- {
- "phase": "Final Synthesis",
- "content": synthesis_summary,
- "confidence": self.knowledge_state.confidence,
- "iterations": self.knowledge_state.iteration,
- "timestamp": self._get_timestamp(),
- }
- )
-
- # Compile all questions
- questions_dict = {}
- for i, questions in enumerate(self.questions_by_iteration):
- if isinstance(questions, list):
- questions_dict[i + 1] = questions
- elif isinstance(questions, dict):
- questions_dict.update(questions)
-
- # Format findings
- formatted_findings = format_findings(
- self.findings, final_answer, questions_dict
- )
-
- return {
- "current_knowledge": final_answer,
- "formatted_findings": formatted_findings,
- "findings": self.findings,
- "iterations": self.knowledge_state.iteration,
- "questions_by_iteration": questions_dict,
- "all_links_of_system": self.all_links_of_system,
- "sources": self.all_links_of_system,
- "knowledge_state": {
- "key_facts": self.knowledge_state.key_facts,
- "uncertainties": self.knowledge_state.uncertainties,
- "candidate_answers": self.knowledge_state.candidate_answers,
- "confidence": self.knowledge_state.confidence,
- "search_history": self.knowledge_state.search_history,
- },
- "strategy": "iterative_reasoning",
- "questions": {
- "total": sum(
- len(q) if isinstance(q, list) else 1
- for q in questions_dict.values()
- ),
- "by_iteration": questions_dict,
- },
- }
-
- def _get_timestamp(self) -> str:
- """Get current timestamp for findings."""
- return datetime.now(UTC).isoformat()
diff --git a/src/local_deep_research/advanced_search_system/strategies/iterative_refinement_strategy.py b/src/local_deep_research/advanced_search_system/strategies/iterative_refinement_strategy.py
deleted file mode 100644
index 0bc8dd3b59..0000000000
--- a/src/local_deep_research/advanced_search_system/strategies/iterative_refinement_strategy.py
+++ /dev/null
@@ -1,638 +0,0 @@
-"""
-Iterative Refinement Strategy
-
-This strategy orchestrates iterative refinement of research results by:
-1. Running initial research with a base strategy
-2. Using LLM to evaluate results and identify gaps
-3. Generating follow-up queries to address gaps
-4. Calling the follow-up strategy to refine results
-5. Repeating until quality threshold is met or max iterations reached
-"""
-
-from typing import Dict, Optional
-from loguru import logger
-
-from ...utilities.json_utils import extract_json, get_llm_response_text
-
-from .base_strategy import BaseSearchStrategy
-from .followup.enhanced_contextual_followup import (
- EnhancedContextualFollowUpStrategy,
-)
-
-
-class IterativeRefinementStrategy(BaseSearchStrategy):
- """
- Strategy that iteratively refines research results using LLM-guided decisions.
-
- This strategy acts as an orchestrator that:
- - Runs initial research using any base strategy
- - Evaluates results quality with LLM
- - Generates targeted follow-up queries
- - Uses EnhancedContextualFollowUpStrategy for refinement
- - Accumulates knowledge across iterations
- """
-
- def __init__(
- self,
- model,
- search,
- initial_strategy: BaseSearchStrategy,
- all_links_of_system=None,
- settings_snapshot=None,
- evaluation_frequency: int = 1,
- max_refinements: int = 3,
- confidence_threshold: float = 0.8,
- max_evaluation_tokens: Optional[int] = None, # None = no truncation
- **kwargs,
- ):
- """
- Initialize the iterative refinement strategy.
-
- Args:
- model: The LLM model to use
- search: The search engine
- initial_strategy: Base strategy for initial research and follow-up delegate
- all_links_of_system: Accumulated links from past searches
- settings_snapshot: Settings configuration
- evaluation_frequency: Evaluate after N refinement rounds (1 = every round)
- max_refinements: Maximum number of refinement cycles
- confidence_threshold: Confidence level to stop refinement (0.0-1.0)
- max_evaluation_tokens: Maximum tokens for LLM evaluation (None = no truncation)
- """
- super().__init__(all_links_of_system, settings_snapshot)
-
- # Validate parameters
- if not 0 <= confidence_threshold <= 1:
- raise ValueError("confidence_threshold must be between 0 and 1")
- if max_refinements < 0:
- raise ValueError("max_refinements must be non-negative")
- if evaluation_frequency < 1:
- raise ValueError("evaluation_frequency must be at least 1")
- if max_evaluation_tokens is not None and max_evaluation_tokens <= 0:
- raise ValueError("max_evaluation_tokens must be positive or None")
-
- self.model = model
- self.search = search
- self.initial_strategy = initial_strategy
- self.evaluation_frequency = evaluation_frequency
- self.max_refinements = max_refinements
- self.confidence_threshold = confidence_threshold
- self.max_evaluation_tokens = max_evaluation_tokens
-
- # Track refinement history
- self.refinement_history = []
-
- logger.info(
- f"IterativeRefinementStrategy initialized with "
- f"max_refinements={max_refinements}, "
- f"confidence_threshold={confidence_threshold}, "
- f"evaluation_frequency={evaluation_frequency}"
- )
-
- def analyze_topic(self, query: str) -> Dict:
- """
- Analyze a topic with iterative refinement.
-
- Args:
- query: The research query to analyze
-
- Returns:
- Research findings with iterative refinements
- """
- logger.info(f"Starting iterative refinement research for: {query}")
-
- self._update_progress(
- "Running initial research",
- 10,
- {"phase": "initial_research", "query": query},
- )
-
- # Step 1: Run initial research
- results = self.initial_strategy.analyze_topic(query)
-
- # Validate initial results before proceeding
- if not results:
- logger.warning("Initial research returned no results")
- return {
- "findings": [],
- "iterations": 0,
- "questions_by_iteration": {},
- "formatted_findings": "Error: Initial research failed to return results.",
- "current_knowledge": "",
- "error": "Initial research failed",
- }
-
- if "error" in results:
- logger.error(
- f"Initial research failed with error: {results['error']}"
- )
- return results
-
- if not results.get("all_links_of_system"):
- logger.warning(
- "Initial research returned no sources, skipping refinement"
- )
- # Still return the results we have, just without refinement
- results["refinement_metadata"] = {
- "strategy": "iterative_refinement",
- "refinements_performed": 0,
- "max_refinements": self.max_refinements,
- "final_confidence": 0.0,
- "total_sources": 0,
- "refinement_history": [],
- "skipped_reason": "No initial sources found",
- }
- return results
-
- # Build initial research context
- research_context = self._build_research_context(results, query)
-
- # Track all accumulated sources
- all_accumulated_sources = results.get("all_links_of_system", []).copy()
-
- refinement_count = 0
- rounds_since_evaluation = 0
-
- # Main refinement loop
- while refinement_count < self.max_refinements:
- self.check_termination()
- rounds_since_evaluation += 1
-
- # Evaluate if it's time (based on frequency)
- if rounds_since_evaluation >= self.evaluation_frequency:
- progress = 20 + (refinement_count * 60 / self.max_refinements)
-
- self._update_progress(
- f"Evaluating research quality (refinement {refinement_count + 1}/{self.max_refinements})",
- progress,
- {"phase": "evaluation", "refinement": refinement_count + 1},
- )
-
- # Step 2: Use LLM to evaluate current results
- evaluation = self._evaluate_with_llm(
- results, query, refinement_count
- )
-
- logger.info(
- f"LLM evaluation - Action: {evaluation.get('action')}, "
- f"Confidence: {evaluation.get('confidence', 0):.2f}"
- )
-
- # Record evaluation in history with full details
- self.refinement_history.append(
- {
- "iteration": refinement_count + 1,
- "evaluation": evaluation,
- "sources_count": len(all_accumulated_sources),
- "action": evaluation.get("action"),
- "confidence": evaluation.get("confidence", 0),
- "gaps": evaluation.get("gaps", []),
- "reasoning": evaluation.get("reasoning", ""),
- "query": evaluation.get("refinement_query", ""),
- }
- )
-
- # Check if we should stop
- if evaluation.get("action") == "COMPLETE":
- logger.info("LLM determined research is complete")
- break
-
- if evaluation.get("confidence", 0) >= self.confidence_threshold:
- logger.info(
- f"Confidence threshold met: {evaluation.get('confidence'):.2f} >= {self.confidence_threshold}"
- )
- break
-
- # Step 3: Generate follow-up query for refinement
- followup_query = evaluation.get("refinement_query")
-
- if not followup_query:
- logger.warning(
- "No refinement query generated, stopping refinement"
- )
- break
-
- logger.info(f"Refinement query: {followup_query}")
-
- self._update_progress(
- f"Running follow-up research: {followup_query[:100]}...",
- progress + 10,
- {"phase": "followup", "query": followup_query},
- )
-
- # Step 4: Create follow-up strategy with accumulated context
- # Reuse the initial strategy directly - it already has all configuration
- # The EnhancedContextualFollowUpStrategy will handle context properly
- followup_strategy = EnhancedContextualFollowUpStrategy(
- model=self.model,
- search=self.search,
- delegate_strategy=self.initial_strategy,
- all_links_of_system=[], # Fresh for this iteration
- settings_snapshot=self.settings_snapshot,
- research_context=research_context,
- )
-
- # Pass progress callback if available
- if self.progress_callback:
- followup_strategy.set_progress_callback(
- self.progress_callback
- )
-
- # Step 5: Run follow-up research
- followup_results = followup_strategy.analyze_topic(
- followup_query
- )
-
- # Check if follow-up produced useful results
- new_sources = followup_results.get("all_links_of_system", [])
- if len(new_sources) < 2:
- logger.info(
- f"Refinement yielded only {len(new_sources)} new sources, stopping refinement"
- )
- break
-
- # Step 6: Merge results
- results = self._merge_results(
- results, followup_results, followup_query
- )
-
- # Update accumulated sources (O(1) lookup with set)
- existing_urls = {s.get("url") for s in all_accumulated_sources}
- new_sources = followup_results.get("all_links_of_system", [])
- for source in new_sources:
- # Check if URL already exists to avoid duplicates
- if source.get("url") not in existing_urls:
- all_accumulated_sources.append(source)
- existing_urls.add(source.get("url"))
-
- # Update research context for next iteration
- research_context = self._build_research_context(results, query)
-
- # Reset evaluation counter
- rounds_since_evaluation = 0
-
- refinement_count += 1
-
- # Reorganize formatted_findings to show final result at the top
- separator_check = "---\n## Refinement:" in results.get(
- "formatted_findings", ""
- )
- logger.info(
- f"Checking reorganization: refinement_count={refinement_count}, has separator={separator_check}"
- )
- if refinement_count > 0 and "---\n## Refinement:" in results.get(
- "formatted_findings", ""
- ):
- logger.info(
- f"Reorganizing findings with {refinement_count} refinements"
- )
- # Split to get the last refinement
- parts = results["formatted_findings"].rsplit(
- "---\n## Refinement:", 1
- )
- if len(parts) == 2:
- last_refinement = "## Refinement:" + parts[1]
- # Extract just the content after the query line
- if "\n" in last_refinement:
- _, final_content = last_refinement.split("\n", 1)
-
- # Build confidence progression and evaluation details
- confidence_progression = []
- for hist in self.refinement_history:
- conf = hist["evaluation"].get("confidence", 0)
- confidence_progression.append(f"{conf:.0%}")
-
- confidence_str = (
- " → ".join(confidence_progression)
- if confidence_progression
- else "N/A"
- )
-
- # Build evaluation insights section
- evaluation_insights = []
- for i, hist in enumerate(self.refinement_history, 1):
- gaps = hist.get("gaps", [])
- reasoning = hist.get("reasoning", "")
- query = hist.get("query", "")
- action = hist.get("action", "")
-
- if gaps or reasoning:
- evaluation_insights.append(f"""
-**Refinement {i} Analysis:**
-- **Action**: {action}
-- **Gaps Identified**: {", ".join(gaps) if gaps else "None"}
-- **Reasoning**: {reasoning}
-- **Follow-up Query**: {query if query else "N/A"}""")
-
- insights_section = ""
- if evaluation_insights:
- insights_section = f"""
-
----
-
-## Refinement Analysis
-
-The LLM identified these issues and improvements during the refinement process:
-{"".join(evaluation_insights)}"""
-
- # Prepend final answer at top
- results["formatted_findings"] = f"""## Final Answer
-*After {refinement_count} refinement{"s" if refinement_count != 1 else ""} | Confidence progression: {confidence_str}*
-
-{final_content}{insights_section}
-
----
-
-## Research Progression
-
-{results["formatted_findings"]}"""
-
- # Add refinement metadata to results
- results["refinement_metadata"] = {
- "strategy": "iterative_refinement",
- "refinements_performed": refinement_count,
- "max_refinements": self.max_refinements,
- "final_confidence": self.refinement_history[-1]["evaluation"].get(
- "confidence", 0
- )
- if self.refinement_history
- else 0,
- "total_sources": len(all_accumulated_sources),
- "refinement_history": self.refinement_history,
- }
-
- # Ensure all accumulated sources are in final results
- results["all_links_of_system"] = all_accumulated_sources
-
- self._update_progress(
- f"Research complete after {refinement_count} refinement(s)",
- 100,
- {"phase": "complete", "refinements": refinement_count},
- )
-
- logger.info(
- f"Iterative refinement complete: {refinement_count} refinements, "
- f"{len(all_accumulated_sources)} total sources"
- )
-
- return results
-
- def _evaluate_with_llm(
- self, results: Dict, original_query: str, iteration: int
- ) -> Dict:
- """
- Use LLM to evaluate current research results and decide on refinement.
-
- Args:
- results: Current research results
- original_query: The original research query
- iteration: Current refinement iteration number
-
- Returns:
- Dictionary with evaluation results including action and refinement query
- """
- # Get formatted findings for evaluation
- findings = results.get("formatted_findings", "")
- sources_count = len(results.get("all_links_of_system", []))
-
- # Build gaps summary from refinement history
- previous_gaps = []
- if self.refinement_history:
- for hist in self.refinement_history:
- gaps = hist["evaluation"].get("gaps", [])
- previous_gaps.extend(gaps)
-
- prompt = f"""You are evaluating research results to determine if refinement is needed.
-
-Original Research Query: {original_query}
-Current Refinement Iteration: {iteration + 1} of {self.max_refinements}
-
-Current Research Findings:
-{findings if self.max_evaluation_tokens is None else findings[: self.max_evaluation_tokens]}
-
-Number of sources found: {sources_count}
-Previous gaps identified: {", ".join(previous_gaps) if previous_gaps else "None"}
-
-Your task is to critically evaluate these research results and decide what would most improve them.
-
-Key questions to consider:
-- Are the main entities/companies mentioned still active and correctly described?
-- Is the information current and up-to-date?
-- Are we missing obvious major players or important aspects?
-- Are there any suspicious claims that need verification?
-- Does the answer fully address what was asked?
-- Are there contradictions or inconsistencies?
-
-You have complete freedom to:
-- Ask verification questions ("Is X company still active in this field?")
-- Challenge assumptions ("Shouldn't Y also be considered a leader?")
-- Request missing perspectives ("What about competitor Z's approach?")
-- Seek recent updates ("What's the latest status as of 2024/2025?")
-- Explore contradictions ("Source says X but that conflicts with Y")
-
-Respond with ONLY valid JSON, no markdown formatting, no additional text before or after:
-{{
- "action": "REFINE" or "COMPLETE",
- "confidence": 0.0 to 1.0 (your honest assessment of completeness/accuracy),
- "gaps": ["list", "of", "identified", "gaps", "or", "concerns"],
- "reasoning": "Your honest evaluation - what's good, what's problematic, what's missing",
- "refinement_query": "If action is REFINE, ask whatever question would most improve the research - be creative and thorough"
-}}
-
-Be critical and thorough. It's better to verify and be sure than to present incorrect information.
-Your refinement query can be as long and specific as needed to get good results."""
-
- try:
- response = self.model.invoke(prompt)
- content = get_llm_response_text(response)
-
- evaluation = extract_json(content, expected_type=dict)
- except Exception as e:
- logger.exception("Error in LLM evaluation")
- # Return default to continue without refinement
- return {
- "action": "COMPLETE",
- "confidence": 0.5,
- "gaps": [],
- "reasoning": f"Evaluation error: {str(e)}",
- "refinement_query": None,
- }
-
- if evaluation is None:
- return {
- "action": "COMPLETE",
- "confidence": 0.5,
- "gaps": [],
- "reasoning": "Could not parse JSON from LLM response",
- "refinement_query": None,
- }
-
- # Validate and clean up the evaluation
- if "action" not in evaluation:
- evaluation["action"] = "COMPLETE"
-
- evaluation["action"] = evaluation["action"].upper()
- if evaluation["action"] not in ["REFINE", "COMPLETE"]:
- evaluation["action"] = "COMPLETE"
-
- # Ensure confidence is a float between 0 and 1
- evaluation["confidence"] = max(
- 0.0, min(1.0, float(evaluation.get("confidence", 0.5)))
- )
-
- # Ensure gaps is a list
- if not isinstance(evaluation.get("gaps", []), list):
- evaluation["gaps"] = []
-
- return evaluation
-
- def _build_research_context(
- self, results: Dict, original_query: str
- ) -> Dict:
- """
- Build research context for follow-up strategy.
-
- Args:
- results: Current research results
- original_query: Original research query
-
- Returns:
- Context dictionary for follow-up strategy
- """
- context = {
- "original_query": original_query,
- "past_findings": results.get("formatted_findings", ""),
- "past_sources": results.get("all_links_of_system", []),
- "resources": results.get("all_links_of_system", []),
- "delegate_strategy": self.initial_strategy.__class__.__name__.replace(
- "Strategy", ""
- )
- .replace("SearchStrategy", "")
- .lower(),
- }
-
- # Add iteration information if available
- if "questions_by_iteration" in results:
- context["questions_by_iteration"] = results[
- "questions_by_iteration"
- ]
-
- # Add findings if available
- if "findings" in results:
- context["findings"] = results["findings"]
-
- return context
-
- def _merge_results(
- self,
- original_results: Dict,
- followup_results: Dict,
- followup_query: str,
- ) -> Dict:
- """
- Merge follow-up results into original results.
-
- Args:
- original_results: Original research results
- followup_results: Follow-up research results
- followup_query: The follow-up query used
-
- Returns:
- Merged results dictionary
- """
- merged = original_results.copy()
-
- # Append new findings
- if "findings" in followup_results:
- if "findings" not in merged:
- merged["findings"] = []
-
- # Add a separator finding
- merged["findings"].append(
- {
- "phase": f"Refinement: {followup_query[:100]}",
- "content": f"Follow-up research for: {followup_query}",
- "type": "refinement_separator",
- }
- )
-
- # Add the new findings
- merged["findings"].extend(followup_results["findings"])
-
- # Merge formatted findings with clear separation
- if "formatted_findings" in followup_results:
- original_findings = merged.get("formatted_findings", "")
- followup_findings = followup_results["formatted_findings"]
-
- merged["formatted_findings"] = f"""{original_findings}
-
----
-## Refinement: {followup_query}
-
-{followup_findings}"""
-
- # Update current knowledge to latest
- if "current_knowledge" in followup_results:
- merged["current_knowledge"] = followup_results["current_knowledge"]
-
- # Merge questions by iteration
- if "questions_by_iteration" in followup_results:
- if "questions_by_iteration" not in merged:
- merged["questions_by_iteration"] = {}
-
- # Add follow-up questions with new keys
- max_iter = (
- max(merged["questions_by_iteration"].keys())
- if merged["questions_by_iteration"]
- else 0
- )
- # Create a list copy of items to avoid dictionary changed size during iteration error
- followup_items = list(
- followup_results["questions_by_iteration"].items()
- )
- for key, questions in followup_items:
- merged["questions_by_iteration"][max_iter + key] = questions
-
- # Merge links (handled in main loop to avoid duplicates)
- # Don't merge here as we handle it in analyze_topic
-
- return merged
-
- def set_progress_callback(self, callback):
- """
- Set progress callback for both this strategy and delegates.
-
- Args:
- callback: Progress callback function
- """
- super().set_progress_callback(callback)
- if self.initial_strategy:
- self.initial_strategy.set_progress_callback(callback)
-
- @property
- def citation_handler(self):
- """Expose the initial_strategy's citation_handler.
-
- Same rationale as ``EnhancedContextualFollowUpStrategy``: the
- wrapper does no citation work of its own, and external code
- (chat-mode streaming hookup in ``research_service.py``) accesses
- the handler via ``strategy.citation_handler``. Forwarding here
- keeps that path working if iterative-refinement is ever selected
- as the chat strategy. Returns ``None`` when no delegate is set
- so the call-site ``hasattr`` check short-circuits cleanly.
- """
- if self.initial_strategy is None:
- return None
- return getattr(self.initial_strategy, "citation_handler", None)
-
- def close(self):
- """Forward close() to initial_strategy so resource-holding
- strategies (e.g. ConstraintParallelStrategy) get a chance to shut
- down. Without this, AdvancedSearchSystem.close() would call
- BaseSearchStrategy.close() on the wrapper — a no-op — and never
- reach the wrapped strategy."""
- super().close()
- if self.initial_strategy is not None:
- from ...utilities.resource_utils import safe_close
-
- safe_close(self.initial_strategy, "initial strategy")
diff --git a/src/local_deep_research/advanced_search_system/strategies/iterdrag_strategy.py b/src/local_deep_research/advanced_search_system/strategies/iterdrag_strategy.py
deleted file mode 100644
index 78292d050f..0000000000
--- a/src/local_deep_research/advanced_search_system/strategies/iterdrag_strategy.py
+++ /dev/null
@@ -1,496 +0,0 @@
-"""
-IterDRAG strategy implementation.
-"""
-
-import json
-from datetime import datetime, UTC
-from typing import Dict, List
-
-from loguru import logger
-
-from ...citation_handler import CitationHandler
-
-# Model and search should be provided by AdvancedSearchSystem
-from ...config.thread_settings import get_setting_from_snapshot
-from ...utilities.search_utilities import extract_links_from_search_results
-from ..findings.repository import FindingsRepository
-from ..knowledge.standard_knowledge import StandardKnowledge
-from ..questions.decomposition_question import DecompositionQuestionGenerator
-from .base_strategy import BaseSearchStrategy
-
-
-class IterDRAGStrategy(BaseSearchStrategy):
- """IterDRAG strategy that breaks queries into sub-queries."""
-
- def __init__(
- self,
- search,
- model,
- max_iterations=3,
- subqueries_per_iteration=2,
- all_links_of_system=None,
- settings_snapshot=None,
- ):
- """Initialize the IterDRAG strategy with search and LLM.
-
- Args:
- search: Search engine to use for web queries
- model: LLM to use for text generation and reasoning
- max_iterations: Maximum number of iterations to run
- subqueries_per_iteration: Number of sub-queries to generate per iteration
- all_links_of_system: Optional list of links to initialize with
- settings_snapshot: Settings snapshot for thread context
- """
- super().__init__(
- all_links_of_system=all_links_of_system,
- settings_snapshot=settings_snapshot,
- )
- self.search = search
- self.model = model
- self.max_iterations = max_iterations
- self.subqueries_per_iteration = subqueries_per_iteration
-
- # Initialize progress callback
- self.progress_callback = None
- # Note: questions_by_iteration is already initialized by parent class
-
- # Create citation handler with settings
- self.citation_handler = CitationHandler(
- self.model, settings_snapshot=settings_snapshot
- )
-
- # Initialize components
- self.question_generator = DecompositionQuestionGenerator(self.model)
- self.knowledge_generator = StandardKnowledge(self.model)
- self.findings_repository = FindingsRepository(self.model)
-
- def _generate_subqueries(
- self, query: str, initial_results: List[Dict], current_knowledge: str
- ) -> List[str]:
- """Generate sub-queries based on initial search results and the main query."""
- try:
- # Format context for question generation
- context = f"""Current Query: {query}
-Current Date: {datetime.now(UTC).strftime("%Y-%m-%d")}
-Past Questions: {self.questions_by_iteration}
-Current Knowledge: {current_knowledge}
-
-Initial Search Results:
-{json.dumps(initial_results, indent=2)}"""
-
- # Generate sub-queries using the question generator
- return self.question_generator.generate_questions(
- query,
- context,
- questions_per_iteration=int(
- get_setting_from_snapshot(
- "search.questions_per_iteration",
- settings_snapshot=self.settings_snapshot,
- )
- or 3
- ),
- )
- except Exception:
- logger.exception("Error generating sub-queries")
- return []
-
- def analyze_topic(self, query: str) -> Dict:
- """IterDRAG implementation of the topic analysis process."""
- findings = []
- current_knowledge = ""
- section_links = []
-
- self._update_progress(
- "Initializing IterDRAG research system",
- 5,
- {"phase": "init", "strategy": "iterdrag"},
- )
-
- # Check if search engine is available
- if self.search is None:
- error_msg = "Error: No search engine available. Please check your configuration."
- self._update_progress(
- error_msg,
- 100,
- {
- "phase": "error",
- "error": "No search engine available",
- "status": "failed",
- },
- )
- return {
- "findings": [],
- "iterations": 0,
- "questions": {},
- "formatted_findings": "Error: Unable to conduct research without a search engine.",
- "current_knowledge": "",
- "error": error_msg,
- }
-
- # Initial search for the main query
- self._update_progress(
- "Performing initial search for main query",
- 10,
- {"phase": "search", "iteration": 1},
- )
-
- initial_results = self.search.run(query)
- if not initial_results:
- self._update_progress(
- "No initial results found",
- 15,
- {"phase": "search_complete", "result_count": 0},
- )
- initial_results = []
- else:
- self._update_progress(
- f"Found {len(initial_results)} initial results",
- 15,
- {
- "phase": "search_complete",
- "result_count": len(initial_results),
- },
- )
-
- # Extract and save links
- initial_links = extract_links_from_search_results(initial_results)
- self.all_links_of_system.extend(initial_links)
- section_links.extend(initial_links)
-
- # Generate sub-queries
- self._update_progress(
- "Generating sub-queries for IterDRAG analysis",
- 20,
- {"phase": "iterdrag_decomposition"},
- )
-
- sub_queries = self._generate_subqueries(
- query, initial_results, current_knowledge
- )
-
- # Store questions in repository and in self.questions_by_iteration
- self.questions_by_iteration = {0: sub_queries}
- self.findings_repository.set_questions_by_iteration(
- self.questions_by_iteration
- )
-
- if not sub_queries:
- logger.error("No sub-queries were generated to analyze.")
- finding = {
- "phase": "Analysis Error",
- "content": "No sub-queries could be generated for the main question.",
- "question": query,
- "search_results": [],
- }
- findings.append(finding)
- else:
- # Process each sub-query
- total_subqueries = len(sub_queries)
-
- for i, sub_query in enumerate(sub_queries, 1):
- progress_base = 25 + (i / total_subqueries * 50)
- self._update_progress(
- f"Processing sub-query {i} of {total_subqueries}: {sub_query}",
- int(progress_base),
- {"phase": "subquery", "subquery_index": i},
- )
-
- # Search for the sub-query
- try:
- sub_results = self.search.run(sub_query)
- if not sub_results:
- self._update_progress(
- f"No results for sub-query: {sub_query}",
- int(progress_base + 2),
- {"phase": "search_complete", "result_count": 0},
- )
- sub_results = []
- else:
- self._update_progress(
- f"Found {len(sub_results)} results for sub-query: {sub_query}",
- int(progress_base + 2),
- {
- "phase": "search_complete",
- "result_count": len(sub_results),
- },
- )
- except Exception:
- logger.exception("Error searching for sub-query")
- sub_results = []
-
- try:
- # Use previous knowledge to answer this sub-query
- result = self.citation_handler.analyze_followup(
- sub_query,
- sub_results,
- current_knowledge,
- nr_of_links=len(self.all_links_of_system),
- )
-
- # Extract and save links AFTER citation handler processes results
- sub_links = extract_links_from_search_results(sub_results)
- self.all_links_of_system.extend(sub_links)
- section_links.extend(sub_links)
-
- if result is not None:
- finding = {
- "phase": f"Sub-query {i}",
- "content": result["content"],
- "question": sub_query,
- "search_results": sub_results,
- "documents": result["documents"],
- }
- findings.append(finding)
- self.findings_repository.add_finding(sub_query, finding)
- self.findings_repository.add_documents(
- result["documents"]
- )
-
- # Add to current knowledge with space around +
- current_knowledge = (
- current_knowledge
- + "\n\n\n New: \n"
- + result["content"]
- )
- except Exception:
- logger.exception("Error analyzing sub-query results:")
- finding = {
- "phase": f"Follow-up Iteration 0.{i + 1}",
- "content": "Error analyzing sub-query results.",
- "question": sub_query,
- "search_results": [],
- "documents": [],
- }
- findings.append(finding)
- # Optionally update current_knowledge even if analysis failed?
-
- # Final answer synthesis based on all sub-query findings
- self._update_progress(
- "Synthesizing final answer from sub-queries",
- 80,
- {"phase": "final_synthesis"},
- )
-
- try:
- # Extract finding contents for synthesis
- finding_contents = [
- f["content"] for f in findings if "content" in f
- ]
-
- # Synthesize findings into a final answer
- final_answer = self.findings_repository.synthesize_findings(
- query=query,
- sub_queries=sub_queries,
- findings=finding_contents,
- accumulated_knowledge=current_knowledge,
- )
-
- # Check if the synthesis failed with an error
- if isinstance(final_answer, str) and final_answer.startswith(
- "Error:"
- ):
- logger.error(f"Synthesis returned an error: {final_answer}")
-
- # Extract error type for better handling
- error_type = "unknown"
- error_message = final_answer.lower()
-
- if "timeout" in error_message:
- error_type = "timeout"
- elif "token limit" in error_message:
- error_type = "token_limit"
- elif "rate limit" in error_message:
- error_type = "rate_limit"
- elif "connection" in error_message:
- error_type = "connection"
-
- # Log with specific error type
- logger.error(
- f"Synthesis failed with error type: {error_type}"
- )
-
- # Add error information to progress update
- self._update_progress(
- f"Synthesis failed: {error_type}. Attempting fallback...",
- 85,
- {"phase": "synthesis_error", "error_type": error_type},
- )
-
- # Try fallback: use the best individual finding as the final answer
- longest_finding = ""
- for f in findings:
- if isinstance(f, dict) and "content" in f:
- if len(f["content"]) > len(longest_finding):
- longest_finding = f["content"]
-
- if longest_finding:
- logger.info(
- "Using longest finding as fallback synthesis"
- )
- final_answer = f"""
-# Research Results (Fallback Mode)
-
-{longest_finding}
-
-## Note
-The final synthesis could not be completed due to an error: {final_answer}
-This is a fallback response using the most detailed individual finding.
- """
- else:
- # If we don't have any findings with content, use current_knowledge
- logger.info(
- "Using current knowledge as fallback synthesis"
- )
- final_answer = f"""
-# Research Results (Fallback Mode)
-
-{current_knowledge}
-
-## Note
-The final synthesis could not be completed due to an error: {final_answer}
-This is a fallback response using the accumulated knowledge.
- """
-
- # Create a synthesis finding
- finding = {
- "phase": "Final synthesis",
- "content": final_answer,
- "question": query,
- "search_results": [],
- "documents": [],
- }
- findings.append(finding)
-
- # Store the synthesized content
- self.findings_repository.add_finding(
- query + "_synthesis", final_answer
- )
-
- # Update current knowledge with the synthesized version
- current_knowledge = final_answer
- except Exception as e:
- logger.exception("Error synthesizing final answer")
-
- # Create an error finding
- error_finding = {
- "phase": "Final synthesis error",
- "content": f"Error during synthesis: {e!s}",
- "question": query,
- "search_results": [],
- "documents": [],
- }
- findings.append(error_finding)
-
- # If synthesis completely fails, construct a fallback answer from the most relevant findings
- self._update_progress(
- "Synthesis failed. Creating fallback summary...",
- 85,
- {"phase": "synthesis_fallback"},
- )
-
- try:
- # Extract best content from findings
- key_findings = []
- for i, f in enumerate(findings):
- if (
- isinstance(f, dict)
- and "content" in f
- and f.get("content")
- ):
- # Only take the first 500 chars of each finding for the fallback
- content_preview = f.get("content", "")[:500]
- if content_preview:
- key_findings.append(
- f"### Finding {i + 1}\n\n{content_preview}..."
- )
-
- # Create fallback content
- fallback_content = f"""
-# Research Results (Error Recovery Mode)
-
-## Original Query
-{query}
-
-## Key Findings
-{chr(10).join(key_findings[:5]) if key_findings else "No valid findings were generated."}
-
-## Error Information
-The system encountered an error during final synthesis: {e!s}
-This is an automatically generated fallback response.
- """
-
- final_answer = fallback_content
- except Exception as fallback_error:
- # Last resort fallback
- logger.exception("Even fallback creation failed")
- final_answer = f"""
-# Research Error
-
-The system encountered multiple errors while processing your query: "{query}"
-
-Primary error: {e!s}
-Fallback error: {fallback_error!s}
-
-Please try again with a different query or contact support.
- """
-
- # Compress knowledge if needed
- if (
- get_setting_from_snapshot(
- "general.knowledge_accumulation",
- "ITERATION",
- settings_snapshot=self.settings_snapshot,
- )
- == "ITERATION"
- ):
- try:
- self._update_progress(
- "Compressing knowledge",
- 90,
- {"phase": "knowledge_compression"},
- )
- current_knowledge = self.knowledge_generator.compress_knowledge(
- current_knowledge, query, section_links
- )
- except Exception:
- logger.exception("Error compressing knowledge")
-
- # Format and save findings
- self._update_progress(
- "Formatting and saving findings", 95, {"phase": "formatting"}
- )
-
- try:
- # First, get just the synthesized content without formatting
- if not isinstance(final_answer, str):
- logger.error(
- "final_answer is not a string, using current_knowledge as fallback"
- )
- final_answer = current_knowledge
-
- # Ensure latest questions are in the repository
- self.findings_repository.set_questions_by_iteration(
- self.questions_by_iteration
- )
-
- # Now format the findings with search questions and sources
- formatted_findings = (
- self.findings_repository.format_findings_to_text(
- findings, final_answer
- )
- )
- except Exception:
- logger.exception("Error formatting final findings")
- formatted_findings = (
- "Error: Could not format findings due to an error."
- )
-
- self._update_progress("Research complete", 100, {"phase": "complete"})
-
- return {
- "findings": findings, # Keep the detailed findings list
- "iterations": 1,
- "questions": self.questions_by_iteration, # Use the member variable instead of {"0": sub_queries}
- "formatted_findings": formatted_findings, # This is the fully formatted string for UI
- "current_knowledge": current_knowledge, # This is the synthesized content for knowledge base
- }
diff --git a/src/local_deep_research/advanced_search_system/strategies/modular_strategy.py b/src/local_deep_research/advanced_search_system/strategies/modular_strategy.py
deleted file mode 100644
index 02d4f6718c..0000000000
--- a/src/local_deep_research/advanced_search_system/strategies/modular_strategy.py
+++ /dev/null
@@ -1,1053 +0,0 @@
-"""
-Modular strategy that demonstrates usage of the new constraint_checking and candidate_exploration modules.
-Enhanced with LLM-driven constraint processing, early rejection, and immediate evaluation.
-"""
-
-import asyncio
-from concurrent.futures import ThreadPoolExecutor, as_completed
-from dataclasses import dataclass
-from typing import Dict, List, Optional, Tuple
-
-from loguru import logger
-
-from ...database.thread_local_session import thread_cleanup
-from ...utilities.json_utils import extract_json
-from ...utilities.search_cache import get_search_cache, normalize_entity_query
-from ..candidate_exploration import (
- AdaptiveExplorer,
- ConstraintGuidedExplorer,
- DiversityExplorer,
- ParallelExplorer,
-)
-from ..constraint_checking import (
- DualConfidenceChecker,
- StrictChecker,
- ThresholdChecker,
-)
-from ..constraints import ConstraintAnalyzer
-from ..questions import StandardQuestionGenerator
-from .base_strategy import BaseSearchStrategy
-
-
-@dataclass
-class CandidateConfidence:
- """Track candidate confidence levels for early rejection"""
-
- candidate: object
- positive_confidence: float
- negative_confidence: float
- rejection_reason: Optional[str] = None
- should_continue: bool = True
-
-
-class LLMConstraintProcessor:
- """LLM-driven intelligent constraint processing"""
-
- def __init__(self, model):
- self.model = model
-
- async def generate_intelligent_combinations(
- self, existing_queries=None, original_query=None
- ):
- """LLM generates smart combinations of atomic elements"""
-
- if existing_queries is None:
- existing_queries = []
-
- all_queries_used = (
- [original_query] + existing_queries
- if original_query
- else existing_queries
- )
- existing_queries_str = (
- "\n".join([f"- {q}" for q in all_queries_used])
- if all_queries_used
- else "None yet"
- )
-
- prompt = f"""
- Create search query variations using TWO strategies:
-
- ORIGINAL QUERY: "{original_query if original_query else "Not provided"}"
-
- ALREADY USED QUERIES (DO NOT REPEAT):
- {existing_queries_str}
-
- **STRATEGY 1: QUERY REFORMULATION** (5-8 variations)
- Keep ALL key information but rephrase the entire query:
- - Change word order and sentence structure
- - Use synonyms for key terms
- - Convert questions to statements or keyword phrases
- - Maintain all specific details (names, dates, numbers)
-
- **STRATEGY 2: RANGE SPLITTING** (10-15 variations)
- For any time periods, ranges, or multiple options, create separate specific searches:
- - Split year ranges into individual years
- - Split time periods into specific decades/years
- - Split "between X and Y" into individual values
- - Create one search per specific value in any range
-
- **EXAMPLES:**
- Original: "Who won Nobel Prize between 1960-1965?"
- - Reformulations: "Nobel Prize winner 1960-1965", "Nobel laureate from 1960 to 1965"
- - Range splits: "Nobel Prize winner 1960", "Nobel Prize winner 1961", "Nobel Prize winner 1962", "Nobel Prize winner 1963", "Nobel Prize winner 1964", "Nobel Prize winner 1965"
-
- Generate 15-25 search queries total (reformulations + range splits).
- Focus on maximum specificity through systematic coverage.
-
- Return as a valid JSON list of search queries:
- ["query1", "query2", "query3"]
- """
-
- response = await self.model.ainvoke(prompt)
- return self._parse_combinations(response.content)
-
- def _parse_combinations(self, content):
- """Parse LLM combinations response"""
- result = extract_json(content, expected_type=list)
- if result is not None:
- return result
-
- # If parsing fails, return empty list - let the system handle gracefully
- logger.warning("Failed to parse LLM combinations, returning empty list")
- return []
-
-
-class EarlyRejectionManager:
- """Manages early rejection and confidence tracking"""
-
- def __init__(self, model, positive_threshold=0.6, negative_threshold=0.3):
- self.model = model
- self.positive_threshold = positive_threshold
- self.negative_threshold = negative_threshold
- self.rejected_candidates = set()
-
- async def quick_confidence_check(self, candidate, constraints):
- """Quick confidence assessment for early rejection"""
-
- prompt = f"""
- Quickly assess if this candidate matches the search criteria:
-
- Candidate: {candidate.name}
- Available info: {getattr(candidate, "metadata", {})}
-
- Constraints to match:
- {[c.description for c in constraints]}
-
- Provide:
- 1. **Positive confidence** (0.0-1.0): How likely this candidate matches
- 2. **Negative confidence** (0.0-1.0): How likely this candidate does NOT match
- 3. **Quick reasoning**: Brief explanation
-
- Return as JSON:
- {{
- "positive_confidence": 0.X,
- "negative_confidence": 0.X,
- "reasoning": "brief explanation"
- }}
- """
-
- try:
- response = await self.model.ainvoke(prompt)
- return self._parse_confidence(response.content)
- except Exception:
- logger.exception("Quick confidence check failed")
- return {
- "positive_confidence": 0.5,
- "negative_confidence": 0.3,
- "reasoning": "fallback",
- }
-
- def should_reject_early(self, confidence_result):
- """Determine if candidate should be rejected early"""
- negative = confidence_result.get("negative_confidence", 0.3)
-
- # Only reject if we have strong negative evidence (not just lack of positive evidence)
- if negative > 0.85:
- return (
- True,
- f"High negative confidence ({negative:.2f})",
- )
-
- return False, None
-
- def should_continue_search(self, all_candidates, high_confidence_count):
- """Determine if we should continue searching"""
- # Stop if we have enough high-confidence candidates
- if high_confidence_count >= 5:
- return False, "Found sufficient high-confidence candidates"
-
- # Stop if we have many candidates but low quality
- if len(all_candidates) > 50 and high_confidence_count == 0:
- return False, "Too many low-quality candidates"
-
- return True, None
-
- def _parse_confidence(self, content):
- """Parse confidence assessment"""
- result = extract_json(content, expected_type=dict)
- if result is not None:
- return result
-
- return {
- "positive_confidence": 0.5,
- "negative_confidence": 0.3,
- "reasoning": "parse_error",
- }
-
-
-class ModularStrategy(BaseSearchStrategy):
- """
- A strategy that showcases the new modular architecture using:
- - constraint_checking module for candidate evaluation
- - candidate_exploration module for search execution
- - constraints module for constraint analysis
- - LLM-driven intelligent constraint processing
- - Early rejection and confidence-based filtering
- - Immediate candidate evaluation
- """
-
- def __init__(
- self,
- model,
- search,
- all_links_of_system=None,
- constraint_checker_type: str = "dual_confidence", # dual_confidence, strict, threshold
- exploration_strategy: str = "adaptive", # parallel, adaptive, constraint_guided, diversity
- early_rejection: bool = True, # Enable early rejection by default
- early_stopping: bool = True, # Enable early stopping by default
- llm_constraint_processing: bool = True, # Enable LLM-driven constraint processing by default
- immediate_evaluation: bool = True, # Enable immediate candidate evaluation by default
- settings_snapshot=None,
- **kwargs,
- ):
- super().__init__(
- all_links_of_system=all_links_of_system,
- settings_snapshot=settings_snapshot,
- )
-
- self.model = model
- self.search_engine = search
- self.search_engines = getattr(search, "search_engines", [])
-
- # Initialize constraint analyzer
- self.constraint_analyzer = ConstraintAnalyzer(self.model)
-
- # Initialize LLM constraint processor if enabled
- self.llm_processor = (
- LLMConstraintProcessor(self.model)
- if llm_constraint_processing
- else None
- )
-
- # Initialize early rejection manager if enabled
- self.early_rejection_manager = (
- EarlyRejectionManager(self.model) if early_rejection else None
- )
-
- # Initialize constraint checker based on type (default to dual confidence)
- self.constraint_checker = self._create_constraint_checker(
- constraint_checker_type
- )
-
- # Initialize candidate explorer based on strategy
- self.candidate_explorer = self._create_candidate_explorer(
- exploration_strategy
- )
-
- # Initialize question generator
- self.question_generator = StandardQuestionGenerator(model=self.model)
-
- # Strategy configuration
- self.constraint_checker_type = constraint_checker_type
- self.exploration_strategy = exploration_strategy
- self.early_rejection = early_rejection
- self.early_stopping = early_stopping
- self.llm_constraint_processing = llm_constraint_processing
- self.immediate_evaluation = immediate_evaluation
-
- logger.info(
- f"Initialized ModularStrategy with {constraint_checker_type} checker, {exploration_strategy} explorer, "
- f"early_rejection={early_rejection}, early_stopping={early_stopping}, "
- f"llm_processing={llm_constraint_processing}, immediate_eval={immediate_evaluation}"
- )
-
- def _create_constraint_checker(self, checker_type: str):
- """Create the appropriate constraint checker."""
- if checker_type == "dual_confidence":
- return DualConfidenceChecker(
- model=self.model,
- evidence_gatherer=self._gather_evidence_for_constraint,
- negative_threshold=0.75,
- positive_threshold=0.2,
- uncertainty_penalty=0.1,
- negative_weight=1.5,
- )
- if checker_type == "strict":
- return StrictChecker(
- model=self.model,
- evidence_gatherer=self._gather_evidence_for_constraint,
- )
- if checker_type == "threshold":
- return ThresholdChecker(
- model=self.model,
- evidence_gatherer=self._gather_evidence_for_constraint,
- acceptance_threshold=0.7,
- )
- raise ValueError(f"Unknown constraint checker type: {checker_type}")
-
- def _create_candidate_explorer(self, strategy_type: str):
- """Create the appropriate candidate explorer."""
- if strategy_type == "parallel":
- return ParallelExplorer(
- search_engine=self.search_engine,
- model=self.model,
- max_workers=4,
- )
- if strategy_type == "adaptive":
- return AdaptiveExplorer(
- search_engine=self.search_engine,
- model=self.model,
- learning_rate=0.1,
- )
- if strategy_type == "constraint_guided":
- return ConstraintGuidedExplorer(
- search_engine=self.search_engine, model=self.model
- )
- if strategy_type == "diversity":
- return DiversityExplorer(
- search_engine=self.search_engine,
- model=self.model,
- diversity_factor=0.3,
- )
- raise ValueError(f"Unknown exploration strategy: {strategy_type}")
-
- async def search(
- self,
- query: str,
- search_engines: List[str] = None,
- progress_callback=None,
- **kwargs,
- ) -> Tuple[str, Dict]:
- """
- Execute the modular search strategy.
- """
- try:
- logger.info(f"Starting enhanced modular search for: {query}")
-
- # Phase 1: Extract base constraints
- if progress_callback:
- progress_callback(
- {
- "phase": "constraint_analysis",
- "progress": 5,
- "message": "Analyzing query constraints",
- }
- )
-
- base_constraints = self.constraint_analyzer.extract_constraints(
- query
- )
- logger.info(f"Extracted {len(base_constraints)} base constraints")
-
- # Phase 2: LLM constraint processing (if enabled)
- all_search_queries = []
- if self.llm_constraint_processing and self.llm_processor:
- if progress_callback:
- progress_callback(
- {
- "phase": "llm_processing",
- "progress": 15,
- "message": "LLM processing constraints intelligently",
- }
- )
-
- logger.info("🤖 LLM CONSTRAINT PROCESSING ACTIVATED")
-
- # Pass existing base constraint queries to avoid duplication
- existing_queries = [c.description for c in base_constraints]
- logger.info("📋 BASE CONSTRAINT QUERIES:")
- for i, base_query in enumerate(existing_queries, 1):
- logger.info(f" BASE-{i:02d}: {base_query}")
-
- intelligent_combinations = (
- await self.llm_processor.generate_intelligent_combinations(
- existing_queries, query
- )
- )
-
- logger.info("🧠 LLM-GENERATED INTELLIGENT QUERIES:")
- logger.info("### START_LLM_QUERIES ###") # Grep-friendly marker
- for i, llm_query in enumerate(intelligent_combinations, 1):
- logger.info(f" LLM-{i:02d}: {llm_query}")
- logger.info("### END_LLM_QUERIES ###") # Grep-friendly marker
-
- # OPTIMIZATION: Start with original query, then use LLM-generated targeted queries
- # This ensures we search for the exact question first, then explore variations
- all_search_queries = (
- [query] + intelligent_combinations
- ) # Original query first, then LLM combinations
- logger.info(
- f"🎯 Using original query + {len(intelligent_combinations)} targeted LLM search combinations (skipping broad base constraints)"
- )
- logger.info(
- f"📊 Optimized search strategies: {len(all_search_queries)} (original + {len(intelligent_combinations)} LLM queries)"
- )
- else:
- logger.warning(
- "⚠️ LLM constraint processing is DISABLED - falling back to basic searches"
- )
- # Fallback to basic constraint searches
- all_search_queries = [c.description for c in base_constraints]
-
- # Phase 3: Enhanced candidate exploration with immediate evaluation
- if progress_callback:
- progress_callback(
- {
- "phase": "candidate_exploration",
- "progress": 25,
- "message": f"🔍 Exploring with {len(all_search_queries)} enhanced search strategies",
- }
- )
-
- all_candidates = []
- high_confidence_count = 0
- search_progress = 30
-
- # DECOUPLED APPROACH: Separate search execution from candidate evaluation
- candidate_evaluation_queue = asyncio.Queue()
- evaluation_results = []
- rejected_candidates = [] # Store rejected candidates for potential recovery
-
- # Execute searches in parallel batches with decoupled evaluation
- batch_size = 8 # Optimized for parallel execution
- logger.info(
- f"🚀 Starting enhanced exploration with {len(all_search_queries)} search queries (8 concurrent, decoupled evaluation)"
- )
-
- # Start background candidate evaluation task
- evaluation_task = asyncio.create_task(
- self._background_candidate_evaluation(
- candidate_evaluation_queue,
- base_constraints,
- evaluation_results,
- query,
- rejected_candidates,
- )
- )
-
- for i in range(0, len(all_search_queries), batch_size):
- batch = all_search_queries[i : i + batch_size]
-
- if progress_callback:
- progress_callback(
- {
- "phase": "search_batch",
- "progress": search_progress,
- "message": f"🔍 Executing search batch {i // batch_size + 1}",
- }
- )
-
- logger.info(
- f"📦 Processing batch {i // batch_size + 1}: {batch}"
- )
-
- # Execute batch searches in parallel using ThreadPoolExecutor
- batch_results = []
- with ThreadPoolExecutor(max_workers=8) as executor:
- # Submit all searches in the batch concurrently
- future_to_query = {
- executor.submit(
- thread_cleanup(
- self.candidate_explorer._execute_search
- ),
- query,
- ): query
- for query in batch
- }
-
- # Collect results as they complete
- for future in as_completed(future_to_query):
- query = future_to_query[future]
- try:
- result = future.result()
- batch_results.append(result)
- except Exception as e:
- logger.exception(
- f"❌ Parallel search failed for '{query[:30]}...'"
- )
- batch_results.append(e)
-
- # CRITICAL: Yield control to allow background evaluation task to run
- await asyncio.sleep(0)
-
- # Process batch results - QUEUE CANDIDATES FOR BACKGROUND EVALUATION
- for j, result in enumerate(batch_results):
- if isinstance(result, Exception):
- logger.exception(
- f"❌ Search failed: {batch[j]} - {result}"
- )
- continue
-
- candidates = self.candidate_explorer._extract_candidates_from_results(
- result, original_query=query
- )
-
- logger.info(
- f"🎯 Found {len(candidates)} candidates from query: '{batch[j][:50]}...'"
- )
-
- # QUEUE CANDIDATES for background evaluation (non-blocking)
- for candidate in candidates:
- await candidate_evaluation_queue.put(candidate)
-
- # Progress tracking without blocking on evaluation
- total_candidates = sum(
- len(
- self.candidate_explorer._extract_candidates_from_results(
- result, original_query=query
- )
- )
- for result in batch_results
- if not isinstance(result, Exception)
- )
-
- logger.info(
- f"📦 Batch {i // batch_size + 1}: queued {total_candidates} candidates for evaluation"
- )
-
- # CRITICAL: Yield control after each batch to allow background evaluation
- await asyncio.sleep(
- 0.1
- ) # Small delay to let background task process
-
- search_progress = min(search_progress + 10, 75)
-
- # Signal completion to background evaluation and wait for final results
- await candidate_evaluation_queue.put(
- None
- ) # Sentinel to signal completion
-
- # Wait for background evaluation to complete
- try:
- await asyncio.wait_for(
- evaluation_task, timeout=30.0
- ) # 30s timeout
- except asyncio.TimeoutError:
- logger.warning(
- "⚠️ Background evaluation timed out, using partial results"
- )
- evaluation_task.cancel()
-
- # Collect all evaluated candidates
- all_candidates = [
- result for result in evaluation_results if result is not None
- ]
-
- logger.info(
- f"🏁 Search completed: {len(all_candidates)} total candidates, {high_confidence_count} high-confidence"
- )
-
- # Phase 4: Final candidate evaluation (if immediate evaluation was disabled)
- evaluated_candidates = all_candidates
- if not self.immediate_evaluation:
- if progress_callback:
- progress_callback(
- {
- "phase": "candidate_evaluation",
- "progress": 80,
- "message": f"🔍 Evaluating {len(all_candidates)} candidates",
- }
- )
-
- evaluated_candidates = []
- for candidate in all_candidates[:20]: # Limit to top 20
- try:
- result = self.constraint_checker.check_candidate(
- candidate, base_constraints
- )
- candidate.evaluation_results = result.detailed_results
- candidate.score = result.total_score
- candidate.should_reject = result.should_reject
-
- if not result.should_reject:
- evaluated_candidates.append(candidate)
-
- except Exception:
- logger.exception(
- f"💥 Error evaluating candidate {candidate.name}"
- )
- continue
-
- # Phase 5: Select best candidate
- if progress_callback:
- progress_callback(
- {
- "phase": "result_selection",
- "progress": 90,
- "message": "🏆 Selecting best result",
- }
- )
-
- if not evaluated_candidates:
- # Check all candidates including rejected ones
- all_scored_candidates = []
-
- # Add all candidates with scores
- for c in all_candidates:
- if hasattr(c, "score") and c.score > 0:
- all_scored_candidates.append(c)
-
- # Add rejected candidates with scores
- for c in rejected_candidates:
- if hasattr(c, "score") and c.score > 0:
- all_scored_candidates.append(c)
-
- if all_scored_candidates:
- # Sort by score
- all_scored_candidates.sort(
- key=lambda x: x.score, reverse=True
- )
- best_candidate = all_scored_candidates[0]
-
- # Accept if score is above minimum threshold (20%)
- if best_candidate.score >= 0.20:
- logger.info(
- f"🎯 Accepting best available candidate (recovered from rejected): {best_candidate.name} with score {best_candidate.score:.2%}"
- )
- evaluated_candidates = [best_candidate]
- else:
- logger.warning(
- f"❌ Best candidate {best_candidate.name} has too low score: {best_candidate.score:.2%}"
- )
-
- if not evaluated_candidates:
- logger.warning(
- "❌ No valid candidates found after evaluation"
- )
- return "No valid candidates found after evaluation", {
- "strategy": "enhanced_modular",
- "constraint_checker": self.constraint_checker_type,
- "exploration_strategy": self.exploration_strategy,
- "early_rejection": self.early_rejection,
- "llm_processing": self.llm_constraint_processing,
- "total_searches": len(all_search_queries),
- "candidates_found": len(all_candidates),
- "candidates_valid": 0,
- "high_confidence_count": high_confidence_count,
- }
-
- # Sort by score and select best
- evaluated_candidates.sort(
- key=lambda x: getattr(x, "score", 0), reverse=True
- )
- best_candidate = evaluated_candidates[0]
-
- logger.info(
- f"🏆 Best candidate: {best_candidate.name} with score {getattr(best_candidate, 'score', 0):.2%}"
- )
-
- # Phase 6: Generate final answer
- if progress_callback:
- progress_callback(
- {
- "phase": "final_answer",
- "progress": 95,
- "message": "📝 Generating final answer",
- }
- )
-
- answer = await self._generate_final_answer(
- query, best_candidate, base_constraints
- )
-
- # Search Query Analysis Summary for easy analysis
- logger.info("=" * 80)
- logger.info("🔍 SEARCH QUERY ANALYSIS SUMMARY")
- logger.info("=" * 80)
- logger.info(
- f"📊 TOTAL QUERIES GENERATED: {len(all_search_queries)}"
- )
- logger.info(
- f"📋 BASE CONSTRAINT QUERIES: {len(existing_queries) if 'existing_queries' in locals() else 0}"
- )
- logger.info(
- f"🧠 LLM INTELLIGENT QUERIES: {len(intelligent_combinations) if 'intelligent_combinations' in locals() else 0}"
- )
-
- if (
- "intelligent_combinations" in locals()
- and intelligent_combinations
- ):
- logger.info("\n🎯 SAMPLE LLM-GENERATED QUERIES (first 10):")
- for i, query in enumerate(intelligent_combinations[:10], 1):
- logger.info(f" SAMPLE-{i:02d}: {query}")
-
- logger.info("=" * 80)
-
- metadata = {
- "strategy": "enhanced_modular",
- "constraint_checker": self.constraint_checker_type,
- "exploration_strategy": self.exploration_strategy,
- "early_rejection_enabled": self.early_rejection,
- "early_stopping_enabled": self.early_stopping,
- "llm_processing_enabled": self.llm_constraint_processing,
- "immediate_evaluation_enabled": self.immediate_evaluation,
- "total_searches_generated": len(all_search_queries),
- "candidates_found": len(all_candidates),
- "candidates_evaluated": len(evaluated_candidates),
- "high_confidence_count": high_confidence_count,
- "best_candidate": best_candidate.name,
- "best_score": getattr(best_candidate, "score", 0),
- }
-
- return answer, metadata
-
- except Exception:
- logger.exception("💥 Error in enhanced modular search")
- return "Search failed", {"error": "Search failed"}
-
- async def _generate_final_answer(
- self, query: str, best_candidate, constraints
- ) -> str:
- """Generate the final answer using the best candidate."""
-
- constraint_info = "\n".join(
- [f"- {c.description} (weight: {c.weight})" for c in constraints]
- )
-
- evaluation_info = ""
- if hasattr(best_candidate, "evaluation_results"):
- evaluation_info = "\n".join(
- [
- f"- {result.get('constraint', 'Unknown')}: {result.get('score', 0):.0%}"
- for result in best_candidate.evaluation_results
- ]
- )
-
- prompt = f"""Based on the search results, provide a comprehensive answer to: {query}
-
-Best candidate found: {best_candidate.name}
-Score: {best_candidate.score:.0%}
-
-Constraints analyzed:
-{constraint_info}
-
-Constraint evaluation results:
-{evaluation_info}
-
-Evidence summary: {getattr(best_candidate, "summary", "No summary available")}
-
-Provide a clear, factual answer that addresses the original question and explains how the candidate satisfies the constraints."""
-
- response = await self.model.ainvoke(prompt)
- return response.content
-
- def _gather_evidence_for_constraint(self, candidate, constraint):
- """Gather evidence for a constraint using actual search with caching."""
- # Check cache first
- cache = get_search_cache()
- cache_key = normalize_entity_query(candidate.name, constraint.value)
-
- cached_results = cache.get(cache_key, "modular_strategy")
- if cached_results is not None:
- logger.debug(
- f"Using cached evidence for {candidate.name} - {constraint.value[:30]}..."
- )
- return cached_results
-
- try:
- # Build search query intelligently based on constraint type
- query_parts = []
-
- # Add candidate name
- query_parts.append(f'"{candidate.name}"')
-
- # Parse constraint value for key terms
- constraint_value = constraint.value
-
- # Remove common prefixes
- prefixes_to_remove = [
- "The individual is associated with",
- "The answer must be",
- "The character must be",
- "The entity must be",
- "Must be",
- "Should be",
- "Is",
- ]
-
- for prefix in prefixes_to_remove:
- if constraint_value.startswith(prefix):
- constraint_value = constraint_value[len(prefix) :].strip()
- break
-
- # Handle different constraint types
- if constraint.type.value == "TEMPORAL":
- # For temporal constraints, extract years/dates and search specifically
- import re
-
- years = re.findall(r"\b(19\d{2}|20\d{2})\b", constraint_value)
- decades = re.findall(
- r"\b(19\d{2}s|20\d{2}s)\b", constraint_value
- )
-
- if years:
- query_parts.extend(years)
- elif decades:
- query_parts.extend(decades)
- else:
- query_parts.append(constraint_value)
-
- elif constraint.type.value == "PROPERTY":
- # For properties, focus on the specific characteristic
- query_parts.append(constraint_value)
-
- elif constraint.type.value == "STATISTIC":
- # For statistics, include numbers and comparisons
- query_parts.append(constraint_value)
-
- else:
- # Default: use the constraint value as-is
- query_parts.append(constraint_value)
-
- # Build final query
- query = " ".join(query_parts)
- logger.debug(f"Evidence search query: {query}")
-
- # Execute search using the appropriate method
- results = None
-
- # Try different search methods based on what's available
- if hasattr(self.search_engine, "run"):
- results = self.search_engine.run(query)
- elif hasattr(self.search_engine, "search"):
- results = self.search_engine.search(query)
- elif callable(self.search_engine):
- results = self.search_engine(query)
- else:
- logger.error(
- f"Search engine has no callable method: {type(self.search_engine)}"
- )
- return []
-
- # Process results
- evidence = []
-
- # Handle different result formats
- if results is None:
- logger.warning("Search returned None")
- return []
-
- if isinstance(results, list):
- result_list = results
- elif isinstance(results, dict):
- # Try common keys for results
- result_list = (
- results.get("results")
- or results.get("items")
- or results.get("data")
- or []
- )
- else:
- logger.warning(f"Unknown search result type: {type(results)}")
- result_list = []
-
- # Extract top evidence (limit to 5 for better quality)
- for i, result in enumerate(result_list[:5]):
- if isinstance(result, dict):
- # Extract text content
- text = (
- result.get("snippet")
- or result.get("content")
- or result.get("description")
- or result.get("text")
- or ""
- )
-
- # Extract source information
- source = (
- result.get("url")
- or result.get("link")
- or result.get("source")
- or f"search_result_{i + 1}"
- )
-
- # Extract title
- title = result.get("title", "")
-
- # Calculate confidence based on result position and content
- base_confidence = 0.8 - (i * 0.1) # Decay by position
-
- # Boost confidence if key terms are present
- if candidate.name.lower() in text.lower():
- base_confidence += 0.1
- if any(
- term.lower() in text.lower()
- for term in constraint_value.split()
- ):
- base_confidence += 0.1
-
- confidence = min(base_confidence, 0.95)
-
- evidence.append(
- {
- "text": text[:500], # Limit text length
- "source": source,
- "confidence": confidence,
- "title": title,
- "full_text": text, # Keep full text for detailed analysis
- }
- )
- else:
- # Handle string results
- evidence.append(
- {
- "text": str(result)[:500],
- "source": f"search_result_{i + 1}",
- "confidence": 0.6,
- "title": "",
- }
- )
-
- logger.debug(
- f"Gathered {len(evidence)} evidence items for {candidate.name} - {constraint.value[:50]}..."
- )
-
- # Cache the results for future use
- cache.put(
- cache_key, evidence, "modular_strategy", ttl=1800
- ) # 30 minutes TTL
-
- return evidence
-
- except Exception:
- logger.exception("Error gathering evidence")
- # Return empty list instead of mock evidence
- return []
-
- async def _background_candidate_evaluation(
- self,
- queue,
- constraints,
- results,
- original_query=None,
- rejected_candidates=None,
- ):
- """Background task to evaluate candidates without blocking search progress."""
- logger.info("🔄 Started background candidate evaluation")
-
- # Use provided rejected_candidates list or create new one
- if rejected_candidates is None:
- rejected_candidates = []
-
- while True:
- try:
- # Get candidate from queue
- candidate = await queue.get()
-
- # Check for completion sentinel
- if candidate is None:
- logger.info("🏁 Background evaluation completed")
- break
-
- # Evaluate candidate with LLM pre-screening
- try:
- # Always do full constraint evaluation to get scores
- result = self.constraint_checker.check_candidate(
- candidate, constraints, original_query=original_query
- )
- candidate.evaluation_results = result.detailed_results
- candidate.score = result.total_score
- candidate.should_reject = result.should_reject
-
- # Now check early rejection AFTER we have a score
- if self.early_rejection_manager:
- confidence = await self.early_rejection_manager.quick_confidence_check(
- candidate, constraints
- )
-
- should_reject, reason = (
- self.early_rejection_manager.should_reject_early(
- confidence
- )
- )
- if (
- should_reject and candidate.score < 0.5
- ): # Only early reject if score is also low
- logger.debug(
- f"⚡ Early rejected {candidate.name}: {reason} (score: {candidate.score:.2%})"
- )
- # Store the candidate anyway for potential best candidate recovery
- rejected_candidates.append(candidate)
- continue
-
- if not result.should_reject:
- results.append(candidate)
- logger.info(
- f"✅ Accepted: {candidate.name} (score: {result.total_score:.2%})"
- )
-
- # Check for excellent candidates
- if result.total_score > 0.9:
- logger.info(
- f"🏆 EXCELLENT: {candidate.name} with {result.total_score:.1%} score"
- )
- else:
- # Store rejected candidates with scores for potential recovery
- rejected_candidates.append(candidate)
- logger.debug(
- f"❌ Rejected: {candidate.name} (score: {candidate.score:.2%})"
- )
-
- except Exception:
- logger.exception(f"💥 Error evaluating {candidate.name}")
-
- except Exception:
- logger.exception("💥 Background evaluation error")
-
- def analyze_topic(self, query: str) -> Dict:
- """
- Analyze a topic using the modular strategy.
-
- This is the main entry point that implements the BaseSearchStrategy interface.
- """
- try:
- # Run the search asynchronously
- import asyncio
-
- # Run async search — detect whether we're inside an event loop
- try:
- asyncio.get_running_loop()
- # Inside a running loop — run in a thread to avoid nesting
- with ThreadPoolExecutor() as executor:
- future = executor.submit(
- thread_cleanup(lambda: asyncio.run(self.search(query)))
- )
- answer, metadata = future.result()
- except RuntimeError:
- # No running event loop — safe to use asyncio.run() directly
- answer, metadata = asyncio.run(self.search(query))
-
- return {
- "findings": [{"content": answer}],
- "iterations": 1,
- "final_answer": answer,
- "current_knowledge": answer,
- "metadata": metadata,
- "links": getattr(self, "all_links_of_system", []),
- "questions_by_iteration": getattr(
- self, "questions_by_iteration", []
- ),
- }
-
- except Exception as e:
- logger.exception("Error in analyze_topic")
- return {
- "findings": [],
- "iterations": 0,
- "final_answer": f"Analysis failed: {e!s}",
- "metadata": {"error": str(e)},
- "links": [],
- "questions_by_iteration": [],
- }
diff --git a/src/local_deep_research/advanced_search_system/strategies/parallel_constrained_strategy.py b/src/local_deep_research/advanced_search_system/strategies/parallel_constrained_strategy.py
deleted file mode 100644
index 61013adce5..0000000000
--- a/src/local_deep_research/advanced_search_system/strategies/parallel_constrained_strategy.py
+++ /dev/null
@@ -1,479 +0,0 @@
-"""
-Parallel constrained search strategy with progressive constraint relaxation.
-
-Key improvements:
-1. Combines multiple constraints in initial searches
-2. Runs searches in parallel for efficiency
-3. Progressively loosens constraints if needed
-4. Compact design to minimize context usage
-"""
-
-import concurrent.futures
-from dataclasses import dataclass
-from typing import List
-
-from loguru import logger
-
-from ...database.thread_local_session import thread_cleanup
-from ..candidates.base_candidate import Candidate
-from ..constraints.base_constraint import Constraint, ConstraintType
-from .constrained_search_strategy import ConstrainedSearchStrategy
-
-
-@dataclass
-class SearchCombination:
- """Represents a combination of constraints for searching."""
-
- constraints: List[Constraint]
- query: str
- priority: int
-
- def __hash__(self):
- return hash(self.query)
-
-
-class ParallelConstrainedStrategy(ConstrainedSearchStrategy):
- """
- Enhanced constrained strategy with parallel search and smart constraint combination.
- """
-
- def __init__(
- self,
- *args,
- parallel_workers: int = 100,
- min_results_threshold: int = 10,
- **kwargs,
- ):
- super().__init__(*args, **kwargs)
- self.parallel_workers = parallel_workers
- self.min_results_threshold = min_results_threshold
-
- def _classify_constraints(self):
- """Classify constraints into hard (must satisfy) and soft (scoring) categories."""
- self.hard_constraints = []
- self.soft_constraints = []
-
- for constraint in self.constraint_ranking:
- # Temporal and statistic constraints are hard
- if constraint.type in [
- ConstraintType.TEMPORAL,
- ConstraintType.STATISTIC,
- ]:
- self.hard_constraints.append(constraint)
- else:
- self.soft_constraints.append(constraint)
-
- logger.info(
- f"Classified {len(self.hard_constraints)} hard constraints and {len(self.soft_constraints)} soft constraints"
- )
-
- def _progressive_constraint_search(self):
- """Override parent method with parallel, combined constraint search."""
- current_candidates = []
- search_iterations = 0
- max_search_iterations = 3
-
- # Check if constraint_ranking is available
- if (
- not hasattr(self, "constraint_ranking")
- or not self.constraint_ranking
- ):
- logger.error(
- "No constraint ranking available - calling parent method"
- )
- return super()._progressive_constraint_search()
-
- # Detect what type of entity we're looking for
- self.entity_type = self._detect_entity_type()
- logger.info(f"Detected entity type: {self.entity_type}")
-
- logger.info(
- f"Starting parallel constraint search with {len(self.constraint_ranking)} constraints"
- )
- logger.info(
- f"Constraint ranking: {[c.value for c in self.constraint_ranking[:5]]}"
- )
-
- while search_iterations < max_search_iterations:
- search_iterations += 1
-
- # Phase 1: Combined constraints (strict)
- if search_iterations == 1:
- combinations = self._create_strict_combinations()
- strictness = "strict"
- # Phase 2: Relaxed combinations
- elif search_iterations == 2:
- combinations = self._create_relaxed_combinations()
- strictness = "relaxed"
- # Phase 3: Individual constraints (fallback)
- else:
- combinations = self._create_individual_combinations()
- strictness = "individual"
-
- logger.info(
- f"Iteration {search_iterations}: {strictness} mode with {len(combinations)} combinations"
- )
-
- # Log the actual combinations
- for i, combo in enumerate(combinations):
- logger.info(
- f" Combination {i + 1}: query='{combo.query[:60]}...', constraints={len(combo.constraints)}"
- )
-
- if self.progress_callback:
- self.progress_callback(
- f"Search iteration {search_iterations}: {strictness} mode ({len(combinations)} combinations)",
- 15 + (search_iterations * 25),
- {
- "phase": "parallel_search",
- "iteration": search_iterations,
- "combinations": len(combinations),
- "mode": strictness,
- },
- )
-
- # Run searches in parallel
- new_candidates = self._parallel_search(combinations)
- current_candidates.extend(new_candidates)
-
- # Check if we have enough results
- unique_candidates = self._deduplicate_candidates(current_candidates)
-
- if len(unique_candidates) >= self.min_results_threshold:
- if self.progress_callback:
- self.progress_callback(
- f"Found {len(unique_candidates)} candidates - stopping search",
- 90,
- {
- "phase": "search_complete",
- "candidates": len(unique_candidates),
- },
- )
- break
-
- if self.progress_callback:
- self.progress_callback(
- f"Found {len(unique_candidates)} candidates - continuing search",
- None,
- {
- "phase": "search_continue",
- "candidates": len(unique_candidates),
- },
- )
-
- self.candidates = unique_candidates[: self.candidate_limit]
-
- # Add stage tracking for parent class compatibility
- self.stage_candidates = {
- 0: self.candidates, # Final results as last stage
- }
- return None
-
- def _create_strict_combinations(self) -> List[SearchCombination]:
- """Create initial strict constraint combinations."""
- combinations = []
-
- # Group constraints by type for better combination
- by_type = {}
- for c in self.constraint_ranking[:6]: # Top 6 constraints
- if c.type not in by_type:
- by_type[c.type] = []
- by_type[c.type].append(c)
-
- # Strategy 1: Combine most restrictive constraints
- if len(self.constraint_ranking) >= 2:
- top_two = self.constraint_ranking[:2]
- query = self._build_query(top_two)
- combinations.append(SearchCombination(top_two, query, 1))
-
- # Strategy 2: Combine temporal + property constraints
- temporal = [
- c
- for c in self.constraint_ranking
- if c.type in [ConstraintType.EVENT, ConstraintType.TEMPORAL]
- ]
- properties = [
- c
- for c in self.constraint_ranking
- if c.type == ConstraintType.PROPERTY
- ]
-
- if temporal and properties:
- combined = temporal[:1] + properties[:1]
- query = self._build_query(combined)
- combinations.append(SearchCombination(combined, query, 2))
-
- # Strategy 3: Combine statistic + property
- stats = [
- c
- for c in self.constraint_ranking
- if c.type == ConstraintType.STATISTIC
- ]
- if stats and properties:
- combined = stats[:1] + properties[:2]
- query = self._build_query(combined)
- combinations.append(SearchCombination(combined, query, 3))
-
- return combinations[:5] # Limit to 5 combinations
-
- def _create_relaxed_combinations(self) -> List[SearchCombination]:
- """Create relaxed constraint combinations."""
- combinations = []
-
- # Use single most restrictive constraints
- for i, constraint in enumerate(self.constraint_ranking[:3]):
- query = self._build_query([constraint])
- combinations.append(SearchCombination([constraint], query, i + 10))
-
- # Combine weaker constraints
- if len(self.constraint_ranking) > 3:
- weaker = self.constraint_ranking[3:6]
- query = self._build_query(weaker)
- combinations.append(SearchCombination(weaker, query, 20))
-
- return combinations
-
- def _create_individual_combinations(self) -> List[SearchCombination]:
- """Create individual constraint searches as fallback."""
- combinations = []
-
- for i, constraint in enumerate(self.constraint_ranking[:5]):
- # Create multiple query variations
- queries = self._generate_query_variations(constraint)
- for j, query in enumerate(
- queries[:2]
- ): # 2 variations per constraint
- combinations.append(
- SearchCombination([constraint], query, i * 10 + j + 30)
- )
-
- return combinations
-
- def _build_query(self, constraints: List[Constraint]) -> str:
- """Build an optimized query from constraints."""
- terms = []
-
- # Use entity type to add context
- entity_type = getattr(self, "entity_type", None)
- if entity_type and entity_type != "unknown entity":
- # Add entity type as a search term
- terms.append(f'"{entity_type}"')
-
- for c in constraints:
- # Add quotes for multi-word values
- value = c.value
- if " " in value and not value.startswith('"'):
- value = f'"{value}"'
- terms.append(value)
-
- # Join with AND for strict matching
- return " AND ".join(terms)
-
- def _generate_query_variations(self, constraint: Constraint) -> List[str]:
- """Generate query variations for a single constraint."""
- base = constraint.value
- variations = [base]
-
- # Add type-specific variations
- if constraint.type == ConstraintType.STATISTIC:
- variations.extend(
- [f"list {base}", f"complete {base}", f"all {base}"]
- )
- elif constraint.type == ConstraintType.PROPERTY:
- variations.extend(
- [f"with {base}", f"featuring {base}", f"known for {base}"]
- )
-
- return variations[:3] # Limit variations
-
- def _parallel_search(
- self, combinations: List[SearchCombination]
- ) -> List[Candidate]:
- """Execute searches in parallel."""
- all_candidates = []
-
- with concurrent.futures.ThreadPoolExecutor(
- max_workers=self.parallel_workers
- ) as executor:
- # Submit all searches
- future_to_combo = {
- executor.submit(self._execute_combination_search, combo): combo
- for combo in combinations
- }
-
- # Process results as they complete
- for i, future in enumerate(
- concurrent.futures.as_completed(future_to_combo)
- ):
- combo = future_to_combo[future]
- try:
- candidates = future.result()
- all_candidates.extend(candidates)
-
- if self.progress_callback:
- self.progress_callback(
- f"Completed search {i + 1}/{len(combinations)}: {len(candidates)} results",
- None,
- {
- "phase": "parallel_result",
- "query": combo.query[:50],
- "candidates": len(candidates),
- "total_so_far": len(all_candidates),
- },
- )
- except Exception:
- logger.exception(f"Search failed for {combo.query}")
-
- return all_candidates
-
- @thread_cleanup
- def _execute_combination_search(
- self, combination: SearchCombination
- ) -> List[Candidate]:
- """Execute a single combination search."""
- try:
- results = self._execute_search(combination.query)
-
- # Extract candidates using LLM
- candidates = []
- content = results.get("current_knowledge", "")
-
- logger.info(
- f"Search '{combination.query[:50]}...' returned {len(content)} chars of content"
- )
-
- if content and len(content) > 50:
- # Always use LLM extraction for accuracy
- extracted = self._extract_relevant_candidates(
- {"current_knowledge": content},
- combination.constraints[0]
- if combination.constraints
- else None,
- )
- candidates.extend(extracted)
-
- logger.info(
- f"Search '{combination.query[:30]}' found {len(candidates)} candidates"
- )
- return candidates
-
- except Exception:
- logger.exception("Error in combination search")
- return []
-
- def _quick_extract_candidates(
- self, content: str, constraints: List[Constraint]
- ) -> List[Candidate]:
- """Extract candidates using LLM with entity type awareness."""
- # Use the detected entity type if available
- entity_type = getattr(self, "entity_type", "entity")
-
- extraction_prompt = f"""
-From the following search result, extract {entity_type} names that might match the given constraints.
-
-Search result:
-{content}
-
-Constraints to consider:
-{chr(10).join(f"- {c.value}" for c in constraints)}
-
-Important:
-- Extract ONLY {entity_type} names
-- Do NOT include other types of entities
-- Focus on entities that could potentially match the constraints
-
-Return the {entity_type} names, one per line.
-"""
-
- try:
- response = self.model.invoke(extraction_prompt).content
- candidates = []
- for line in response.split("\n"):
- name = line.strip()
- if name and len(name) > 2:
- candidates.append(Candidate(name=name))
- return candidates[:15]
- except Exception:
- logger.exception("Entity extraction failed")
- return []
-
- def _validate_hard_constraints(
- self, candidates: List[Candidate]
- ) -> List[Candidate]:
- """Filter candidates that don't meet hard constraints."""
- if not self.hard_constraints or not candidates:
- return candidates
-
- entity_type = getattr(self, "entity_type", "entity")
-
- validation_prompt = f"""
-Validate {entity_type} candidates against hard constraints.
-
-Hard constraints that MUST be satisfied:
-{chr(10).join(f"- {c.value}" for c in self.hard_constraints)}
-
-{entity_type} candidates to evaluate:
-{chr(10).join(f"- {c.name}" for c in candidates[:20])}
-
-Return ONLY the {entity_type} names that satisfy ALL hard constraints, one per line.
-Reject any candidates that:
-1. Are not actually a {entity_type}
-2. Do not satisfy ALL the hard constraints listed above
-
-Be strict - if there's doubt about a constraint being satisfied, reject the candidate."""
-
- try:
- response = self.model.invoke(validation_prompt).content
- valid_names = [
- line.strip() for line in response.split("\n") if line.strip()
- ]
-
- # Keep only candidates that passed validation
- filtered = [c for c in candidates if c.name in valid_names]
-
- logger.info(
- f"Hard constraint validation: {len(candidates)} -> {len(filtered)} candidates"
- )
- return filtered
-
- except Exception:
- logger.exception("Hard constraint validation failed")
- # Don't return unvalidated candidates for hard constraints
- return []
-
- def _detect_entity_type(self) -> str:
- """Use LLM to detect what type of entity we're searching for."""
- # Build context from constraints
- constraint_text = "\n".join(
- [f"- {c.value}" for c in self.constraint_ranking]
- )
-
- prompt = f"""
-Analyze these search constraints and determine what type of entity is being searched for:
-
-Constraints:
-{constraint_text}
-
-What is the primary entity type being searched for? Be specific.
-
-Examples of entity types (but you can choose any appropriate type):
-- fictional character
-- TV show
-- movie
-- actor/actress
-- historical figure
-- company
-- product
-- location
-- event
-
-Respond with just the entity type.
-"""
-
- try:
- entity_type = self.model.invoke(prompt).content.strip()
- logger.info(f"LLM determined entity type: {entity_type}")
- return entity_type
- except Exception:
- logger.exception("Failed to detect entity type")
- return "unknown entity"
diff --git a/src/local_deep_research/advanced_search_system/strategies/parallel_search_strategy.py b/src/local_deep_research/advanced_search_system/strategies/parallel_search_strategy.py
deleted file mode 100644
index 125f93c2de..0000000000
--- a/src/local_deep_research/advanced_search_system/strategies/parallel_search_strategy.py
+++ /dev/null
@@ -1,474 +0,0 @@
-"""
-Parallel search strategy implementation for maximum search speed.
-"""
-
-import concurrent.futures
-from typing import Dict
-
-from loguru import logger
-
-from ...citation_handler import CitationHandler
-
-# Model and search should be provided by AdvancedSearchSystem
-from ...database.thread_local_session import thread_cleanup
-from ...utilities.search_utilities import extract_links_from_search_results
-from ..filters.cross_engine_filter import CrossEngineFilter
-from ..findings.repository import FindingsRepository
-from ..questions.standard_question import StandardQuestionGenerator
-from .base_strategy import BaseSearchStrategy
-
-
-class ParallelSearchStrategy(BaseSearchStrategy):
- """
- Parallel search strategy that generates questions and runs all searches
- simultaneously for maximum speed.
- """
-
- def __init__(
- self,
- search,
- model,
- citation_handler=None,
- include_text_content: bool = True,
- use_cross_engine_filter: bool = True,
- filter_reorder: bool = True,
- filter_reindex: bool = True,
- cross_engine_max_results: int = None,
- all_links_of_system=None,
- settings_snapshot=None,
- ):
- """Initialize with optional dependency injection for testing.
-
- Args:
- search: Optional search engine instance
- model: Optional LLM model instance
- citation_handler: Optional citation handler instance
- include_text_content: If False, only includes metadata and links in search results
- use_cross_engine_filter: If True, filter search results across engines
- filter_reorder: Whether to reorder results by relevance
- filter_reindex: Whether to update result indices after filtering
- cross_engine_max_results: Maximum number of results to keep after cross-engine filtering
- all_links_of_system: Optional list of links to initialize with
- settings_snapshot: Settings snapshot for thread context
- """
- super().__init__(
- all_links_of_system=all_links_of_system,
- settings_snapshot=settings_snapshot,
- )
- self.search = search
- self.model = model
- self.progress_callback = None
- # Note: questions_by_iteration is already initialized by parent class
- self.include_text_content = include_text_content
- self.use_cross_engine_filter = use_cross_engine_filter
- self.filter_reorder = filter_reorder
- self.filter_reindex = filter_reindex
-
- # Initialize the cross-engine filter
- self.cross_engine_filter = CrossEngineFilter(
- model=self.model,
- max_results=cross_engine_max_results,
- default_reorder=filter_reorder,
- default_reindex=filter_reindex,
- settings_snapshot=settings_snapshot,
- )
-
- # Set include_full_content on the search engine if it supports it
- if hasattr(self.search, "include_full_content"):
- self.search.include_full_content = include_text_content
-
- # Use provided citation_handler or create one
- self.citation_handler = citation_handler or CitationHandler(
- self.model, settings_snapshot=settings_snapshot
- )
-
- # Initialize components
- self.question_generator = StandardQuestionGenerator(self.model)
- self.findings_repository = FindingsRepository(self.model)
-
- def analyze_topic(self, query: str) -> Dict:
- """
- Analyze a topic using parallel search, supporting multiple iterations.
-
- Args:
- query: The research query to analyze
- """
- logger.info(f"Starting parallel research on topic: {query}")
-
- findings = []
- all_search_results = []
- current_knowledge = ""
-
- # Track all search results across iterations
- # Note: all_links_of_system and questions_by_iteration are already initialized
-
- self._update_progress(
- "Initializing parallel research",
- 5,
- {
- "phase": "init",
- "strategy": "parallel",
- "include_text_content": self.include_text_content,
- },
- )
-
- # Check search engine
- if not self._validate_search_engine():
- return {
- "findings": [],
- "iterations": 0,
- "questions_by_iteration": {},
- "formatted_findings": "Error: Unable to conduct research without a search engine.",
- "current_knowledge": "",
- "error": "No search engine available",
- }
-
- # Determine number of iterations to run
- iterations_to_run = self.get_setting("search.iterations")
- logger.debug("Selected amount of iterations: " + str(iterations_to_run))
- iterations_to_run = int(iterations_to_run)
- try:
- # Run each iteration
- for iteration in range(1, iterations_to_run + 1):
- iteration_progress_base = 5 + (iteration - 1) * (
- 70 / iterations_to_run
- )
-
- self._update_progress(
- f"Starting iteration {iteration}/{iterations_to_run}",
- iteration_progress_base,
- {"phase": f"iteration_{iteration}", "iteration": iteration},
- )
-
- # Step 1: Generate questions
- self._update_progress(
- f"Generating search questions for iteration {iteration}",
- iteration_progress_base + 5,
- {"phase": "question_generation", "iteration": iteration},
- )
-
- # For first iteration, generate initial questions
- # For subsequent iterations, generate follow-up questions
- logger.info("Starting to generate questions")
- if iteration == 1:
- # Generate additional questions (plus the main query)
- if iterations_to_run > 1:
- context = f"""Iteration: {1} of {iterations_to_run}"""
- else:
- context = ""
- questions_per_iter = self.get_setting(
- "search.questions_per_iteration"
- )
- questions = self.question_generator.generate_questions(
- current_knowledge=context,
- query=query,
- questions_per_iteration=int(questions_per_iter)
- if questions_per_iter is not None
- else 3,
- questions_by_iteration=self.questions_by_iteration,
- )
-
- # Add the original query as the first question
- all_questions = [query] + questions
-
- # Store in questions_by_iteration
- self.questions_by_iteration[iteration] = questions
- logger.info(
- f"Generated questions for iteration {iteration}: {questions}"
- )
- else:
- # Get past questions from all previous iterations
- past_questions = []
- for prev_iter in range(1, iteration):
- if prev_iter in self.questions_by_iteration:
- past_questions.extend(
- self.questions_by_iteration[prev_iter]
- )
-
- # Generate follow-up questions based on accumulated knowledge if iterations > 2
- use_knowledge = iterations_to_run > 2
- knowledge_for_questions = (
- current_knowledge if use_knowledge else ""
- )
- context = f"""Current Knowledge: {knowledge_for_questions}
- Iteration: {iteration} of {iterations_to_run}"""
-
- # Generate questions
- questions_per_iter = self.get_setting(
- "search.questions_per_iteration"
- )
- questions = self.question_generator.generate_questions(
- current_knowledge=context,
- query=query,
- questions_per_iteration=int(questions_per_iter)
- if questions_per_iter is not None
- else 3,
- questions_by_iteration=self.questions_by_iteration,
- )
-
- # Use only the new questions for this iteration's searches
- all_questions = questions
-
- # Store in questions_by_iteration
- self.questions_by_iteration[iteration] = questions
- logger.info(
- f"Generated questions for iteration {iteration}: {questions}"
- )
-
- # Skip if no questions (all_questions includes original query in iteration 1)
- if not all_questions:
- logger.warning(
- f"No questions generated for iteration {iteration}, skipping search phase"
- )
- continue
-
- # Step 2: Run all searches in parallel for this iteration
- self._update_progress(
- f"Running parallel searches for iteration {iteration}",
- iteration_progress_base + 10,
- {"phase": "parallel_search", "iteration": iteration},
- )
-
- # Function for thread pool
- @thread_cleanup
- def search_question(q):
- try:
- result = self.search.run(q)
- return {"question": q, "results": result or []}
- except Exception:
- logger.exception(f"Error searching for '{q}'")
- return {
- "question": q,
- "results": [],
- "error": "Search failed",
- }
-
- # Run searches in parallel
- with concurrent.futures.ThreadPoolExecutor(
- max_workers=len(all_questions)
- ) as executor:
- futures = [
- executor.submit(search_question, q)
- for q in all_questions
- ]
- iteration_search_dict = {}
- iteration_search_results = []
-
- # Process results as they complete
- for i, future in enumerate(
- concurrent.futures.as_completed(futures)
- ):
- result_dict = future.result()
- question = result_dict["question"]
- search_results = result_dict["results"]
- iteration_search_dict[question] = search_results
-
- self._update_progress(
- f"Completed search {i + 1} of {len(all_questions)}: {question[:500]}",
- iteration_progress_base
- + 10
- + ((i + 1) / len(all_questions) * 30),
- {
- "phase": "search_complete",
- "iteration": iteration,
- "result_count": len(search_results),
- "question": question,
- },
- )
-
- # Collect all search results for this iteration
- iteration_search_results.extend(search_results)
-
- # Step 3: Filter and analyze results for this iteration
- self._update_progress(
- f"Analyzing results for iteration {iteration}",
- iteration_progress_base + 45,
- {"phase": "iteration_analysis", "iteration": iteration},
- )
-
- # Apply cross-engine filtering if enabled
- if self.use_cross_engine_filter:
- self._update_progress(
- f"Filtering search results for iteration {iteration}",
- iteration_progress_base + 45,
- {
- "phase": "cross_engine_filtering",
- "iteration": iteration,
- },
- )
-
- # Get the current link count (for indexing)
- existing_link_count = len(self.all_links_of_system)
-
- # Filter the search results
- filtered_search_results = self.cross_engine_filter.filter_results(
- iteration_search_results,
- query,
- reorder=self.filter_reorder,
- reindex=self.filter_reindex,
- start_index=existing_link_count, # Start indexing after existing links
- )
-
- links = extract_links_from_search_results(
- filtered_search_results
- )
- self.all_links_of_system.extend(links)
-
- self._update_progress(
- f"Filtered from {len(iteration_search_results)} to {len(filtered_search_results)} results",
- iteration_progress_base + 50,
- {
- "phase": "filtering_complete",
- "iteration": iteration,
- "links_count": len(self.all_links_of_system),
- },
- )
-
- # Use filtered results for analysis
- iteration_search_results = filtered_search_results
- else:
- # Just extract links without filtering
- links = extract_links_from_search_results(
- iteration_search_results
- )
- self.all_links_of_system.extend(links)
-
- # Add to all search results
- all_search_results.extend(iteration_search_results)
-
- # Create a finding for this iteration's results
- if self.include_text_content and iteration_search_results:
- # For iteration > 1 with knowledge accumulation, use follow-up analysis
- if iteration > 1 and iterations_to_run > 2:
- citation_result = (
- self.citation_handler.analyze_followup(
- query,
- iteration_search_results,
- current_knowledge,
- len(self.all_links_of_system) - len(links),
- )
- )
- else:
- # For first iteration or without knowledge accumulation, use initial analysis
- citation_result = self.citation_handler.analyze_initial(
- query, iteration_search_results
- )
-
- if citation_result:
- # Create a finding for this iteration
- iteration_content = citation_result["content"]
-
- # Update current knowledge if iterations > 2
- if iterations_to_run > 2:
- if current_knowledge:
- current_knowledge = f"{current_knowledge}\n\n## FINDINGS FROM ITERATION {iteration}:\n\n{iteration_content}"
- else:
- current_knowledge = iteration_content
-
- finding = {
- "phase": f"Iteration {iteration}",
- "content": iteration_content,
- "question": query,
- "search_results": iteration_search_results,
- "documents": citation_result.get("documents", []),
- }
- findings.append(finding)
-
- # Add documents to repository
- if "documents" in citation_result:
- self.findings_repository.add_documents(
- citation_result["documents"]
- )
-
- # Mark iteration as complete
- iteration_progress = 5 + iteration * (70 / iterations_to_run)
- self._update_progress(
- f"Completed iteration {iteration}/{iterations_to_run}",
- iteration_progress,
- {"phase": "iteration_complete", "iteration": iteration},
- )
-
- # Final synthesis after all iterations
- self._update_progress(
- "Generating final synthesis", 80, {"phase": "synthesis"}
- )
-
- # Handle final synthesis based on include_text_content flag
- if self.include_text_content:
- # Generate a final synthesis from all search results
- if iterations_to_run > 1:
- final_citation_result = (
- self.citation_handler.analyze_initial(
- query, all_search_results
- )
- )
- # Add null check for final_citation_result
- if final_citation_result:
- synthesized_content = final_citation_result["content"]
- else:
- synthesized_content = (
- "No relevant results found in final synthesis."
- )
- else:
- # For single iteration, use the content from findings
- synthesized_content = (
- findings[0]["content"]
- if findings
- else "No relevant results found."
- )
- # Add a final synthesis finding
- final_finding = {
- "phase": "Final synthesis",
- "content": synthesized_content,
- "question": query,
- "search_results": all_search_results,
- "documents": [],
- }
- findings.append(final_finding)
- else:
- # Skip LLM analysis, just format the raw search results
- synthesized_content = "LLM analysis skipped"
- final_finding = {
- "phase": "Raw search results",
- "content": "LLM analysis was skipped. Displaying raw search results with links.",
- "question": query,
- "search_results": all_search_results,
- "documents": [],
- }
- findings.append(final_finding)
-
- # Transfer questions to repository
- self.findings_repository.set_questions_by_iteration(
- self.questions_by_iteration
- )
-
- # Format findings
- formatted_findings = (
- self.findings_repository.format_findings_to_text(
- findings, synthesized_content
- )
- )
-
- except Exception as e:
- error_msg = f"Error in research process: {e!s}"
- logger.exception(error_msg)
- synthesized_content = f"Error: {e!s}"
- formatted_findings = f"Error: {e!s}"
- finding = {
- "phase": "Error",
- "content": synthesized_content,
- "question": query,
- "search_results": [],
- "documents": [],
- }
- findings.append(finding)
-
- self._update_progress("Research complete", 100, {"phase": "complete"})
-
- return {
- "findings": findings,
- "iterations": iterations_to_run,
- "questions_by_iteration": self.questions_by_iteration,
- "formatted_findings": formatted_findings,
- "current_knowledge": synthesized_content,
- }
diff --git a/src/local_deep_research/advanced_search_system/strategies/rapid_search_strategy.py b/src/local_deep_research/advanced_search_system/strategies/rapid_search_strategy.py
deleted file mode 100644
index 6462a49d42..0000000000
--- a/src/local_deep_research/advanced_search_system/strategies/rapid_search_strategy.py
+++ /dev/null
@@ -1,296 +0,0 @@
-"""
-RapidSearch strategy implementation.
-"""
-
-from typing import Dict
-
-from loguru import logger
-
-from ...citation_handler import CitationHandler
-
-# Model and search should be provided by AdvancedSearchSystem
-from ...utilities.search_utilities import extract_links_from_search_results
-from ..findings.repository import FindingsRepository
-from ..knowledge.standard_knowledge import StandardKnowledge
-from ..questions.standard_question import StandardQuestionGenerator
-from .base_strategy import BaseSearchStrategy
-
-
-class RapidSearchStrategy(BaseSearchStrategy):
- """
- Rapid search strategy that only analyzes snippets and performs
- a single synthesis step at the end, optimized for speed.
- """
-
- def __init__(
- self,
- search,
- model,
- citation_handler=None,
- all_links_of_system=None,
- settings_snapshot=None,
- ):
- """Initialize with optional dependency injection for testing."""
- super().__init__(
- all_links_of_system=all_links_of_system,
- settings_snapshot=settings_snapshot,
- )
- self.search = search
- self.model = model
- self.progress_callback = None
- # Note: questions_by_iteration is already initialized by parent class
-
- # Use provided citation_handler or create one
- self.citation_handler = citation_handler or CitationHandler(
- self.model, settings_snapshot=settings_snapshot
- )
-
- # Initialize components
- self.question_generator = StandardQuestionGenerator(self.model)
- self.knowledge_generator = StandardKnowledge(self.model)
- self.findings_repository = FindingsRepository(self.model)
-
- def analyze_topic(self, query: str) -> Dict:
- """
- RapidSearch implementation that collects snippets, avoids intermediate
- synthesis, and only performs a final synthesis at the end.
- """
- logger.info(f"Starting rapid research on topic: {query}")
-
- findings = []
- all_search_results = []
- collected_snippets = []
- section_links = []
-
- self._update_progress(
- "Initializing rapid research system",
- 5,
- {"phase": "init", "strategy": "rapid"},
- )
-
- # Check if search engine is available
- if not self._validate_search_engine():
- return {
- "findings": [],
- "iterations": 0,
- "questions": {},
- "formatted_findings": "Error: Unable to conduct research without a search engine.",
- "current_knowledge": "",
- "error": "No search engine available",
- }
-
- # Step 1: Initial search for the main query
- self._update_progress(
- "Performing initial search for main query",
- 10,
- {"phase": "search", "iteration": 1},
- )
-
- try:
- initial_results = self.search.run(query)
-
- if not initial_results:
- self._update_progress(
- "No initial results found",
- 15,
- {"phase": "search_complete", "result_count": 0},
- )
- initial_results = []
- else:
- self._update_progress(
- f"Found {len(initial_results)} initial results",
- 15,
- {
- "phase": "search_complete",
- "result_count": len(initial_results),
- },
- )
-
- # Extract snippets and links
- for result in initial_results:
- if "snippet" in result:
- collected_snippets.append(
- {
- "text": result["snippet"],
- "source": result.get("title", "Unknown Source"),
- "link": result.get("link", ""),
- "query": query,
- }
- )
-
- # Extract and save links
- initial_links = extract_links_from_search_results(initial_results)
- self.all_links_of_system.extend(initial_links)
- section_links.extend(initial_links)
- all_search_results.extend(initial_results)
-
- # No findings added here - just collecting data
-
- except Exception:
- logger.exception("SEARCH ERROR: Error during initial search")
- self._update_progress(
- "Error during initial search",
- 15,
- {"phase": "search_error", "error": "Search error"},
- )
- initial_results = []
-
- # Step 2: Generate a few follow-up questions (optional, can be skipped for ultimate speed)
- self._update_progress(
- "Generating follow-up questions",
- 25,
- {"phase": "question_generation"},
- )
-
- questions = self.question_generator.generate_questions(
- current_knowledge="", # No knowledge accumulation in rapid mode
- query=query,
- questions_per_iteration=3, # Fewer questions for speed
- questions_by_iteration={},
- )
-
- self.questions_by_iteration[0] = questions
- logger.info(f"Generated questions: {questions}")
-
- # Step 3: Process follow-up questions
- question_count = len(questions)
- for q_idx, question in enumerate(questions):
- question_progress = 30 + ((q_idx + 1) / question_count * 40)
-
- self._update_progress(
- f"Searching for: {question}",
- int(question_progress),
- {"phase": "search", "question_index": q_idx + 1},
- )
-
- try:
- search_results = self.search.run(question)
-
- if not search_results:
- self._update_progress(
- f"No results found for question: {question}",
- int(question_progress + 2),
- {"phase": "search_complete", "result_count": 0},
- )
- continue
-
- self._update_progress(
- f"Found {len(search_results)} results for question: {question}",
- int(question_progress + 5),
- {
- "phase": "search_complete",
- "result_count": len(search_results),
- },
- )
-
- # Extract snippets only
- for result in search_results:
- if "snippet" in result:
- collected_snippets.append(
- {
- "text": result["snippet"],
- "source": result.get("title", "Unknown Source"),
- "link": result.get("link", ""),
- "query": question,
- }
- )
-
- # Extract and save links
- links = extract_links_from_search_results(search_results)
- self.all_links_of_system.extend(links)
- section_links.extend(links)
- all_search_results.extend(search_results)
-
- # No findings added here - just collecting data
-
- except Exception:
- logger.exception("SEARCH ERROR: Error during search")
- self._update_progress(
- "Error during search",
- int(question_progress + 2),
- {"phase": "search_error", "error": "Search error"},
- )
-
- # Step 4: Perform a single final synthesis with all collected snippets using the citation handler
- self._update_progress(
- "Synthesizing all collected information",
- 80,
- {"phase": "final_synthesis"},
- )
-
- try:
- # Use citation handler for the final analysis
- # First, we need a stub of current knowledge
-
- # Use the citation handler to analyze the results
- result = self.citation_handler.analyze_initial(
- query, all_search_results
- )
-
- if result:
- synthesized_content = result["content"]
-
- # Create a synthesis finding
- finding = {
- "phase": "Final synthesis",
- "content": synthesized_content,
- "question": query,
- "search_results": all_search_results,
- "documents": result.get("documents", []),
- }
- findings.append(finding)
-
- # Transfer questions to the repository
- self.findings_repository.set_questions_by_iteration(
- self.questions_by_iteration
- )
-
- # Format the findings with search questions and sources
- formatted_findings = (
- self.findings_repository.format_findings_to_text(
- findings, synthesized_content
- )
- )
-
- # Also add to the repository
- self.findings_repository.add_documents(
- result.get("documents", [])
- )
- else:
- # Fallback if citation handler fails
- synthesized_content = (
- "Error: Failed to synthesize results with citation handler."
- )
- formatted_findings = synthesized_content
- finding = {
- "phase": "Error",
- "content": synthesized_content,
- "question": query,
- "search_results": all_search_results,
- "documents": [],
- }
- findings.append(finding)
-
- except Exception as e:
- error_msg = f"Error synthesizing final answer: {e!s}"
- logger.exception(error_msg)
- synthesized_content = f"Error generating synthesis: {e!s}"
- formatted_findings = f"Error: {e!s}"
- finding = {
- "phase": "Error",
- "content": synthesized_content,
- "question": query,
- "search_results": all_search_results,
- "documents": [],
- }
- findings.append(finding)
-
- self._update_progress("Research complete", 100, {"phase": "complete"})
-
- return {
- "findings": findings,
- "iterations": 1, # Always 1 iteration in rapid mode
- "questions": self.questions_by_iteration,
- "formatted_findings": formatted_findings,
- "current_knowledge": synthesized_content,
- }
diff --git a/src/local_deep_research/advanced_search_system/strategies/recursive_decomposition_strategy.py b/src/local_deep_research/advanced_search_system/strategies/recursive_decomposition_strategy.py
deleted file mode 100644
index af14bccd56..0000000000
--- a/src/local_deep_research/advanced_search_system/strategies/recursive_decomposition_strategy.py
+++ /dev/null
@@ -1,493 +0,0 @@
-"""
-Recursive Decomposition Strategy for hierarchical question answering.
-
-This strategy decomposes complex questions into subtasks, recursively solving
-each subtask and aggregating results to answer the original question.
-"""
-
-from typing import Any, Dict, List
-
-from langchain_core.language_models import BaseChatModel
-from loguru import logger
-
-from ...utilities.search_utilities import format_findings, remove_think_tags
-from ..findings.repository import FindingsRepository
-from ..questions.standard_question import StandardQuestionGenerator
-from .base_strategy import BaseSearchStrategy
-from .source_based_strategy import SourceBasedSearchStrategy
-
-
-class RecursiveDecompositionStrategy(BaseSearchStrategy):
- """
- A strategy that recursively decomposes complex questions into subtasks.
-
- Each subtask is either solved directly via search or further decomposed,
- creating a hierarchical problem-solving approach.
- """
-
- def __init__(
- self,
- model: BaseChatModel,
- search: Any,
- all_links_of_system: List[Any],
- max_recursion_depth: int = 5,
- source_search_iterations: int = 2,
- source_questions_per_iteration: int = 20,
- settings_snapshot: dict | None = None,
- ):
- """Initialize the recursive decomposition strategy.
-
- Args:
- model: The language model to use
- search: The search engine instance
- all_links_of_system: List to store all encountered links
- max_recursion_depth: Maximum recursion depth to prevent infinite loops
- source_search_iterations: Iterations for source-based searches
- source_questions_per_iteration: Questions per iteration for source-based searches
- settings_snapshot: Optional settings snapshot for configuration
- """
- super().__init__(
- all_links_of_system, settings_snapshot=settings_snapshot
- )
- self.model = model
- self.search = search
- self.max_recursion_depth = max_recursion_depth
- self.source_search_iterations = source_search_iterations
- self.source_questions_per_iteration = source_questions_per_iteration
- self.question_generator = StandardQuestionGenerator(model)
- self.findings_repository = FindingsRepository(model)
- self.current_depth = 0
- self.original_query = None # Store the original query for context
-
- def analyze_topic(self, query: str, recursion_depth: int = 0) -> Dict:
- """Analyze a topic using recursive decomposition.
-
- Args:
- query: The research query to analyze
- recursion_depth: Current recursion depth
-
- Returns:
- Dictionary containing analysis results
- """
- if recursion_depth >= self.max_recursion_depth:
- logger.warning(
- f"Max recursion depth {self.max_recursion_depth} reached"
- )
- return self._use_source_based_strategy(query)
-
- # Initialize tracking at top level
- if recursion_depth == 0:
- self.all_links_of_system.clear()
- self.questions_by_iteration = []
- self.findings = []
- self.original_query = query # Store the original query
-
- # Progress callback for UI
- if self.progress_callback:
- self.progress_callback(
- "Starting recursive decomposition analysis",
- 1,
- {"phase": "init", "strategy": "recursive_decomposition"},
- )
-
- logger.info(f"Analyzing query at depth {recursion_depth}: {query}")
-
- # Decide whether to decompose or search directly
- decomposition_decision = self._decide_decomposition(query)
-
- if decomposition_decision["should_decompose"]:
- # Add decomposition decision to findings for UI visibility
- self.findings.append(
- {
- "phase": f"Decomposition Decision (Depth {recursion_depth})",
- "content": decomposition_decision["reasoning"],
- "subtasks": decomposition_decision["subtasks"],
- "timestamp": self._get_timestamp(),
- }
- )
-
- if self.progress_callback:
- self.progress_callback(
- f"Decomposing query into {len(decomposition_decision['subtasks'])} subtasks",
- 10 + (recursion_depth * 10),
- {
- "phase": "decomposition",
- "depth": recursion_depth,
- "subtask_count": len(
- decomposition_decision["subtasks"]
- ),
- },
- )
-
- return self._handle_decomposition(
- query, decomposition_decision, recursion_depth
- )
- # Add search decision to findings
- self.findings.append(
- {
- "phase": f"Direct Search Decision (Depth {recursion_depth})",
- "content": f"Searching directly for: {query}",
- "reasoning": decomposition_decision["reasoning"],
- "timestamp": self._get_timestamp(),
- }
- )
-
- return self._use_source_based_strategy(query)
-
- def _decide_decomposition(self, query: str) -> Dict:
- """Decide whether to decompose the query or search directly.
-
- Args:
- query: The query to analyze
-
- Returns:
- Dictionary with decomposition decision and subtasks if applicable
- """
- # Include original query context when needed
- context_info = ""
- if self.original_query and query != self.original_query:
- context_info = f"\nOriginal research topic: {self.original_query}"
-
- prompt = f"""Analyze this research query and decide whether to decompose it into subtasks or search directly.
-
-Query: {query}{context_info}
-
-Consider:
-1. Is this a compound question with multiple distinct parts?
-2. Does it require finding specific information that builds on other information?
-3. Would breaking it down lead to more focused, answerable questions?
-4. Can this be answered with a straightforward web search?
-
-Respond in this format:
-DECISION: [DECOMPOSE or SEARCH_DIRECTLY]
-REASONING: [Your reasoning in 1-2 sentences]
-If DECOMPOSE, provide:
-SUBTASKS:
-1. [First subtask - make it specific and searchable]
-2. [Second subtask - make it specific and searchable]
-...
-DEPENDENCIES: [Explain which subtasks depend on others, if any]
-
-When creating subtasks, ensure they maintain relevance to the original topic."""
-
- response = self.model.invoke(prompt)
- content = remove_think_tags(str(response.content))
-
- # Log the decision for debugging
- logger.info(f"Decomposition decision for '{query}': {content[:200]}...")
-
- # Parse the response
- lines = content.strip().split("\n")
- decision = "SEARCH_DIRECTLY"
- subtasks = []
- dependencies = []
- reasoning = ""
-
- parsing_subtasks = False
- for line in lines:
- if line.startswith("DECISION:"):
- decision = line.split(":", 1)[1].strip()
- elif line.startswith("REASONING:"):
- reasoning = line.split(":", 1)[1].strip()
- elif line.startswith("SUBTASKS:"):
- parsing_subtasks = True
- elif line.startswith("DEPENDENCIES:"):
- parsing_subtasks = False
- dependencies_text = line.split(":", 1)[1].strip()
- if dependencies_text:
- dependencies = [dependencies_text]
- elif parsing_subtasks and line.strip():
- # Handle numbered subtasks
- if line[0].isdigit() and "." in line:
- subtasks.append(line.split(".", 1)[1].strip())
- elif line.strip().startswith("-"):
- subtasks.append(line.strip()[1:].strip())
-
- return {
- "should_decompose": decision == "DECOMPOSE",
- "reasoning": reasoning,
- "subtasks": subtasks,
- "dependencies": dependencies,
- }
-
- def _handle_decomposition(
- self, query: str, decomposition: Dict, recursion_depth: int
- ) -> Dict:
- """Handle the decomposition of a query into subtasks.
-
- Args:
- query: The original query
- decomposition: The decomposition decision with subtasks
- recursion_depth: Current recursion depth
-
- Returns:
- Aggregated results from all subtasks
- """
- subtasks = decomposition["subtasks"]
- subtask_results = []
-
- # Process each subtask
- for i, subtask in enumerate(subtasks):
- logger.info(
- f"Processing subtask {i + 1}/{len(subtasks)} at depth {recursion_depth}: {subtask}"
- )
-
- # Update progress for UI
- progress = (
- 20 + (recursion_depth * 10) + ((i + 1) / len(subtasks) * 40)
- )
- if self.progress_callback:
- self.progress_callback(
- f"Processing subtask {i + 1}/{len(subtasks)}: {subtask[:50]}...",
- int(progress),
- {
- "phase": "subtask_processing",
- "depth": recursion_depth,
- "current_subtask": i + 1,
- "total_subtasks": len(subtasks),
- "subtask_text": subtask,
- },
- )
-
- # Recursively analyze subtask
- result = self.analyze_topic(subtask, recursion_depth + 1)
-
- # Store subtask result with metadata
- subtask_results.append(
- {
- "subtask": subtask,
- "result": result,
- "depth": recursion_depth + 1,
- "index": i + 1,
- }
- )
-
- # Add subtask completion to findings
- self.findings.append(
- {
- "phase": f"Subtask {i + 1} Complete (Depth {recursion_depth})",
- "content": f"Completed: {subtask}",
- "result_summary": result.get("current_knowledge", "")[:500],
- "timestamp": self._get_timestamp(),
- }
- )
-
- # Aggregate results
- return self._aggregate_subtask_results(
- query, subtask_results, recursion_depth
- )
-
- def _aggregate_subtask_results(
- self,
- original_query: str,
- subtask_results: List[Dict],
- recursion_depth: int,
- ) -> Dict:
- """Aggregate results from multiple subtasks to answer the original query.
-
- Args:
- original_query: The original query
- subtask_results: Results from all subtasks
- recursion_depth: Current recursion depth
-
- Returns:
- Aggregated result answering the original query
- """
- # Update progress
- if self.progress_callback:
- self.progress_callback(
- f"Synthesizing results from {len(subtask_results)} subtasks",
- 80 + (recursion_depth * 5),
- {"phase": "synthesis", "depth": recursion_depth},
- )
-
- # Prepare context from subtask results
- context_parts = []
- all_links = []
- all_findings = []
- all_questions = []
-
- for idx, result in enumerate(subtask_results):
- subtask = result["subtask"]
- subtask_result = result["result"]
-
- # Extract key information
- if "current_knowledge" in subtask_result:
- context_parts.append(
- f"### Subtask {idx + 1}: {subtask}\n"
- f"Result: {subtask_result['current_knowledge']}\n"
- )
-
- if "all_links_of_system" in subtask_result:
- all_links.extend(subtask_result["all_links_of_system"])
-
- if "findings" in subtask_result:
- all_findings.extend(subtask_result["findings"])
-
- if "questions_by_iteration" in subtask_result:
- all_questions.extend(subtask_result["questions_by_iteration"])
-
- context = "\n".join(context_parts)
-
- # Include master context for better synthesis
- master_context_info = ""
- if self.original_query and original_query != self.original_query:
- master_context_info = (
- f"\nMaster Research Topic: {self.original_query}"
- )
-
- # Use LLM to synthesize final answer
- synthesis_prompt = f"""Based on the following subtask results, provide a comprehensive answer to the original query.
-
-Original Query: {original_query}{master_context_info}
-
-Subtask Results:
-{context}
-
-Synthesize the information to directly answer the original query. Be specific and reference the relevant information from the subtasks. Provide a clear, well-structured answer.
-"""
-
- response = self.model.invoke(synthesis_prompt)
- synthesized_answer = remove_think_tags(str(response.content))
-
- # Add synthesis to findings
- synthesis_finding = {
- "phase": f"Final Synthesis (Depth {recursion_depth})",
- "content": synthesized_answer,
- "question": original_query,
- "timestamp": self._get_timestamp(),
- }
- self.findings.append(synthesis_finding)
- all_findings.append(synthesis_finding)
-
- # Format findings for UI using the standard utility
- # Remove duplicate links (can't use set() since links might be dicts)
- unique_links = []
- seen_links = set()
- for link in all_links:
- # If link is a dict, use its URL/link as the unique identifier
- if isinstance(link, dict):
- link_id = link.get("link") or link.get("url") or str(link)
- else:
- link_id = str(link)
-
- if link_id not in seen_links:
- seen_links.add(link_id)
- unique_links.append(link)
-
- # Convert questions list to the expected dictionary format
- questions_dict = {}
- for i, questions in enumerate(all_questions):
- if isinstance(questions, list):
- questions_dict[i + 1] = questions
- elif isinstance(questions, dict):
- # If it's already a dict, just merge it
- questions_dict.update(questions)
- elif questions is not None:
- # For any other type, make it a single-item list
- questions_dict[i + 1] = [str(questions)]
-
- formatted_findings = format_findings(
- all_findings,
- synthesized_answer, # Pass the synthesized answer as the second argument
- questions_dict, # Pass the questions dictionary as the third argument
- )
-
- # Compile final result matching source-based strategy format
- result = {
- "current_knowledge": synthesized_answer,
- "formatted_findings": formatted_findings,
- "findings": all_findings,
- "iterations": 0, # Set to 0 since we don't track iterations
- "questions_by_iteration": questions_dict,
- "all_links_of_system": unique_links,
- "sources": unique_links,
- "subtask_results": subtask_results,
- "strategy": "recursive_decomposition",
- "recursion_depth": recursion_depth,
- "questions": {
- "total": sum(
- len(q) if isinstance(q, (list, dict)) else 1
- for q in all_questions
- if q is not None
- ),
- "by_iteration": questions_dict,
- },
- }
-
- # Final progress update
- if self.progress_callback and recursion_depth == 0:
- self.progress_callback(
- "Analysis complete",
- 100,
- {"phase": "complete", "strategy": "recursive_decomposition"},
- )
-
- return result
-
- def _use_source_based_strategy(self, query: str) -> Dict:
- """Fall back to source-based strategy for direct search.
-
- Args:
- query: The query to search
-
- Returns:
- Search results from source-based strategy
- """
- # If we have original query context and it's different from current query,
- # create an enhanced query that includes the context
- enhanced_query = query
- if self.original_query and query != self.original_query:
- enhanced_query = (
- f"{query} (in the context of: {self.original_query})"
- )
- logger.info(
- f"Enhanced query for source-based search: {enhanced_query}"
- )
- else:
- logger.info(
- f"Using source-based strategy for direct search: {query}"
- )
-
- # Create a source-based strategy instance with specified parameters
- source_strategy = SourceBasedSearchStrategy(
- model=self.model,
- search=self.search,
- all_links_of_system=self.all_links_of_system,
- include_text_content=True,
- use_cross_engine_filter=True,
- use_atomic_facts=True,
- )
-
- # Configure with our parameters
- source_strategy.max_iterations = self.source_search_iterations
- source_strategy.questions_per_iteration = (
- self.source_questions_per_iteration
- )
-
- # Copy our callback to maintain UI integration
- if self.progress_callback:
- source_strategy.set_progress_callback(self.progress_callback)
-
- # Run the search with the enhanced query
- results = source_strategy.analyze_topic(enhanced_query)
-
- # Update our tracking to maintain consistency with UI
- if hasattr(source_strategy, "questions_by_iteration"):
- self.questions_by_iteration.extend(
- source_strategy.questions_by_iteration
- )
-
- # Ensure results have the fields the UI expects
- if "findings" not in results:
- results["findings"] = []
- if "questions_by_iteration" not in results:
- results["questions_by_iteration"] = self.questions_by_iteration
-
- return results
-
- def _get_timestamp(self) -> str:
- """Get current timestamp for findings."""
- from datetime import datetime, UTC
-
- return datetime.now(UTC).isoformat()
diff --git a/src/local_deep_research/advanced_search_system/strategies/smart_decomposition_strategy.py b/src/local_deep_research/advanced_search_system/strategies/smart_decomposition_strategy.py
deleted file mode 100644
index 34f504764a..0000000000
--- a/src/local_deep_research/advanced_search_system/strategies/smart_decomposition_strategy.py
+++ /dev/null
@@ -1,286 +0,0 @@
-"""
-Smart Decomposition Strategy that chooses between recursive and adaptive approaches.
-
-This strategy analyzes the query type and chooses the most appropriate
-decomposition method for optimal results.
-"""
-
-from enum import Enum
-from typing import Any, Dict, List
-
-from langchain_core.language_models import BaseChatModel
-from loguru import logger
-
-from ...utilities.search_utilities import remove_think_tags
-from .adaptive_decomposition_strategy import AdaptiveDecompositionStrategy
-from .base_strategy import BaseSearchStrategy
-from .browsecomp_optimized_strategy import BrowseCompOptimizedStrategy
-from .evidence_based_strategy import EvidenceBasedStrategy
-from .recursive_decomposition_strategy import RecursiveDecompositionStrategy
-
-
-class QueryType(Enum):
- """Types of queries that benefit from different strategies."""
-
- PUZZLE_LIKE = "puzzle_like" # Queries with specific clues/constraints
- HIERARCHICAL = "hierarchical" # Multi-part questions with clear structure
- EXPLORATORY = "exploratory" # Open-ended research questions
- COMPARATIVE = "comparative" # Comparison between multiple entities
- FACTUAL = "factual" # Simple factual questions
- CONSTRAINT_BASED = (
- "constraint_based" # Queries with multiple verifiable constraints
- )
-
-
-class SmartDecompositionStrategy(BaseSearchStrategy):
- """
- A meta-strategy that intelligently chooses between decomposition approaches.
-
- It analyzes the query characteristics and selects either:
- - Adaptive decomposition for puzzle-like or constraint-based queries
- - Recursive decomposition for clearly hierarchical queries
- - Direct search for simple factual queries
- """
-
- def __init__(
- self,
- model: BaseChatModel,
- search: Any,
- all_links_of_system: List[Any],
- settings_snapshot=None,
- **kwargs,
- ):
- """Initialize the smart decomposition strategy.
-
- Args:
- model: The language model to use
- search: The search engine instance
- all_links_of_system: List to store all encountered links
- settings_snapshot: Settings snapshot for thread context
- **kwargs: Additional parameters for sub-strategies
- """
- super().__init__(all_links_of_system, settings_snapshot)
- self.model = model
- self.search = search
- self.strategy_params = kwargs
-
- def analyze_topic(self, query: str) -> Dict:
- """Analyze a topic using the most appropriate strategy.
-
- Args:
- query: The research query to analyze
-
- Returns:
- Dictionary containing analysis results
- """
- # Determine query type
- query_type = self._classify_query(query)
- logger.info(f"Query classified as: {query_type.value}")
-
- # Progress callback for UI
- if self.progress_callback:
- self.progress_callback(
- f"Analyzing query type: {query_type.value}",
- 5,
- {
- "phase": "query_classification",
- "query_type": query_type.value,
- },
- )
-
- # Choose and execute appropriate strategy
- if query_type == QueryType.PUZZLE_LIKE:
- # Check if it's specifically a BrowseComp-style puzzle
- if self._is_browsecomp_style(query):
- return self._use_browsecomp_strategy(query)
- return self._use_evidence_strategy(query)
- if query_type == QueryType.CONSTRAINT_BASED:
- return self._use_evidence_strategy(query)
- if query_type == QueryType.HIERARCHICAL or query_type in [
- QueryType.COMPARATIVE,
- QueryType.EXPLORATORY,
- ]:
- return self._use_recursive_strategy(query)
- # FACTUAL or unknown
- return self._use_adaptive_strategy(query)
-
- def _classify_query(self, query: str) -> QueryType:
- """Classify the query type to determine best strategy.
-
- Args:
- query: The query to classify
-
- Returns:
- QueryType enum value
- """
- prompt = f"""Analyze this query and classify its type:
-
-Query: {query}
-
-Query Types:
-1. PUZZLE_LIKE - Contains specific clues, constraints, or puzzle elements that need to be solved step by step
-2. HIERARCHICAL - Multi-part question with clear subtopics that can be addressed independently
-3. EXPLORATORY - Open-ended research question seeking broad understanding
-4. COMPARATIVE - Requires comparing multiple entities or concepts
-5. FACTUAL - Simple factual question with a direct answer
-6. CONSTRAINT_BASED - Has multiple specific constraints that need verification (dates, numbers, properties)
-
-Consider:
-- Does it have specific constraints or clues to follow?
-- Can it be broken into independent subtasks?
-- Is it seeking a specific answer or broad understanding?
-- Does it require step-by-step verification?
-
-Respond with:
-QUERY_TYPE: [type]
-REASONING: [brief explanation]
-KEY_CHARACTERISTICS: [list main characteristics]
-"""
-
- response = self.model.invoke(prompt)
- content = remove_think_tags(str(response.content))
-
- # Parse response
- query_type = QueryType.EXPLORATORY # Default
-
- lines = content.strip().split("\n")
- for line in lines:
- if line.startswith("QUERY_TYPE:"):
- type_str = line.split(":", 1)[1].strip()
- try:
- query_type = QueryType[type_str]
- except KeyError:
- # Try to match by value
- for q_type in QueryType:
- if q_type.value in type_str.lower():
- query_type = q_type
- break
-
- logger.info(f"Query classification reasoning: {content}")
- return query_type
-
- def _use_adaptive_strategy(self, query: str) -> Dict:
- """Use adaptive decomposition strategy.
-
- Args:
- query: The query to analyze
-
- Returns:
- Analysis results
- """
- logger.info("Using adaptive decomposition strategy")
-
- strategy = AdaptiveDecompositionStrategy(
- model=self.model,
- search=self.search,
- all_links_of_system=self.all_links_of_system,
- **self.strategy_params,
- )
-
- if self.progress_callback:
- strategy.set_progress_callback(self.progress_callback)
-
- return strategy.analyze_topic(query)
-
- def _is_browsecomp_style(self, query: str) -> bool:
- """Check if query is a BrowseComp-style puzzle.
-
- Args:
- query: The query to check
-
- Returns:
- True if it appears to be a BrowseComp puzzle
- """
- browsecomp_indicators = [
- "specific scenic location",
- "body part",
- "fell from",
- "viewpoint",
- "search and rescue",
- "SAR incidents",
- "exact answer",
- "multiple clues",
- "last ice age",
- "times more",
- "between",
- "what is the name",
- ]
-
- lower_query = query.lower()
- indicator_count = sum(
- 1
- for indicator in browsecomp_indicators
- if indicator.lower() in lower_query
- )
-
- # If 3+ indicators present, likely BrowseComp-style
- return indicator_count >= 3
-
- def _use_browsecomp_strategy(self, query: str) -> Dict:
- """Use BrowseComp-optimized strategy.
-
- Args:
- query: The query to analyze
-
- Returns:
- Analysis results
- """
- logger.info("Using BrowseComp-optimized strategy for puzzle query")
-
- strategy = BrowseCompOptimizedStrategy(
- model=self.model,
- search=self.search,
- all_links_of_system=self.all_links_of_system,
- **self.strategy_params,
- )
-
- if self.progress_callback:
- strategy.set_progress_callback(self.progress_callback)
-
- return strategy.analyze_topic(query)
-
- def _use_evidence_strategy(self, query: str) -> Dict:
- """Use evidence-based strategy.
-
- Args:
- query: The query to analyze
-
- Returns:
- Analysis results
- """
- logger.info("Using evidence-based strategy for constraint-based query")
-
- strategy = EvidenceBasedStrategy(
- model=self.model,
- search=self.search,
- all_links_of_system=self.all_links_of_system,
- **self.strategy_params,
- )
-
- if self.progress_callback:
- strategy.set_progress_callback(self.progress_callback)
-
- return strategy.analyze_topic(query)
-
- def _use_recursive_strategy(self, query: str) -> Dict:
- """Use recursive decomposition strategy.
-
- Args:
- query: The query to analyze
-
- Returns:
- Analysis results
- """
- logger.info("Using recursive decomposition strategy")
-
- strategy = RecursiveDecompositionStrategy(
- model=self.model,
- search=self.search,
- all_links_of_system=self.all_links_of_system,
- **self.strategy_params,
- )
-
- if self.progress_callback:
- strategy.set_progress_callback(self.progress_callback)
-
- return strategy.analyze_topic(query)
diff --git a/src/local_deep_research/advanced_search_system/strategies/smart_query_strategy.py b/src/local_deep_research/advanced_search_system/strategies/smart_query_strategy.py
deleted file mode 100644
index 59c75faba4..0000000000
--- a/src/local_deep_research/advanced_search_system/strategies/smart_query_strategy.py
+++ /dev/null
@@ -1,522 +0,0 @@
-"""
-Smart query generation strategy that works for any type of search target.
-"""
-
-import concurrent.futures
-from typing import Dict, List
-
-from loguru import logger
-
-from ...database.thread_local_session import thread_cleanup
-from ..constraints.base_constraint import Constraint
-from ..constraints.constraint_analyzer import ConstraintType
-from .early_stop_constrained_strategy import EarlyStopConstrainedStrategy
-
-
-class SmartQueryStrategy(EarlyStopConstrainedStrategy):
- """
- Enhanced strategy with intelligent query generation that:
- 1. Analyzes constraints to identify key search terms
- 2. Uses LLM to suggest search queries based on constraint meaning
- 3. Generates multiple query variations for better coverage
- """
-
- def __init__(
- self,
- *args,
- use_llm_query_generation: bool = True,
- queries_per_combination: int = 3,
- use_entity_seeding: bool = True,
- use_direct_property_search: bool = True,
- **kwargs,
- ):
- super().__init__(*args, **kwargs)
- self.use_llm_query_generation = use_llm_query_generation
- self.queries_per_combination = queries_per_combination
- self.use_entity_seeding = use_entity_seeding
- self.use_direct_property_search = use_direct_property_search
- # Track queries to avoid duplicates
- self.searched_queries = set()
- self.query_variations = set()
- # Store entity seeds for targeted search
- self.entity_seeds = []
-
- def _build_query(self, constraints: List[Constraint]) -> str:
- """Build intelligent queries using constraint analysis."""
- if self.use_llm_query_generation:
- # Use LLM to generate smart queries
- return self._generate_smart_query(constraints)
- # Fallback to improved standard approach
- return self._build_standard_query(constraints)
-
- def _generate_smart_query(self, constraints: List[Constraint]) -> str:
- """Use LLM to generate optimal search queries."""
- constraint_text = "\n".join(
- [
- f"- {c.type.value}: {c.value} (weight: {c.weight})"
- for c in constraints
- ]
- )
-
- # Build a list of already searched queries to avoid duplication
- searched_list = list(self.searched_queries)[:10] # Show last 10 to LLM
- already_searched = (
- "\n".join([f"- {q}" for q in searched_list])
- if searched_list
- else "None"
- )
-
- prompt = f"""
-Analyze these search constraints and generate an optimal web search query:
-
-Constraints:
-{constraint_text}
-
-Target type: {getattr(self, "entity_type", "unknown")}
-
-Already searched queries (avoid these):
-{already_searched}
-
-Generate a single search query that would most effectively find results matching these constraints.
-The query should:
-1. Include the most identifying/unique terms
-2. Use appropriate search operators (quotes, AND, OR)
-3. Be specific enough to find relevant results but not too narrow
-4. Focus on the highest weighted constraints
-5. Be different from already searched queries
-
-Return only the search query, nothing else.
-"""
-
- try:
- query = self.model.invoke(prompt).content.strip()
-
- # Check if this query is too similar to existing ones
- normalized_query = query.strip().lower()
- if normalized_query in self.searched_queries:
- logger.info(
- f"LLM generated duplicate query, using fallback: {query}"
- )
- return self._build_standard_query(constraints)
-
- logger.info(f"LLM generated query: {query}")
- return query
- except Exception:
- logger.exception("Failed to generate smart query")
- return self._build_standard_query(constraints)
-
- def _build_standard_query(self, constraints: List[Constraint]) -> str:
- """Improved standard query building."""
- # Group constraints by importance
- critical_terms = []
- supplementary_terms = []
-
- for c in constraints:
- term = c.value
-
- # Quote multi-word terms
- if " " in term and not term.startswith('"'):
- term = f'"{term}"'
-
- if c.weight > 0.7:
- critical_terms.append(term)
- else:
- supplementary_terms.append(term)
-
- # Build query with critical terms required, supplementary optional
- query_parts = []
-
- # Add entity type if known
- entity_type = getattr(self, "entity_type", None)
- if entity_type and entity_type != "unknown entity":
- query_parts.append(entity_type)
-
- # Add critical terms
- if critical_terms:
- query_parts.extend(critical_terms)
-
- # Add some supplementary terms
- if supplementary_terms:
- query_parts.extend(
- supplementary_terms[:2]
- ) # Limit to avoid overly specific queries
-
- return " ".join(query_parts)
-
- @thread_cleanup
- def _execute_combination_search(self, combo) -> List:
- """Override to generate multiple query variations per combination."""
- all_candidates = []
-
- if self.use_llm_query_generation:
- # Generate multiple query variations
- queries = self._generate_query_variations(combo.constraints)
-
- # Execute searches in parallel
- with concurrent.futures.ThreadPoolExecutor(
- max_workers=self.queries_per_combination
- ) as executor:
- futures = []
- for query in queries:
- # Check if we've already searched this query
- normalized_query = query.strip().lower()
- if normalized_query in self.searched_queries:
- logger.info(f"Skipping duplicate query: '{query}'")
- continue
-
- self.searched_queries.add(normalized_query)
- future = executor.submit(
- thread_cleanup(self._execute_search), query
- )
- futures.append((query, future))
-
- for query, future in futures:
- try:
- results = future.result()
- candidates = self._extract_candidates_from_results(
- results
- )
- all_candidates.extend(candidates)
-
- logger.info(
- f"Query '{query}' found {len(candidates)} candidates"
- )
- except Exception:
- logger.exception(f"Search failed for query '{query}'")
- else:
- # Use single query from parent implementation
- candidates = super()._execute_combination_search(combo)
- all_candidates.extend(candidates)
-
- return all_candidates
-
- def _generate_query_variations(
- self, constraints: List[Constraint]
- ) -> List[str]:
- """Generate multiple query variations for better coverage."""
- # Handle single constraint case
- if isinstance(constraints, Constraint):
- constraints = [constraints]
-
- constraint_text = "\n".join(
- [f"- {c.type.value}: {c.value}" for c in constraints]
- )
-
- # Build a list of already searched queries to avoid duplication
- searched_list = list(self.searched_queries)[:20] # Show last 20 to LLM
- already_searched = (
- "\n".join([f"- {q}" for q in searched_list])
- if searched_list
- else "None"
- )
-
- prompt = f"""
-Generate {self.queries_per_combination} different search queries for these constraints:
-
-{constraint_text}
-
-Already searched queries (avoid these):
-{already_searched}
-
-Each query should:
-- Approach the search from a different angle
-- Use different search terms or operators
-- Target different aspects of the constraints
-- Be distinctly different from already searched queries
-
-Provide each query on a separate line.
-"""
-
- try:
- response = self.model.invoke(prompt).content
- queries = [q.strip() for q in response.split("\n") if q.strip()]
-
- # Filter out duplicates
- unique_queries = []
- for query in queries:
- normalized = query.strip().lower()
- if (
- normalized not in self.searched_queries
- and normalized not in self.query_variations
- ):
- unique_queries.append(query)
- self.query_variations.add(normalized)
- else:
- logger.info(
- f"Filtering out duplicate query variation: {query}"
- )
-
- # If all queries were duplicates, generate a fallback
- if not unique_queries:
- fallback = self._build_standard_query(constraints)
- if fallback.strip().lower() not in self.searched_queries:
- unique_queries = [fallback]
-
- return unique_queries[: self.queries_per_combination]
- except Exception:
- logger.exception("Failed to generate query variations")
- # Fallback to single query
- return [self._build_standard_query(constraints)]
-
- def _extract_candidates_from_results(self, results: Dict) -> List:
- """Improved candidate extraction that's more generic."""
- candidates = []
- content = results.get("current_knowledge", "")
-
- if not content:
- return candidates
-
- # Use LLM to extract relevant entities/topics from the content
- prompt = f"""
-From the following search results, extract all relevant entities, topics, or answers that match our search target type: {getattr(self, "entity_type", "unknown")}
-
-Content:
-{content}
-
-List each potential match on a separate line.
-Include only names/titles/identifiers, not descriptions.
-"""
-
- try:
- response = self.model.invoke(prompt).content
- entity_names = [
- name.strip() for name in response.split("\n") if name.strip()
- ]
-
- # Create candidates from extracted names
- from ..candidates.base_candidate import Candidate
-
- for name in entity_names:
- if name and len(name) < 100: # Basic validation
- candidate = Candidate(name=name)
- candidates.append(candidate)
-
- logger.info(f"Extracted {len(candidates)} candidates from results")
-
- except Exception:
- logger.exception("Error extracting candidates")
-
- return candidates
-
- def _should_use_entity_seeding(self) -> bool:
- """Determine if entity seeding would be beneficial."""
- entity_type = getattr(self, "entity_type", "").lower()
- return (
- "character" in entity_type
- or "person" in entity_type
- or "hero" in entity_type
- )
-
- def _perform_entity_seeding(self):
- """Use LLM to suggest specific entity names based on constraints."""
- logger.info("Performing entity seeding based on constraints")
-
- # Extract key properties from constraints
- key_properties = []
- for constraint in self.constraint_ranking:
- if constraint.weight > 0.7: # High-weight constraints
- key_properties.append(constraint.value)
-
- if not key_properties:
- return
-
- properties_text = "\n".join([f"- {prop}" for prop in key_properties])
-
- prompt = f"""
-Based on these properties, suggest 5-10 specific {self.entity_type} names that might match:
-
-Properties:
-{properties_text}
-
-For example, if looking for a scientist from the 19th century, you might suggest:
-- Charles Darwin
-- Marie Curie
-- Louis Pasteur
-- Thomas Edison
-
-Provide one name per line. Be specific with actual character/entity names.
-"""
-
- try:
- response = self.model.invoke(prompt).content
- self.entity_seeds = [
- name.strip() for name in response.split("\n") if name.strip()
- ]
- logger.info(f"Generated entity seeds: {self.entity_seeds}")
-
- # Immediately search for these seeds
- self._search_entity_seeds()
-
- except Exception:
- logger.exception("Error generating entity seeds")
-
- def _search_entity_seeds(self):
- """Search for the entity seeds directly."""
- if not self.entity_seeds:
- return
-
- with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
- futures = []
- for seed in self.entity_seeds[:5]: # Limit to top 5
- query = f'"{seed}"'
- if query.lower() not in self.searched_queries:
- self.searched_queries.add(query.lower())
- future = executor.submit(
- thread_cleanup(self._execute_search), query
- )
- futures.append((seed, future))
-
- for seed, future in futures:
- try:
- results = future.result()
- candidates = self._extract_candidates_from_results(results)
-
- # Look for exact matches
- for candidate in candidates:
- if seed.lower() in candidate.name.lower():
- logger.info(
- f"Found seeded entity: {candidate.name}"
- )
- # Evaluate immediately
- if hasattr(self, "_evaluate_candidate_immediately"):
- self._evaluate_candidate_immediately(candidate)
- else:
- # Add to candidates list
- if not hasattr(self, "candidates"):
- self.candidates = []
- self.candidates.append(candidate)
-
- except Exception:
- logger.exception(f"Error searching for seed {seed}")
-
- def _try_direct_property_search(self):
- """Try direct searches for high-weight property constraints."""
- property_queries = []
-
- for constraint in self.constraint_ranking:
- if (
- constraint.weight > 0.7
- and constraint.type == ConstraintType.PROPERTY
- ):
- # Create specific property-based queries
- if (
- "elastic" in constraint.value.lower()
- or "stretch" in constraint.value.lower()
- ):
- property_queries.extend(
- [
- f'"{constraint.value}" superhero character',
- f'characters with "{constraint.value}"',
- f"list of {self.entity_type} {constraint.value}",
- ]
- )
- elif (
- "voice" in constraint.value.lower()
- or "actor" in constraint.value.lower()
- ):
- property_queries.append(
- f"{constraint.value} {self.entity_type}"
- )
-
- # Execute property searches
- if property_queries:
- logger.info(
- f"Executing direct property searches: {property_queries}"
- )
- with concurrent.futures.ThreadPoolExecutor(
- max_workers=3
- ) as executor:
- futures = []
- for query in property_queries[
- :3
- ]: # Limit to avoid too many searches
- if query.lower() not in self.searched_queries:
- self.searched_queries.add(query.lower())
- future = executor.submit(
- thread_cleanup(self._execute_search), query
- )
- futures.append(future)
-
- for future in futures:
- try:
- results = future.result()
- candidates = self._extract_candidates_from_results(
- results
- )
-
- for candidate in candidates:
- if hasattr(self, "_evaluate_candidate_immediately"):
- self._evaluate_candidate_immediately(candidate)
-
- except Exception:
- logger.exception("Property search error")
-
- def _perform_entity_name_search(self):
- """Last resort: search for entity names directly with constraints."""
- logger.info("Performing entity name search fallback")
-
- for entity_name in self.entity_seeds[:3]: # Top 3 seeds
- # Combine entity name with key constraints
- constraint_terms = []
- for constraint in self.constraint_ranking[:2]: # Top 2 constraints
- if constraint.weight > 0.5:
- constraint_terms.append(constraint.value)
-
- if constraint_terms:
- query = f'"{entity_name}" {" ".join(constraint_terms)}'
- if query.lower() not in self.searched_queries:
- logger.info(f"Trying targeted entity search: {query}")
- self.searched_queries.add(query.lower())
-
- try:
- results = self._execute_search(query)
- candidates = self._extract_candidates_from_results(
- results
- )
-
- for candidate in candidates:
- if entity_name.lower() in candidate.name.lower():
- logger.info(
- f"Found target entity in fallback: {candidate.name}"
- )
- if hasattr(
- self, "_evaluate_candidate_immediately"
- ):
- self._evaluate_candidate_immediately(
- candidate
- )
-
- # Check for early stop
- if (
- hasattr(self, "best_score")
- and self.best_score >= 0.99
- ):
- return
-
- except Exception:
- logger.exception("Entity name search error")
-
- def _progressive_constraint_search(self):
- """Override to add entity seeding and property search."""
- # Detect entity type first
- self.entity_type = self._detect_entity_type()
- logger.info(f"Detected entity type: {self.entity_type}")
-
- # Perform entity seeding if enabled and entity type suggests specific entities
- if self.use_entity_seeding and self._should_use_entity_seeding():
- self._perform_entity_seeding()
-
- # Try direct property search for high-weight properties
- if self.use_direct_property_search:
- self._try_direct_property_search()
-
- # Continue with normal progressive search
- super()._progressive_constraint_search()
-
- # If still no good results, try name-based fallback
- if (
- hasattr(self, "best_score")
- and self.best_score < 0.9
- and self.entity_seeds
- ):
- self._perform_entity_name_search()
diff --git a/src/local_deep_research/advanced_search_system/strategies/standard_strategy.py b/src/local_deep_research/advanced_search_system/strategies/standard_strategy.py
deleted file mode 100644
index 2ea17d91f3..0000000000
--- a/src/local_deep_research/advanced_search_system/strategies/standard_strategy.py
+++ /dev/null
@@ -1,342 +0,0 @@
-import json
-from typing import Dict, List, Union, cast
-
-from loguru import logger
-
-from ...citation_handler import CitationHandler
-
-# Model and search should be provided by AdvancedSearchSystem
-from ...config.thread_settings import get_setting_from_snapshot
-from ...utilities.enums import KnowledgeAccumulationApproach
-from ...utilities.search_utilities import extract_links_from_search_results
-from ..findings.repository import FindingsRepository
-from ..knowledge.standard_knowledge import StandardKnowledge
-from ..questions.standard_question import StandardQuestionGenerator
-from .base_strategy import BaseSearchStrategy
-
-
-class StandardSearchStrategy(BaseSearchStrategy):
- """Standard iterative search strategy that generates follow-up questions."""
-
- def __init__(
- self,
- search,
- model,
- citation_handler=None,
- all_links_of_system=None,
- settings_snapshot=None,
- ):
- """Initialize with optional dependency injection for testing."""
- super().__init__(
- all_links_of_system=all_links_of_system,
- settings_snapshot=settings_snapshot,
- )
- self.search = search
- self.model = model
-
- # Get iterations setting
- self.max_iterations = int(
- get_setting_from_snapshot(
- "search.iterations",
- settings_snapshot=settings_snapshot,
- default=3,
- )
- )
-
- self.questions_per_iteration = int(
- get_setting_from_snapshot(
- "search.questions_per_iteration",
- settings_snapshot=settings_snapshot,
- default=1,
- )
- )
- self.context_limit = int(
- get_setting_from_snapshot(
- "general.knowledge_accumulation_context_limit",
- settings_snapshot=settings_snapshot,
- default=2000000,
- )
- )
- # Note: questions_by_iteration is already initialized by parent class
-
- # Use provided citation_handler or create one
- self.citation_handler = citation_handler or CitationHandler(
- self.model, settings_snapshot=settings_snapshot
- )
-
- # Initialize specialized components
- self.question_generator = StandardQuestionGenerator(self.model)
- self.knowledge_generator = StandardKnowledge(self.model)
- self.findings_repository = FindingsRepository(self.model)
-
- # Initialize other attributes
- self.progress_callback = None
-
- def analyze_topic(self, query: str) -> Dict:
- """Standard implementation of the topic analysis process."""
- logger.info(f"Starting research on topic: {query}")
-
- findings = []
- current_knowledge = ""
- iteration = 0
- total_iterations = self.max_iterations
- section_links = []
-
- self._update_progress(
- "Initializing research system",
- 5,
- {"phase": "init", "iterations_planned": total_iterations},
- )
-
- # Check if search engine is available
- if self.search is None:
- error_msg = "Error: No search engine available. Please check your configuration."
- self._update_progress(
- error_msg,
- 100,
- {
- "phase": "error",
- "error": "No search engine available",
- "status": "failed",
- },
- )
- return {
- "findings": [],
- "iterations": 0,
- "questions": {},
- "formatted_findings": "Error: Unable to conduct research without a search engine.",
- "current_knowledge": "",
- "error": error_msg,
- }
-
- while iteration < self.max_iterations:
- iteration_progress_base = (iteration / total_iterations) * 100
- self._update_progress(
- f"Starting iteration {iteration + 1} of {total_iterations}",
- int(iteration_progress_base),
- {"phase": "iteration_start", "iteration": iteration + 1},
- )
-
- # Generate questions for this iteration using the question generator
- # Prepare context for question generation
- context = f"""Current Query: {query}
-Current Knowledge: {current_knowledge}
-Previous Questions: {json.dumps(self.questions_by_iteration, indent=2)}
-Iteration: {iteration + 1} of {total_iterations}"""
-
- # Call question generator with updated interface
- questions = self.question_generator.generate_questions(
- query=query,
- current_knowledge=context,
- questions_per_iteration=self.questions_per_iteration,
- questions_by_iteration=self.questions_by_iteration,
- )
-
- self.questions_by_iteration[iteration] = questions
- logger.info(f"Generated questions: {questions}")
-
- question_count = len(questions)
- knowledge_accumulation = get_setting_from_snapshot(
- "general.knowledge_accumulation",
- "ITERATION",
- settings_snapshot=self.settings_snapshot,
- )
- for q_idx, question in enumerate(questions):
- question_progress_base = iteration_progress_base + (
- ((q_idx + 1) / question_count)
- * (100 / total_iterations)
- * 0.5
- )
-
- self._update_progress(
- f"Searching for: {question}",
- int(question_progress_base),
- {
- "phase": "search",
- "iteration": iteration + 1,
- "question_index": q_idx + 1,
- },
- )
-
- try:
- if self.search is None:
- self._update_progress(
- f"Search engine unavailable, skipping search for: {question}",
- int(question_progress_base + 2),
- {
- "phase": "search_error",
- "error": "No search engine available",
- },
- )
- search_results = []
- else:
- search_results = self.search.run(question)
- except Exception as e:
- error_msg = f"Error during search: {e!s}"
- logger.exception(f"SEARCH ERROR: {error_msg}")
- self._handle_search_error(
- e, question, int(question_progress_base + 10)
- )
- search_results = []
-
- if search_results is None:
- self._update_progress(
- f"No search results found for question: {question}",
- int(question_progress_base + 2),
- {"phase": "search_complete", "result_count": 0},
- )
- search_results = [] # Initialize to empty list instead of None
- continue
-
- self._update_progress(
- f"Found {len(search_results)} results for question: {question}",
- int(question_progress_base + 2),
- {
- "phase": "search_complete",
- "result_count": len(search_results),
- },
- )
-
- logger.info(f"len search: {len(search_results)}")
-
- if len(search_results) == 0:
- continue
-
- self._update_progress(
- f"Analyzing results for: {question}",
- int(question_progress_base + 5),
- {"phase": "analysis"},
- )
-
- try:
- result = self.citation_handler.analyze_followup(
- question,
- search_results,
- current_knowledge,
- nr_of_links=len(self.all_links_of_system),
- )
- links = extract_links_from_search_results(search_results)
- self.all_links_of_system.extend(links)
- section_links.extend(links)
-
- if result is not None:
- results_with_links = str(result["content"])
- findings.append(
- {
- "phase": f"Follow-up {iteration}.{questions.index(question) + 1}",
- "content": results_with_links,
- "question": question,
- "search_results": search_results,
- "documents": result["documents"],
- }
- )
-
- if knowledge_accumulation != str(
- KnowledgeAccumulationApproach.NO_KNOWLEDGE.value
- ):
- current_knowledge = (
- current_knowledge
- + "\n\n\n New: \n"
- + results_with_links
- )
-
- if knowledge_accumulation == str(
- KnowledgeAccumulationApproach.QUESTION.value
- ):
- logger.info("Compressing knowledge")
- self._update_progress(
- f"Compress Knowledge for: {question}",
- int(question_progress_base + 0),
- {"phase": "analysis"},
- )
- current_knowledge = (
- self.knowledge_generator.compress_knowledge(
- current_knowledge, query, section_links
- )
- )
-
- self._update_progress(
- f"Analysis complete for question: {question}",
- int(question_progress_base + 10),
- {"phase": "analysis_complete"},
- )
- except Exception as e:
- error_msg = f"Error analyzing results: {e!s}"
- logger.exception(f"ANALYSIS ERROR: {error_msg}")
- self._handle_analysis_error(
- e, question, int(question_progress_base + 10)
- )
-
- iteration += 1
-
- self._update_progress(
- f"Compressing knowledge after iteration {iteration}",
- int((iteration / total_iterations) * 100 - 5),
- {"phase": "knowledge_compression"},
- )
-
- if (
- knowledge_accumulation
- == KnowledgeAccumulationApproach.ITERATION.value
- ):
- try:
- logger.info("ITERATION - Compressing Knowledge")
- current_knowledge = (
- self.knowledge_generator.compress_knowledge(
- current_knowledge, query, section_links
- )
- )
- logger.info("FINISHED ITERATION - Compressing Knowledge")
- except Exception as e:
- error_msg = f"Error compressing knowledge: {e!s}"
- logger.exception(f"COMPRESSION ERROR: {error_msg}")
- self._handle_search_error(
- e, query, int((iteration / total_iterations) * 100 - 3)
- )
-
- self._update_progress(
- f"Iteration {iteration} complete",
- int((iteration / total_iterations) * 100),
- {"phase": "iteration_complete", "iteration": iteration},
- )
-
- # Extract content from findings for synthesis
- finding_contents = [
- f["content"] for f in findings if "content" in f
- ]
-
- # First synthesize findings to get coherent content
- synthesized_content = self.findings_repository.synthesize_findings(
- query,
- finding_contents,
- cast(
- List[Union[Dict, str]], findings
- ), # Pass the full findings list with search results
- accumulated_knowledge=current_knowledge,
- old_formatting=False, # Don't format here, just synthesize content
- )
-
- # Transfer questions to the repository
- self.findings_repository.set_questions_by_iteration(
- self.questions_by_iteration
- )
-
- # Now format the findings with search questions and sources
- formatted_findings = (
- self.findings_repository.format_findings_to_text(
- findings, synthesized_content
- )
- )
-
- # Add the synthesized content to the repository
- self.findings_repository.add_finding(query, synthesized_content)
-
- self._update_progress("Research complete", 95, {"phase": "complete"})
-
- return {
- "findings": findings,
- "iterations": iteration,
- "questions": self.questions_by_iteration,
- "formatted_findings": formatted_findings,
- "current_knowledge": current_knowledge,
- }
diff --git a/src/local_deep_research/benchmarks/comparison/evaluator.py b/src/local_deep_research/benchmarks/comparison/evaluator.py
index 63ccb0193c..c1d040186c 100644
--- a/src/local_deep_research/benchmarks/comparison/evaluator.py
+++ b/src/local_deep_research/benchmarks/comparison/evaluator.py
@@ -241,7 +241,7 @@ def _evaluate_single_configuration(
config_search_tool = config.get("search_tool", search_tool)
config_iterations = config.get("iterations", 2)
config_questions_per_iteration = config.get("questions_per_iteration", 2)
- config_search_strategy = config.get("search_strategy", "iterdrag")
+ config_search_strategy = config.get("search_strategy", "source-based")
# Initialize profiling tools
speed_profiler = SpeedProfiler()
diff --git a/src/local_deep_research/benchmarks/metrics/calculation.py b/src/local_deep_research/benchmarks/metrics/calculation.py
index e19b6707f2..2612b6d699 100644
--- a/src/local_deep_research/benchmarks/metrics/calculation.py
+++ b/src/local_deep_research/benchmarks/metrics/calculation.py
@@ -151,7 +151,9 @@ def evaluate_benchmark_quality(
"questions_per_iteration": system_config.get(
"questions_per_iteration", 2
),
- "search_strategy": system_config.get("search_strategy", "iterdrag"),
+ "search_strategy": system_config.get(
+ "search_strategy", "source-based"
+ ),
"search_tool": system_config.get("search_tool", "searxng"),
"model_name": system_config.get("model_name"),
"provider": system_config.get("provider"),
@@ -234,7 +236,7 @@ def measure_execution_time(
questions_per_iteration=system_config.get(
"questions_per_iteration", 2
),
- strategy_name=system_config.get("search_strategy", "iterdrag"),
+ strategy_name=system_config.get("search_strategy", "source-based"),
)
# Run multiple times and calculate average
diff --git a/src/local_deep_research/benchmarks/optimization/api.py b/src/local_deep_research/benchmarks/optimization/api.py
index a35eb0013b..2e4a1919f7 100644
--- a/src/local_deep_research/benchmarks/optimization/api.py
+++ b/src/local_deep_research/benchmarks/optimization/api.py
@@ -120,7 +120,7 @@ def optimize_for_speed(
},
"search_strategy": {
"type": "categorical",
- "choices": ["rapid", "parallel", "source_based"],
+ "choices": ["source-based", "focused-iteration"],
},
}
diff --git a/src/local_deep_research/benchmarks/optimization/optuna_optimizer.py b/src/local_deep_research/benchmarks/optimization/optuna_optimizer.py
index c29040397f..883024f3d2 100644
--- a/src/local_deep_research/benchmarks/optimization/optuna_optimizer.py
+++ b/src/local_deep_research/benchmarks/optimization/optuna_optimizer.py
@@ -282,11 +282,10 @@ class OptunaOptimizer:
"search_strategy": {
"type": "categorical",
"choices": [
- "iterdrag",
- "standard",
- "rapid",
- "parallel",
- "source_based",
+ "source-based",
+ "focused-iteration",
+ "focused-iteration-standard",
+ "topic-organization",
],
},
"max_results": {
@@ -425,7 +424,7 @@ class OptunaOptimizer:
# Extract parameters
iterations = params.get("iterations", 2)
questions_per_iteration = params.get("questions_per_iteration", 2)
- search_strategy = params.get("search_strategy", "iterdrag")
+ search_strategy = params.get("search_strategy", "source-based")
max_results = params.get("max_results", 50)
# Initialize profiling tools
@@ -1135,7 +1134,7 @@ def optimize_for_speed(
},
"search_strategy": {
"type": "categorical",
- "choices": ["rapid", "parallel", "source_based"],
+ "choices": ["source-based", "focused-iteration"],
},
}
diff --git a/src/local_deep_research/constants.py b/src/local_deep_research/constants.py
index 525b16107c..56854ce04e 100644
--- a/src/local_deep_research/constants.py
+++ b/src/local_deep_research/constants.py
@@ -93,7 +93,8 @@ RESEARCH_HISTORY_COLLECTION_DESCRIPTION = (
# --- Available search strategies (UI-facing) ---
# Single source of truth for strategies shown in all UI dropdowns.
# create_strategy() in search_system_factory.py handles additional names
-# (aliases, internal strategies) — this list is purely for the UI.
+# (aliases, internal strategies such as "news_aggregation") — this list is
+# purely for the UI.
AVAILABLE_STRATEGIES: List[Dict[str, str]] = [
{
"name": "source-based",
@@ -110,6 +111,11 @@ AVAILABLE_STRATEGIES: List[Dict[str, str]] = [
"label": "Focused Iteration - Comprehensive (Needs >16,000 context window)",
"description": "Detailed long-form output with citations. Uses standard citation handler for comprehensive answers.",
},
+ {
+ "name": "topic-organization",
+ "label": "Topic Organization (Clusters by topic)",
+ "description": "Clusters sources into topics with lead texts. Organizes research by themes for structured output.",
+ },
{
"name": "mcp",
"label": "MCP ReAct (Agentic research - LLM decides tools)",
@@ -123,136 +129,6 @@ AVAILABLE_STRATEGIES: List[Dict[str, str]] = [
]
-ALL_STRATEGIES: List[Dict[str, str]] = [
- *AVAILABLE_STRATEGIES,
- {
- "name": "iterative-refinement",
- "label": "Iterative Refinement (Progressive refinement)",
- "description": "LLM-guided progressive refinement. Iteratively refines results using evaluation and follow-up queries.",
- },
- {
- "name": "topic-organization",
- "label": "Topic Organization (Clusters by topic)",
- "description": "Clusters sources into topics with lead texts. Organizes research by themes for structured output.",
- },
- {
- "name": "news_aggregation",
- "label": "News Aggregation (Current events)",
- "description": "Specialized for news aggregation and current events.",
- },
- {
- "name": "rapid",
- "label": "Rapid (Quick single-pass search)",
- "description": "Quick single-pass search for fast results. Good for simple queries.",
- },
- {
- "name": "iterative",
- "label": "Iterative (Loop-based reasoning)",
- "description": "Loop-based reasoning with persistent knowledge accumulation and confidence tracking.",
- },
- {
- "name": "parallel",
- "label": "Parallel (Multiple queries simultaneously)",
- "description": "Runs multiple search queries in parallel for comprehensive coverage.",
- },
- {
- "name": "recursive",
- "label": "Recursive (Query decomposition)",
- "description": "Recursive decomposition of complex queries into simpler sub-queries.",
- },
- {
- "name": "adaptive",
- "label": "Adaptive (Step-by-step reasoning)",
- "description": "Adaptive step-by-step reasoning that adjusts strategy based on results.",
- },
- {
- "name": "smart",
- "label": "Smart (Auto sub-query generation)",
- "description": "Smart decomposition with automatic sub-query generation.",
- },
- {
- "name": "standard",
- "label": "Standard (Basic iterative search)",
- "description": "Basic iterative search strategy for general use.",
- },
- {
- "name": "iterdrag",
- "label": "IterDRAG (Iterative retrieval and generation)",
- "description": "IterDRAG strategy for iterative document retrieval and generation.",
- },
- {
- "name": "iterative-reasoning",
- "label": "Iterative Reasoning (Depth-based exploration)",
- "description": "Iterative reasoning with depth-based exploration.",
- },
- {
- "name": "browsecomp",
- "label": "BrowseComp (Confidence-based iteration)",
- "description": "BrowseComp optimized strategy with confidence-based iteration.",
- },
- {
- "name": "evidence",
- "label": "Evidence (Verification with candidate discovery)",
- "description": "Enhanced evidence-based verification with candidate discovery and pattern learning.",
- },
- {
- "name": "constrained",
- "label": "Constrained (Progressive narrowing)",
- "description": "Progressive constraint-based search that narrows candidates step by step.",
- },
- {
- "name": "parallel-constrained",
- "label": "Parallel Constrained (Combined constraint execution)",
- "description": "Parallel constraint-based search with combined constraint execution.",
- },
- {
- "name": "early-stop-constrained",
- "label": "Early Stop Constrained (With early stopping at 99%)",
- "description": "Parallel constraint search with immediate evaluation and early stopping.",
- },
- {
- "name": "smart-query",
- "label": "Smart Query (LLM query generation)",
- "description": "Smart query generation strategy using LLM-generated queries.",
- },
- {
- "name": "dual-confidence",
- "label": "Dual Confidence (Positive/negative/uncertainty scoring)",
- "description": "Dual confidence scoring with positive/negative/uncertainty.",
- },
- {
- "name": "dual-confidence-with-rejection",
- "label": "Dual Confidence + Rejection (Early rejection)",
- "description": "Dual confidence with early rejection of poor candidates.",
- },
- {
- "name": "concurrent-dual-confidence",
- "label": "Concurrent Dual Confidence (Concurrent search & evaluation)",
- "description": "Concurrent search and evaluation with progressive constraint relaxation.",
- },
- {
- "name": "constraint-parallel",
- "label": "Constraint Parallel (Parallel constraint checking)",
- "description": "Parallel constraint checking with entity seeding and direct property search.",
- },
- {
- "name": "modular",
- "label": "Modular (Modular architecture with constraint checking)",
- "description": "Modular architecture using constraint checking and candidate exploration modules.",
- },
- {
- "name": "modular-parallel",
- "label": "Modular Parallel (Modular with parallel exploration)",
- "description": "Modular strategy with parallel exploration.",
- },
- {
- "name": "browsecomp-entity",
- "label": "BrowseComp Entity (Entity-focused with knowledge graph)",
- "description": "Entity-focused search for BrowseComp questions with knowledge graph building.",
- },
-]
-
-
# --- Journal quality scoring thresholds ---
# Used by journal_quality.scoring.derive_quality_score and
# journal_quality.scoring.institution_score_from_h_index. Single source of
@@ -360,15 +236,10 @@ OPENALEX_ENRICHMENT_API_TIMEOUT = 15
JOURNAL_QUALITY_MIN_FREE_DISK_BYTES = 2 * 1024**3
-def get_available_strategies(show_all: bool = False) -> List[Dict[str, str]]:
- """Get the list of available research strategies.
-
- Args:
- show_all: If True, return all strategies including advanced/experimental ones.
+def get_available_strategies() -> List[Dict[str, str]]:
+ """Get the list of available research strategies shown in the UI.
Returns:
List of dictionaries with 'name', 'label', and 'description' keys.
"""
- if show_all:
- return ALL_STRATEGIES.copy()
return AVAILABLE_STRATEGIES.copy()
diff --git a/src/local_deep_research/defaults/default_settings.json b/src/local_deep_research/defaults/default_settings.json
index 51513be109..c40c43e4d5 100644
--- a/src/local_deep_research/defaults/default_settings.json
+++ b/src/local_deep_research/defaults/default_settings.json
@@ -1126,23 +1126,9 @@
"value": 10,
"visible": true
},
- "search.show_all_strategies": {
- "category": "search_parameters",
- "description": "When enabled, all available search strategies (including advanced and experimental ones) are shown in strategy dropdowns. When disabled, only the recommended strategies are shown.",
- "editable": true,
- "max_value": null,
- "min_value": null,
- "name": "Show All Strategies",
- "options": null,
- "step": null,
- "type": "SEARCH",
- "ui_element": "checkbox",
- "value": false,
- "visible": true
- },
"search.search_strategy": {
"category": "search_parameters",
- "description": "Research methodology. 'source-based': Finds and extracts from sources (good for comprehensive research). 'focused-iteration': Uses entity-based progressive exploration (optimized for factual Q&A, ~95% SimpleQA accuracy, requires larger context windows). 'focused-iteration-standard': Comprehensive variant of focused-iteration with broader exploration. 'iterative-refinement': LLM-guided progressive refinement with gap analysis. 'topic-organization': Organizes research around discovered topic clusters. 'mcp': Agentic ReAct-pattern research using MCP tools.",
+ "description": "Research methodology. 'source-based': Finds and extracts from sources (good for comprehensive research). 'focused-iteration': Uses entity-based progressive exploration (optimized for factual Q&A, ~95% SimpleQA accuracy, requires larger context windows). 'focused-iteration-standard': Comprehensive variant of focused-iteration with broader exploration. 'topic-organization': Organizes research around discovered topic clusters. 'mcp': Agentic ReAct-pattern research using MCP tools. 'langgraph-agent': Autonomous agentic research where the LLM decides what to search and when to synthesize.",
"editable": true,
"max_value": null,
"min_value": null,
diff --git a/src/local_deep_research/mcp/server.py b/src/local_deep_research/mcp/server.py
index e831fe7760..8fdf4345ab 100644
--- a/src/local_deep_research/mcp/server.py
+++ b/src/local_deep_research/mcp/server.py
@@ -182,7 +182,7 @@ def _validate_strategy(strategy: Optional[str]) -> Optional[str]:
strategy = strategy.strip()
if not strategy:
return None
- available = get_available_strategies(show_all=True)
+ available = get_available_strategies()
available_names = [s["name"] for s in available]
if strategy not in available_names:
raise ValidationError(
@@ -808,7 +808,7 @@ def list_strategies() -> Dict[str, Any]:
try:
return {
"status": "success",
- "strategies": get_available_strategies(show_all=True),
+ "strategies": get_available_strategies(),
}
except Exception as e:
diff --git a/src/local_deep_research/news/web.py b/src/local_deep_research/news/web.py
index 6450a09747..30bd7eddb8 100644
--- a/src/local_deep_research/news/web.py
+++ b/src/local_deep_research/news/web.py
@@ -27,31 +27,6 @@ def create_news_blueprint():
# Register the API blueprint as sub-blueprint
bp.register_blueprint(news_api_bp) # type: ignore[attr-defined,unused-ignore]
- def _show_all_strategies() -> bool:
- """Check if user has enabled show_all_strategies setting."""
- from flask import session
-
- username = session.get("username", "anonymous")
- if username == "anonymous":
- return False
- try:
- from local_deep_research.database.session_context import (
- get_user_db_session,
- )
- from local_deep_research.utilities.db_utils import (
- get_settings_manager,
- )
-
- with get_user_db_session(username) as db_session:
- settings_manager = get_settings_manager(db_session, username)
- return bool(
- settings_manager.get_setting(
- "search.show_all_strategies", False
- )
- )
- except Exception:
- return False
-
# Page routes
@bp.route("/")
@login_required
@@ -59,9 +34,7 @@ def create_news_blueprint():
"""Render the main news page."""
return render_template(
"pages/news.html",
- strategies=get_available_strategies(
- show_all=_show_all_strategies()
- ),
+ strategies=get_available_strategies(),
)
@bp.route("/subscriptions")
@@ -103,9 +76,7 @@ def create_news_blueprint():
"pages/news-subscription-form.html",
subscription=None,
default_settings=default_settings,
- strategies=get_available_strategies(
- show_all=_show_all_strategies()
- ),
+ strategies=get_available_strategies(),
)
@bp.route("/subscriptions/<subscription_id>/edit")
@@ -143,9 +114,7 @@ def create_news_blueprint():
subscription=None,
error="Subscription not found",
default_settings=default_settings,
- strategies=get_available_strategies(
- show_all=_show_all_strategies()
- ),
+ strategies=get_available_strategies(),
)
# Load user's default settings if logged in
@@ -165,18 +134,14 @@ def create_news_blueprint():
subscription=None,
error="Error loading subscription",
default_settings=default_settings,
- strategies=get_available_strategies(
- show_all=_show_all_strategies()
- ),
+ strategies=get_available_strategies(),
)
return render_template(
"pages/news-subscription-form.html",
subscription=subscription,
default_settings=default_settings,
- strategies=get_available_strategies(
- show_all=_show_all_strategies()
- ),
+ strategies=get_available_strategies(),
)
# Health check
diff --git a/src/local_deep_research/search_system.py b/src/local_deep_research/search_system.py
index 4b49cd2d9b..f14fbc1225 100644
--- a/src/local_deep_research/search_system.py
+++ b/src/local_deep_research/search_system.py
@@ -12,7 +12,6 @@ from .advanced_search_system.strategies.followup.enhanced_contextual_followup im
EnhancedContextualFollowUpStrategy,
)
-# StandardSearchStrategy imported lazily to avoid database access during module import
from .citation_handler import CitationHandler
from .web_search_engines.search_engine_base import BaseSearchEngine
diff --git a/src/local_deep_research/search_system_factory.py b/src/local_deep_research/search_system_factory.py
index 4fd7bc02e3..e6a818d058 100644
--- a/src/local_deep_research/search_system_factory.py
+++ b/src/local_deep_research/search_system_factory.py
@@ -10,7 +10,6 @@ from langchain_core.language_models import BaseChatModel
# Re-export from constants so existing importers don't break
from .constants import ( # noqa: F401
- ALL_STRATEGIES,
AVAILABLE_STRATEGIES,
get_available_strategies,
)
@@ -284,23 +283,7 @@ def create_strategy(
return strategy
- # Iterative reasoning strategy (depth variant)
- if strategy_name_lower in [
- "iterative-reasoning",
- "iterative_reasoning",
- "iterative_reasoning_depth",
- ]:
- from .advanced_search_system.strategies.iterative_reasoning_strategy import (
- IterativeReasoningStrategy,
- )
-
- return IterativeReasoningStrategy(
- model=model,
- search=search,
- all_links_of_system=all_links_of_system,
- )
-
- # News aggregation strategy
+ # News aggregation strategy (used internally by the news subsystem)
if strategy_name_lower in [
"news",
"news_aggregation",
@@ -316,476 +299,6 @@ def create_strategy(
all_links_of_system=all_links_of_system,
)
- # IterDRAG strategy
- if strategy_name_lower == "iterdrag":
- from .advanced_search_system.strategies.iterdrag_strategy import (
- IterDRAGStrategy,
- )
-
- return IterDRAGStrategy(
- model=model,
- search=search,
- all_links_of_system=all_links_of_system,
- settings_snapshot=settings_snapshot,
- )
-
- # Parallel strategy
- if strategy_name_lower == "parallel":
- from .advanced_search_system.strategies.parallel_search_strategy import (
- ParallelSearchStrategy,
- )
-
- return ParallelSearchStrategy(
- model=model,
- search=search,
- include_text_content=kwargs.get("include_text_content", True),
- use_cross_engine_filter=kwargs.get("use_cross_engine_filter", True),
- all_links_of_system=all_links_of_system,
- settings_snapshot=settings_snapshot,
- )
-
- # Rapid strategy
- if strategy_name_lower == "rapid":
- from .advanced_search_system.strategies.rapid_search_strategy import (
- RapidSearchStrategy,
- )
-
- return RapidSearchStrategy(
- model=model,
- search=search,
- all_links_of_system=all_links_of_system,
- settings_snapshot=settings_snapshot,
- )
-
- # Recursive decomposition strategy
- if strategy_name_lower in ["recursive", "recursive-decomposition"]:
- from .advanced_search_system.strategies.recursive_decomposition_strategy import (
- RecursiveDecompositionStrategy,
- )
-
- return RecursiveDecompositionStrategy(
- model=model,
- search=search,
- all_links_of_system=all_links_of_system,
- settings_snapshot=settings_snapshot,
- )
-
- # Iterative reasoning strategy (different from iterative_reasoning_depth)
- if strategy_name_lower == "iterative":
- from .advanced_search_system.strategies.iterative_reasoning_strategy import (
- IterativeReasoningStrategy,
- )
-
- # Get iteration settings from kwargs or use defaults
- max_iterations = kwargs.get("max_iterations", 20)
- questions_per_iteration = kwargs.get("questions_per_iteration", 3)
- search_iterations_per_round = kwargs.get(
- "search_iterations_per_round", 1
- )
-
- return IterativeReasoningStrategy(
- model=model,
- search=search,
- all_links_of_system=all_links_of_system,
- max_iterations=max_iterations,
- confidence_threshold=kwargs.get("confidence_threshold", 0.95),
- search_iterations_per_round=search_iterations_per_round,
- questions_per_search=questions_per_iteration,
- settings_snapshot=settings_snapshot,
- )
-
- # Adaptive decomposition strategy
- if strategy_name_lower == "adaptive":
- from .advanced_search_system.strategies.adaptive_decomposition_strategy import (
- AdaptiveDecompositionStrategy,
- )
-
- return AdaptiveDecompositionStrategy(
- model=model,
- search=search,
- all_links_of_system=all_links_of_system,
- max_steps=kwargs.get("max_steps", kwargs.get("max_iterations", 5)),
- min_confidence=kwargs.get("min_confidence", 0.8),
- source_search_iterations=kwargs.get("source_search_iterations", 2),
- source_questions_per_iteration=kwargs.get(
- "source_questions_per_iteration",
- kwargs.get("questions_per_iteration", 3),
- ),
- settings_snapshot=settings_snapshot,
- )
-
- # Smart decomposition strategy
- if strategy_name_lower == "smart":
- from .advanced_search_system.strategies.smart_decomposition_strategy import (
- SmartDecompositionStrategy,
- )
-
- return SmartDecompositionStrategy(
- model=model,
- search=search,
- all_links_of_system=all_links_of_system,
- max_iterations=kwargs.get("max_iterations", 5),
- source_search_iterations=kwargs.get("source_search_iterations", 2),
- source_questions_per_iteration=kwargs.get(
- "source_questions_per_iteration",
- kwargs.get("questions_per_iteration", 3),
- ),
- settings_snapshot=settings_snapshot,
- )
-
- # BrowseComp optimized strategy
- if strategy_name_lower == "browsecomp":
- from .advanced_search_system.strategies.browsecomp_optimized_strategy import (
- BrowseCompOptimizedStrategy,
- )
-
- return BrowseCompOptimizedStrategy(
- model=model,
- search=search,
- all_links_of_system=all_links_of_system,
- max_browsecomp_iterations=kwargs.get(
- "max_browsecomp_iterations", 15
- ),
- confidence_threshold=kwargs.get("confidence_threshold", 0.9),
- max_iterations=kwargs.get("max_iterations", 5),
- questions_per_iteration=kwargs.get("questions_per_iteration", 3),
- settings_snapshot=settings_snapshot,
- )
-
- # Enhanced evidence-based strategy
- if strategy_name_lower == "evidence":
- from .advanced_search_system.strategies.evidence_based_strategy_v2 import (
- EnhancedEvidenceBasedStrategy,
- )
-
- return EnhancedEvidenceBasedStrategy(
- model=model,
- search=search,
- all_links_of_system=all_links_of_system,
- max_iterations=kwargs.get("max_iterations", 20),
- confidence_threshold=kwargs.get("confidence_threshold", 0.95),
- candidate_limit=kwargs.get("candidate_limit", 20),
- evidence_threshold=kwargs.get("evidence_threshold", 0.9),
- max_search_iterations=kwargs.get("max_search_iterations", 5),
- questions_per_iteration=kwargs.get("questions_per_iteration", 3),
- min_candidates_threshold=kwargs.get("min_candidates_threshold", 10),
- enable_pattern_learning=kwargs.get("enable_pattern_learning", True),
- settings_snapshot=settings_snapshot,
- )
-
- # Constrained search strategy
- if strategy_name_lower == "constrained":
- from .advanced_search_system.strategies.constrained_search_strategy import (
- ConstrainedSearchStrategy,
- )
-
- return ConstrainedSearchStrategy(
- model=model,
- search=search,
- all_links_of_system=all_links_of_system,
- max_iterations=kwargs.get("max_iterations", 20),
- confidence_threshold=kwargs.get("confidence_threshold", 0.95),
- candidate_limit=kwargs.get("candidate_limit", 100),
- evidence_threshold=kwargs.get("evidence_threshold", 0.9),
- max_search_iterations=kwargs.get("max_search_iterations", 5),
- questions_per_iteration=kwargs.get("questions_per_iteration", 3),
- min_candidates_per_stage=kwargs.get("min_candidates_per_stage", 20),
- settings_snapshot=settings_snapshot,
- )
-
- # Parallel constrained strategy
- if strategy_name_lower in [
- "parallel-constrained",
- "parallel_constrained",
- ]:
- from .advanced_search_system.strategies.parallel_constrained_strategy import (
- ParallelConstrainedStrategy,
- )
-
- return ParallelConstrainedStrategy(
- model=model,
- search=search,
- all_links_of_system=all_links_of_system,
- max_iterations=kwargs.get("max_iterations", 20),
- confidence_threshold=kwargs.get("confidence_threshold", 0.95),
- candidate_limit=kwargs.get("candidate_limit", 100),
- evidence_threshold=kwargs.get("evidence_threshold", 0.9),
- max_search_iterations=kwargs.get("max_search_iterations", 5),
- questions_per_iteration=kwargs.get("questions_per_iteration", 3),
- min_candidates_per_stage=kwargs.get("min_candidates_per_stage", 20),
- parallel_workers=kwargs.get("parallel_workers", 100),
- settings_snapshot=settings_snapshot,
- )
-
- # Early stop constrained strategy
- if strategy_name_lower in [
- "early-stop-constrained",
- "early_stop_constrained",
- ]:
- from .advanced_search_system.strategies.early_stop_constrained_strategy import (
- EarlyStopConstrainedStrategy,
- )
-
- return EarlyStopConstrainedStrategy(
- model=model,
- search=search,
- all_links_of_system=all_links_of_system,
- max_iterations=kwargs.get("max_iterations", 20),
- confidence_threshold=kwargs.get("confidence_threshold", 0.95),
- candidate_limit=kwargs.get("candidate_limit", 100),
- evidence_threshold=kwargs.get("evidence_threshold", 0.9),
- max_search_iterations=kwargs.get("max_search_iterations", 5),
- questions_per_iteration=kwargs.get("questions_per_iteration", 3),
- min_candidates_per_stage=kwargs.get("min_candidates_per_stage", 20),
- parallel_workers=kwargs.get("parallel_workers", 100),
- early_stop_threshold=kwargs.get("early_stop_threshold", 0.99),
- concurrent_evaluation=kwargs.get("concurrent_evaluation", True),
- settings_snapshot=settings_snapshot,
- )
-
- # Smart query strategy
- if strategy_name_lower in ["smart-query", "smart_query"]:
- from .advanced_search_system.strategies.smart_query_strategy import (
- SmartQueryStrategy,
- )
-
- return SmartQueryStrategy(
- model=model,
- search=search,
- all_links_of_system=all_links_of_system,
- max_iterations=kwargs.get("max_iterations", 20),
- confidence_threshold=kwargs.get("confidence_threshold", 0.95),
- candidate_limit=kwargs.get("candidate_limit", 100),
- evidence_threshold=kwargs.get("evidence_threshold", 0.9),
- max_search_iterations=kwargs.get("max_search_iterations", 5),
- questions_per_iteration=kwargs.get("questions_per_iteration", 3),
- min_candidates_per_stage=kwargs.get("min_candidates_per_stage", 20),
- parallel_workers=kwargs.get("parallel_workers", 100),
- early_stop_threshold=kwargs.get("early_stop_threshold", 0.99),
- concurrent_evaluation=kwargs.get("concurrent_evaluation", True),
- use_llm_query_generation=kwargs.get(
- "use_llm_query_generation", True
- ),
- queries_per_combination=kwargs.get("queries_per_combination", 3),
- settings_snapshot=settings_snapshot,
- )
-
- # Dual confidence strategy
- if strategy_name_lower in ["dual-confidence", "dual_confidence"]:
- from .advanced_search_system.strategies.dual_confidence_strategy import (
- DualConfidenceStrategy,
- )
-
- return DualConfidenceStrategy(
- model=model,
- search=search,
- all_links_of_system=all_links_of_system,
- max_iterations=kwargs.get("max_iterations", 20),
- confidence_threshold=kwargs.get("confidence_threshold", 0.95),
- candidate_limit=kwargs.get("candidate_limit", 100),
- evidence_threshold=kwargs.get("evidence_threshold", 0.9),
- max_search_iterations=kwargs.get("max_search_iterations", 5),
- questions_per_iteration=kwargs.get("questions_per_iteration", 3),
- min_candidates_per_stage=kwargs.get("min_candidates_per_stage", 20),
- parallel_workers=kwargs.get("parallel_workers", 100),
- early_stop_threshold=kwargs.get("early_stop_threshold", 0.95),
- concurrent_evaluation=kwargs.get("concurrent_evaluation", True),
- use_llm_query_generation=kwargs.get(
- "use_llm_query_generation", True
- ),
- queries_per_combination=kwargs.get("queries_per_combination", 3),
- use_entity_seeding=kwargs.get("use_entity_seeding", True),
- use_direct_property_search=kwargs.get(
- "use_direct_property_search", True
- ),
- uncertainty_penalty=kwargs.get("uncertainty_penalty", 0.2),
- negative_weight=kwargs.get("negative_weight", 0.5),
- settings_snapshot=settings_snapshot,
- )
-
- # Dual confidence with rejection strategy
- if strategy_name_lower in [
- "dual-confidence-with-rejection",
- "dual_confidence_with_rejection",
- ]:
- from .advanced_search_system.strategies.dual_confidence_with_rejection import (
- DualConfidenceWithRejectionStrategy,
- )
-
- return DualConfidenceWithRejectionStrategy(
- model=model,
- search=search,
- all_links_of_system=all_links_of_system,
- max_iterations=kwargs.get("max_iterations", 20),
- confidence_threshold=kwargs.get("confidence_threshold", 0.95),
- candidate_limit=kwargs.get("candidate_limit", 100),
- evidence_threshold=kwargs.get("evidence_threshold", 0.9),
- max_search_iterations=kwargs.get("max_search_iterations", 5),
- questions_per_iteration=kwargs.get("questions_per_iteration", 3),
- min_candidates_per_stage=kwargs.get("min_candidates_per_stage", 20),
- parallel_workers=kwargs.get("parallel_workers", 100),
- early_stop_threshold=kwargs.get("early_stop_threshold", 0.95),
- concurrent_evaluation=kwargs.get("concurrent_evaluation", True),
- use_llm_query_generation=kwargs.get(
- "use_llm_query_generation", True
- ),
- queries_per_combination=kwargs.get("queries_per_combination", 3),
- use_entity_seeding=kwargs.get("use_entity_seeding", True),
- use_direct_property_search=kwargs.get(
- "use_direct_property_search", True
- ),
- uncertainty_penalty=kwargs.get("uncertainty_penalty", 0.2),
- negative_weight=kwargs.get("negative_weight", 0.5),
- rejection_threshold=kwargs.get("rejection_threshold", 0.3),
- positive_threshold=kwargs.get("positive_threshold", 0.2),
- critical_constraint_rejection=kwargs.get(
- "critical_constraint_rejection", 0.2
- ),
- settings_snapshot=settings_snapshot,
- )
-
- # Concurrent dual confidence strategy
- if strategy_name_lower in [
- "concurrent-dual-confidence",
- "concurrent_dual_confidence",
- ]:
- from .advanced_search_system.strategies.concurrent_dual_confidence_strategy import (
- ConcurrentDualConfidenceStrategy,
- )
-
- return ConcurrentDualConfidenceStrategy(
- model=model,
- search=search,
- all_links_of_system=all_links_of_system,
- max_iterations=kwargs.get("max_iterations", 20),
- confidence_threshold=kwargs.get("confidence_threshold", 0.95),
- candidate_limit=kwargs.get("candidate_limit", 100),
- evidence_threshold=kwargs.get("evidence_threshold", 0.9),
- max_search_iterations=kwargs.get("max_search_iterations", 5),
- questions_per_iteration=kwargs.get("questions_per_iteration", 3),
- min_candidates_per_stage=kwargs.get("min_candidates_per_stage", 20),
- parallel_workers=kwargs.get("parallel_workers", 10),
- early_stop_threshold=kwargs.get("early_stop_threshold", 0.95),
- concurrent_evaluation=kwargs.get("concurrent_evaluation", True),
- use_llm_query_generation=kwargs.get(
- "use_llm_query_generation", True
- ),
- queries_per_combination=kwargs.get("queries_per_combination", 3),
- use_entity_seeding=kwargs.get("use_entity_seeding", True),
- use_direct_property_search=kwargs.get(
- "use_direct_property_search", True
- ),
- uncertainty_penalty=kwargs.get("uncertainty_penalty", 0.2),
- negative_weight=kwargs.get("negative_weight", 0.5),
- rejection_threshold=kwargs.get("rejection_threshold", 0.3),
- positive_threshold=kwargs.get("positive_threshold", 0.2),
- critical_constraint_rejection=kwargs.get(
- "critical_constraint_rejection", 0.2
- ),
- min_good_candidates=kwargs.get("min_good_candidates", 3),
- target_candidates=kwargs.get("target_candidates", 5),
- max_candidates=kwargs.get("max_candidates", 10),
- min_score_threshold=kwargs.get("min_score_threshold", 0.65),
- exceptional_score=kwargs.get("exceptional_score", 0.95),
- quality_plateau_threshold=kwargs.get(
- "quality_plateau_threshold", 0.1
- ),
- max_search_time=kwargs.get("max_search_time", 30.0),
- max_evaluations=kwargs.get("max_evaluations", 30),
- settings_snapshot=settings_snapshot,
- )
-
- # Constraint parallel strategy
- if strategy_name_lower in [
- "constraint-parallel",
- "constraint_parallel",
- ]:
- from .advanced_search_system.strategies.constraint_parallel_strategy import (
- ConstraintParallelStrategy,
- )
-
- return ConstraintParallelStrategy(
- model=model,
- search=search,
- all_links_of_system=all_links_of_system,
- max_iterations=kwargs.get("max_iterations", 20),
- confidence_threshold=kwargs.get("confidence_threshold", 0.95),
- candidate_limit=kwargs.get("candidate_limit", 100),
- evidence_threshold=kwargs.get("evidence_threshold", 0.9),
- max_search_iterations=kwargs.get("max_search_iterations", 5),
- questions_per_iteration=kwargs.get("questions_per_iteration", 3),
- min_candidates_per_stage=kwargs.get("min_candidates_per_stage", 20),
- parallel_workers=kwargs.get("parallel_workers", 100),
- early_stop_threshold=kwargs.get("early_stop_threshold", 0.95),
- concurrent_evaluation=kwargs.get("concurrent_evaluation", True),
- use_llm_query_generation=kwargs.get(
- "use_llm_query_generation", True
- ),
- queries_per_combination=kwargs.get("queries_per_combination", 3),
- use_entity_seeding=kwargs.get("use_entity_seeding", True),
- use_direct_property_search=kwargs.get(
- "use_direct_property_search", True
- ),
- uncertainty_penalty=kwargs.get("uncertainty_penalty", 0.2),
- negative_weight=kwargs.get("negative_weight", 0.5),
- rejection_threshold=kwargs.get("rejection_threshold", 0.3),
- positive_threshold=kwargs.get("positive_threshold", 0.2),
- critical_constraint_rejection=kwargs.get(
- "critical_constraint_rejection", 0.2
- ),
- settings_snapshot=settings_snapshot,
- )
-
- # Modular strategy
- if strategy_name_lower in ["modular", "modular-strategy"]:
- from .advanced_search_system.strategies.modular_strategy import (
- ModularStrategy,
- )
-
- return ModularStrategy(
- model=model,
- search=search,
- all_links_of_system=all_links_of_system,
- constraint_checker_type=kwargs.get(
- "constraint_checker_type", "dual_confidence"
- ),
- exploration_strategy=kwargs.get("exploration_strategy", "adaptive"),
- early_rejection=kwargs.get("early_rejection", True),
- early_stopping=kwargs.get("early_stopping", True),
- llm_constraint_processing=kwargs.get(
- "llm_constraint_processing", True
- ),
- immediate_evaluation=kwargs.get("immediate_evaluation", True),
- settings_snapshot=settings_snapshot,
- )
-
- # Modular parallel strategy
- if strategy_name_lower in ["modular-parallel", "modular_parallel"]:
- from .advanced_search_system.strategies.modular_strategy import (
- ModularStrategy,
- )
-
- return ModularStrategy(
- model=model,
- search=search,
- all_links_of_system=all_links_of_system,
- constraint_checker_type="dual_confidence",
- exploration_strategy="parallel",
- settings_snapshot=settings_snapshot,
- )
-
- # BrowseComp entity strategy
- if strategy_name_lower in ["browsecomp-entity", "browsecomp_entity"]:
- from .advanced_search_system.strategies.browsecomp_entity_strategy import (
- BrowseCompEntityStrategy,
- )
-
- return BrowseCompEntityStrategy(
- model=model,
- search=search,
- all_links_of_system=all_links_of_system,
- )
-
# Topic organization strategy
if strategy_name_lower in [
"topic-organization",
@@ -822,54 +335,6 @@ def create_strategy(
generate_text=kwargs.get("generate_text", True),
)
- # Iterative refinement strategy
- if strategy_name_lower in [
- "iterative-refinement",
- "iterative_refinement",
- ]:
- from .advanced_search_system.strategies.iterative_refinement_strategy import (
- IterativeRefinementStrategy,
- )
-
- # Get the initial strategy to use (default to source-based)
- initial_strategy_name = kwargs.get("initial_strategy", "source-based")
-
- # Create the initial strategy
- initial_strategy = create_strategy(
- strategy_name=initial_strategy_name,
- model=model,
- search=search,
- all_links_of_system=[], # Fresh list for initial strategy
- settings_snapshot=settings_snapshot,
- search_original_query=kwargs.get("search_original_query", True),
- )
-
- return IterativeRefinementStrategy(
- model=model,
- search=search,
- initial_strategy=initial_strategy,
- all_links_of_system=all_links_of_system,
- settings_snapshot=settings_snapshot,
- evaluation_frequency=kwargs.get("evaluation_frequency", 1),
- max_refinements=kwargs.get("max_refinements", 3),
- confidence_threshold=kwargs.get(
- "confidence_threshold", 0.95
- ), # Increased from 0.8
- )
-
- # Standard strategy
- if strategy_name_lower == "standard":
- from .advanced_search_system.strategies.standard_strategy import (
- StandardSearchStrategy,
- )
-
- return StandardSearchStrategy(
- model=model,
- search=search,
- all_links_of_system=all_links_of_system,
- settings_snapshot=settings_snapshot,
- )
-
# MCP strategy (ReAct pattern - agentic research)
if strategy_name_lower in ["mcp", "agentic"]:
from .advanced_search_system.strategies.mcp_strategy import (
diff --git a/src/local_deep_research/settings/manager.py b/src/local_deep_research/settings/manager.py
index 64b840321f..f4d9bbf715 100644
--- a/src/local_deep_research/settings/manager.py
+++ b/src/local_deep_research/settings/manager.py
@@ -471,13 +471,7 @@ class SettingsManager(ISettingsManager):
if "search.search_strategy" in settings:
from local_deep_research.constants import get_available_strategies
- # Check the show_all_strategies setting to decide which list
- show_all = False
- if "search.show_all_strategies" in settings:
- val = settings["search.show_all_strategies"].get("value", False)
- show_all = val is True or val == "true"
-
- strategies = get_available_strategies(show_all=show_all)
+ strategies = get_available_strategies()
settings["search.search_strategy"]["options"] = [
{"label": s["label"], "value": s["name"]} for s in strategies
]
@@ -892,11 +886,7 @@ class SettingsManager(ISettingsManager):
if "search.search_strategy" in result:
from local_deep_research.constants import get_available_strategies
- show_all_val = result.get("search.show_all_strategies", {}).get(
- "value", False
- )
- show_all = show_all_val is True or show_all_val == "true"
- strategies = get_available_strategies(show_all=show_all)
+ strategies = get_available_strategies()
result["search.search_strategy"]["options"] = [
{"label": s["label"], "value": s["name"]} for s in strategies
]
diff --git a/src/local_deep_research/web/app_factory.py b/src/local_deep_research/web/app_factory.py
index bfb9f1f39b..ccf93dd180 100644
--- a/src/local_deep_research/web/app_factory.py
+++ b/src/local_deep_research/web/app_factory.py
@@ -568,7 +568,6 @@ def register_blueprints(app):
# Load current settings from database using proper session context
username = session.get("username")
settings = {}
- show_all = False
with get_user_db_session(username) as db_session:
if db_session:
settings_manager = get_settings_manager(db_session, username)
@@ -602,9 +601,6 @@ def register_blueprints(app):
"search.search_strategy", "source-based"
),
}
- show_all = settings_manager.get_setting(
- "search.show_all_strategies", False
- )
# Debug logging
log_settings(settings, "Research page settings loaded")
@@ -612,7 +608,7 @@ def register_blueprints(app):
return render_template_with_defaults(
"pages/research.html",
settings=settings,
- strategies=get_available_strategies(show_all=bool(show_all)),
+ strategies=get_available_strategies(),
)
# Register auth blueprint FIRST (so login page is accessible)
diff --git a/tests/advanced_search_system/constraint_checking/__init__.py b/tests/advanced_search_system/constraint_checking/__init__.py
deleted file mode 100644
index bacf918f0c..0000000000
--- a/tests/advanced_search_system/constraint_checking/__init__.py
+++ /dev/null
@@ -1 +0,0 @@
-"""Tests for constraint checking modules."""
diff --git a/tests/advanced_search_system/constraint_checking/test_base_checker_pure_logic.py b/tests/advanced_search_system/constraint_checking/test_base_checker_pure_logic.py
deleted file mode 100644
index 4a67782f2d..0000000000
--- a/tests/advanced_search_system/constraint_checking/test_base_checker_pure_logic.py
+++ /dev/null
@@ -1,206 +0,0 @@
-"""
-Pure-logic tests for BaseConstraintChecker helper methods.
-
-Tests _calculate_weighted_score and _log_constraint_result — no LLM or
-search calls.
-"""
-
-from unittest.mock import Mock, patch
-
-from local_deep_research.advanced_search_system.candidates.base_candidate import (
- Candidate,
-)
-from local_deep_research.advanced_search_system.constraint_checking.base_constraint_checker import (
- BaseConstraintChecker,
-)
-from local_deep_research.advanced_search_system.constraints.base_constraint import (
- Constraint,
- ConstraintType,
-)
-
-
-def _make_checker():
- """Build a minimal BaseConstraintChecker with abstract methods stubbed."""
-
- # Subclass to implement abstract methods
- class ConcreteChecker(BaseConstraintChecker):
- def check_candidate(self, candidate, constraints):
- pass
-
- def should_reject_candidate(self, candidate, constraint, evidence_data):
- pass
-
- model = Mock()
- return ConcreteChecker(model=model)
-
-
-def _constraint(value="test"):
- return Constraint(
- id="c1",
- type=ConstraintType.PROPERTY,
- description=value,
- value=value,
- weight=1.0,
- )
-
-
-# ---------------------------------------------------------------------------
-# _calculate_weighted_score
-# ---------------------------------------------------------------------------
-
-
-class TestCalculateWeightedScore:
- """Verify weighted average calculation."""
-
- def test_empty_scores_returns_zero(self):
- """Empty score list returns 0.0."""
- checker = _make_checker()
- assert checker._calculate_weighted_score([], []) == 0.0
-
- def test_empty_scores_nonempty_weights(self):
- """Empty scores with non-empty weights returns 0.0."""
- checker = _make_checker()
- assert checker._calculate_weighted_score([], [1.0, 2.0]) == 0.0
-
- def test_nonempty_scores_empty_weights(self):
- """Non-empty scores with empty weights returns 0.0."""
- checker = _make_checker()
- assert checker._calculate_weighted_score([0.5, 0.8], []) == 0.0
-
- def test_equal_weights(self):
- """Equal weights produce simple average."""
- checker = _make_checker()
- result = checker._calculate_weighted_score([0.8, 0.6], [1.0, 1.0])
- assert abs(result - 0.7) < 1e-9
-
- def test_different_weights(self):
- """Different weights produce weighted average."""
- checker = _make_checker()
- # (0.8 * 2.0 + 0.4 * 1.0) / (2.0 + 1.0) = 2.0 / 3.0 = 0.667
- result = checker._calculate_weighted_score([0.8, 0.4], [2.0, 1.0])
- assert abs(result - 2.0 / 3.0) < 1e-9
-
- def test_single_score(self):
- """Single score returns that score."""
- checker = _make_checker()
- result = checker._calculate_weighted_score([0.9], [1.0])
- assert abs(result - 0.9) < 1e-9
-
- def test_zero_scores(self):
- """All-zero scores return 0.0."""
- checker = _make_checker()
- result = checker._calculate_weighted_score([0.0, 0.0], [1.0, 1.0])
- assert result == 0.0
-
- def test_mismatched_lengths(self):
- """Shorter list determines pairing (zip behavior)."""
- checker = _make_checker()
- # zip stops at shorter: (0.8*1.0) / (1.0) = 0.8
- result = checker._calculate_weighted_score([0.8, 0.6], [1.0])
- # sum(weights) is 1.0 since zip truncates
- assert abs(result - 0.8) < 1e-9
-
-
-# ---------------------------------------------------------------------------
-# _log_constraint_result
-# ---------------------------------------------------------------------------
-
-
-class TestLogConstraintResult:
- """Verify logging symbols for different score levels."""
-
- def test_high_score_checkmark(self):
- """Score >= 0.8 logs checkmark symbol."""
- checker = _make_checker()
- candidate = Candidate(name="Test")
- constraint = _constraint("height")
- with patch(
- "local_deep_research.advanced_search_system.constraint_checking.base_constraint_checker.logger"
- ) as mock_logger:
- checker._log_constraint_result(candidate, constraint, 0.85, {})
- call_args = mock_logger.info.call_args[0][0]
- assert "✓" in call_args
-
- def test_medium_score_circle(self):
- """Score >= 0.5 and < 0.8 logs circle symbol."""
- checker = _make_checker()
- candidate = Candidate(name="Test")
- constraint = _constraint("weight")
- with patch(
- "local_deep_research.advanced_search_system.constraint_checking.base_constraint_checker.logger"
- ) as mock_logger:
- checker._log_constraint_result(candidate, constraint, 0.6, {})
- call_args = mock_logger.info.call_args[0][0]
- assert "○" in call_args
-
- def test_low_score_cross(self):
- """Score < 0.5 logs cross symbol."""
- checker = _make_checker()
- candidate = Candidate(name="Test")
- constraint = _constraint("color")
- with patch(
- "local_deep_research.advanced_search_system.constraint_checking.base_constraint_checker.logger"
- ) as mock_logger:
- checker._log_constraint_result(candidate, constraint, 0.3, {})
- call_args = mock_logger.info.call_args[0][0]
- assert "✗" in call_args
-
- def test_includes_candidate_name(self):
- """Log message includes candidate name."""
- checker = _make_checker()
- candidate = Candidate(name="Mount Rainier")
- constraint = _constraint("elevation")
- with patch(
- "local_deep_research.advanced_search_system.constraint_checking.base_constraint_checker.logger"
- ) as mock_logger:
- checker._log_constraint_result(candidate, constraint, 0.7, {})
- call_args = mock_logger.info.call_args[0][0]
- assert "Mount Rainier" in call_args
-
- def test_includes_constraint_value(self):
- """Log message includes constraint value."""
- checker = _make_checker()
- candidate = Candidate(name="Test")
- constraint = _constraint("over 14000 ft")
- with patch(
- "local_deep_research.advanced_search_system.constraint_checking.base_constraint_checker.logger"
- ) as mock_logger:
- checker._log_constraint_result(candidate, constraint, 0.9, {})
- call_args = mock_logger.info.call_args[0][0]
- assert "over 14000 ft" in call_args
-
- def test_includes_percentage(self):
- """Log message includes score as percentage."""
- checker = _make_checker()
- candidate = Candidate(name="Test")
- constraint = _constraint("test")
- with patch(
- "local_deep_research.advanced_search_system.constraint_checking.base_constraint_checker.logger"
- ) as mock_logger:
- checker._log_constraint_result(candidate, constraint, 0.75, {})
- call_args = mock_logger.info.call_args[0][0]
- assert "75%" in call_args
-
- def test_boundary_score_08(self):
- """Exactly 0.8 gets checkmark."""
- checker = _make_checker()
- candidate = Candidate(name="Test")
- constraint = _constraint("test")
- with patch(
- "local_deep_research.advanced_search_system.constraint_checking.base_constraint_checker.logger"
- ) as mock_logger:
- checker._log_constraint_result(candidate, constraint, 0.8, {})
- call_args = mock_logger.info.call_args[0][0]
- assert "✓" in call_args
-
- def test_boundary_score_05(self):
- """Exactly 0.5 gets circle."""
- checker = _make_checker()
- candidate = Candidate(name="Test")
- constraint = _constraint("test")
- with patch(
- "local_deep_research.advanced_search_system.constraint_checking.base_constraint_checker.logger"
- ) as mock_logger:
- checker._log_constraint_result(candidate, constraint, 0.5, {})
- call_args = mock_logger.info.call_args[0][0]
- assert "○" in call_args
diff --git a/tests/advanced_search_system/constraint_checking/test_base_constraint_checker.py b/tests/advanced_search_system/constraint_checking/test_base_constraint_checker.py
deleted file mode 100644
index 5f9fa801c0..0000000000
--- a/tests/advanced_search_system/constraint_checking/test_base_constraint_checker.py
+++ /dev/null
@@ -1,202 +0,0 @@
-"""
-Tests for the BaseConstraintChecker class and ConstraintCheckResult.
-
-Tests cover:
-- ConstraintCheckResult dataclass
-- BaseConstraintChecker initialization
-- Evidence gathering
-- Weighted score calculation
-"""
-
-from unittest.mock import Mock
-from dataclasses import dataclass
-
-
-@dataclass
-class MockCandidate:
- """Mock candidate for testing."""
-
- name: str
- value: str = ""
-
-
-@dataclass
-class MockConstraint:
- """Mock constraint for testing."""
-
- value: str
- weight: float = 1.0
-
-
-class ConcreteConstraintChecker:
- """Concrete implementation for testing the base pattern."""
-
- def __init__(self, model, evidence_gatherer=None, **kwargs):
- self.model = model
- self.evidence_gatherer = evidence_gatherer
-
- def check_candidate(self, candidate, constraints):
- return {
- "candidate": candidate,
- "total_score": 0.8,
- "constraint_scores": {},
- "should_reject": False,
- "rejection_reason": None,
- "detailed_results": [],
- }
-
- def should_reject_candidate(self, candidate, constraint, evidence_data):
- return False, ""
-
- def _gather_evidence_for_constraint(self, candidate, constraint):
- if self.evidence_gatherer:
- return self.evidence_gatherer(candidate, constraint)
- return []
-
- def _calculate_weighted_score(self, constraint_scores, weights):
- if not constraint_scores or not weights:
- return 0.0
- return sum(
- s * w for s, w in zip(constraint_scores, weights, strict=False)
- ) / sum(weights)
-
-
-class TestConstraintCheckResult:
- """Tests for ConstraintCheckResult dataclass."""
-
- def test_result_dataclass_creation(self):
- """ConstraintCheckResult can be created with all fields."""
- from local_deep_research.advanced_search_system.constraint_checking.base_constraint_checker import (
- ConstraintCheckResult,
- )
-
- candidate = MockCandidate(name="Test")
- result = ConstraintCheckResult(
- candidate=candidate,
- total_score=0.85,
- constraint_scores={"constraint1": {"score": 0.9}},
- should_reject=False,
- rejection_reason=None,
- detailed_results=[],
- )
-
- assert result.candidate == candidate
- assert result.total_score == 0.85
- assert result.should_reject is False
-
- def test_result_with_rejection(self):
- """ConstraintCheckResult can store rejection info."""
- from local_deep_research.advanced_search_system.constraint_checking.base_constraint_checker import (
- ConstraintCheckResult,
- )
-
- candidate = MockCandidate(name="Rejected")
- result = ConstraintCheckResult(
- candidate=candidate,
- total_score=0.3,
- constraint_scores={},
- should_reject=True,
- rejection_reason="Failed minimum threshold",
- detailed_results=[],
- )
-
- assert result.should_reject is True
- assert "threshold" in result.rejection_reason.lower()
-
-
-class TestBaseConstraintCheckerInit:
- """Tests for BaseConstraintChecker initialization."""
-
- def test_init_stores_model(self):
- """Checker stores the model reference."""
- mock_model = Mock()
- checker = ConcreteConstraintChecker(mock_model)
-
- assert checker.model is mock_model
-
- def test_init_stores_evidence_gatherer(self):
- """Checker stores the evidence gatherer function."""
- mock_model = Mock()
- mock_gatherer = Mock()
- checker = ConcreteConstraintChecker(
- mock_model, evidence_gatherer=mock_gatherer
- )
-
- assert checker.evidence_gatherer is mock_gatherer
-
- def test_init_without_evidence_gatherer(self):
- """Checker can be initialized without evidence gatherer."""
- mock_model = Mock()
- checker = ConcreteConstraintChecker(mock_model)
-
- assert checker.evidence_gatherer is None
-
-
-class TestGatherEvidenceForConstraint:
- """Tests for _gather_evidence_for_constraint method."""
-
- def test_gather_evidence_calls_gatherer(self):
- """Method calls evidence gatherer with correct args."""
- mock_model = Mock()
- mock_gatherer = Mock(return_value=[{"evidence": "data"}])
-
- checker = ConcreteConstraintChecker(
- mock_model, evidence_gatherer=mock_gatherer
- )
-
- candidate = MockCandidate(name="Test")
- constraint = MockConstraint(value="constraint")
-
- result = checker._gather_evidence_for_constraint(candidate, constraint)
-
- mock_gatherer.assert_called_once_with(candidate, constraint)
- assert result == [{"evidence": "data"}]
-
- def test_gather_evidence_without_gatherer(self):
- """Method returns empty list when no gatherer."""
- mock_model = Mock()
- checker = ConcreteConstraintChecker(mock_model)
-
- candidate = MockCandidate(name="Test")
- constraint = MockConstraint(value="constraint")
-
- result = checker._gather_evidence_for_constraint(candidate, constraint)
-
- assert result == []
-
-
-class TestCheckCandidate:
- """Tests for check_candidate method."""
-
- def test_check_candidate_returns_result(self):
- """check_candidate returns a result dict."""
- mock_model = Mock()
- checker = ConcreteConstraintChecker(mock_model)
-
- candidate = MockCandidate(name="Test")
- constraints = [MockConstraint(value="c1")]
-
- result = checker.check_candidate(candidate, constraints)
-
- assert "candidate" in result
- assert "total_score" in result
- assert "should_reject" in result
-
-
-class TestShouldRejectCandidate:
- """Tests for should_reject_candidate method."""
-
- def test_should_reject_returns_tuple(self):
- """should_reject_candidate returns (bool, str) tuple."""
- mock_model = Mock()
- checker = ConcreteConstraintChecker(mock_model)
-
- candidate = MockCandidate(name="Test")
- constraint = MockConstraint(value="c1")
-
- result = checker.should_reject_candidate(candidate, constraint, {})
-
- assert isinstance(result, tuple)
- assert len(result) == 2
- assert isinstance(result[0], bool)
- assert isinstance(result[1], str)
diff --git a/tests/advanced_search_system/constraint_checking/test_constraint_checker_orchestration.py b/tests/advanced_search_system/constraint_checking/test_constraint_checker_orchestration.py
deleted file mode 100644
index 7973c05d9a..0000000000
--- a/tests/advanced_search_system/constraint_checking/test_constraint_checker_orchestration.py
+++ /dev/null
@@ -1,401 +0,0 @@
-"""
-Tests for ConstraintChecker.check_candidate orchestration logic.
-
-Existing tests only cover a mock ConcreteConstraintChecker, not the real
-ConstraintChecker with its no-evidence fallback, rejection override, and
-weighted average calculation.
-
-Source: src/local_deep_research/advanced_search_system/constraint_checking/constraint_checker.py
-"""
-
-from unittest.mock import Mock, patch
-
-import pytest
-
-from local_deep_research.advanced_search_system.constraint_checking.constraint_checker import (
- ConstraintChecker,
- ConstraintCheckResult,
-)
-
-
-# ---------------------------------------------------------------------------
-# Helpers
-# ---------------------------------------------------------------------------
-
-
-def _make_constraint(value="test_constraint", weight=1.0, type_val="hard"):
- """Create a mock Constraint."""
- c = Mock()
- c.value = value
- c.weight = weight
- c.type = Mock()
- c.type.value = type_val
- return c
-
-
-def _make_candidate(name="test_candidate"):
- """Create a mock Candidate."""
- c = Mock()
- c.name = name
- return c
-
-
-def _make_dual_evidence(positive=0.8, negative=0.1, uncertainty=0.1):
- """Create a mock DualConfidenceEvidence result."""
- e = Mock()
- e.positive_confidence = positive
- e.negative_confidence = negative
- e.uncertainty = uncertainty
- return e
-
-
-# ---------------------------------------------------------------------------
-# No-evidence fallback
-# ---------------------------------------------------------------------------
-
-
-class TestNoEvidenceFallback:
- """When no evidence is found, score = 0.5 - uncertainty_penalty."""
-
- @patch(
- "local_deep_research.advanced_search_system.constraint_checking.constraint_checker.EvidenceAnalyzer"
- )
- @patch(
- "local_deep_research.advanced_search_system.constraint_checking.constraint_checker.RejectionEngine"
- )
- def test_default_uncertainty_penalty(
- self, mock_rejection_cls, mock_analyzer_cls
- ):
- """Default penalty 0.2: score = 0.5 - 0.2 = 0.3."""
- mock_rejection = Mock()
- mock_rejection.check_all_constraints.return_value = Mock(
- should_reject=False
- )
- mock_rejection_cls.return_value = mock_rejection
-
- model = Mock()
- checker = ConstraintChecker(model, evidence_gatherer=lambda c, con: [])
-
- candidate = _make_candidate()
- constraint = _make_constraint(weight=1.0)
-
- result = checker.check_candidate(candidate, [constraint])
-
- assert result.constraint_scores["test_constraint"][
- "total"
- ] == pytest.approx(0.3)
- assert result.constraint_scores["test_constraint"]["positive"] == 0.0
- assert result.constraint_scores["test_constraint"]["negative"] == 0.0
- assert result.constraint_scores["test_constraint"]["uncertainty"] == 1.0
-
- @patch(
- "local_deep_research.advanced_search_system.constraint_checking.constraint_checker.EvidenceAnalyzer"
- )
- @patch(
- "local_deep_research.advanced_search_system.constraint_checking.constraint_checker.RejectionEngine"
- )
- def test_custom_uncertainty_penalty(
- self, mock_rejection_cls, mock_analyzer_cls
- ):
- """Custom penalty 0.4: score = 0.5 - 0.4 = 0.1."""
- mock_rejection = Mock()
- mock_rejection.check_all_constraints.return_value = Mock(
- should_reject=False
- )
- mock_rejection_cls.return_value = mock_rejection
-
- model = Mock()
- checker = ConstraintChecker(
- model,
- evidence_gatherer=lambda c, con: [],
- uncertainty_penalty=0.4,
- )
-
- candidate = _make_candidate()
- constraint = _make_constraint(weight=1.0)
-
- result = checker.check_candidate(candidate, [constraint])
-
- assert result.constraint_scores["test_constraint"][
- "total"
- ] == pytest.approx(0.1)
-
- @patch(
- "local_deep_research.advanced_search_system.constraint_checking.constraint_checker.EvidenceAnalyzer"
- )
- @patch(
- "local_deep_research.advanced_search_system.constraint_checking.constraint_checker.RejectionEngine"
- )
- def test_multiple_no_evidence_weighted_average(
- self, mock_rejection_cls, mock_analyzer_cls
- ):
- """Multiple no-evidence constraints: weighted average of fallback scores."""
- mock_rejection = Mock()
- mock_rejection.check_all_constraints.return_value = Mock(
- should_reject=False
- )
- mock_rejection_cls.return_value = mock_rejection
-
- model = Mock()
- checker = ConstraintChecker(
- model,
- evidence_gatherer=lambda c, con: [],
- uncertainty_penalty=0.2,
- )
-
- candidate = _make_candidate()
- c1 = _make_constraint("c1", weight=1.0)
- c2 = _make_constraint("c2", weight=2.0)
-
- result = checker.check_candidate(candidate, [c1, c2])
-
- # Both have score 0.3, weights 1.0 and 2.0
- # Weighted avg = (0.3*1 + 0.3*2) / 3 = 0.3
- assert result.total_score == pytest.approx(0.3)
-
-
-# ---------------------------------------------------------------------------
-# Evidence gatherer
-# ---------------------------------------------------------------------------
-
-
-class TestEvidenceGatherer:
- """Evidence gatherer is called correctly."""
-
- @patch(
- "local_deep_research.advanced_search_system.constraint_checking.constraint_checker.EvidenceAnalyzer"
- )
- @patch(
- "local_deep_research.advanced_search_system.constraint_checking.constraint_checker.RejectionEngine"
- )
- def test_called_once_per_constraint(
- self, mock_rejection_cls, mock_analyzer_cls
- ):
- """Evidence gatherer is called once per constraint."""
- mock_rejection = Mock()
- mock_rejection.check_all_constraints.return_value = Mock(
- should_reject=False
- )
- mock_rejection_cls.return_value = mock_rejection
-
- mock_analyzer = Mock()
- mock_analyzer.analyze_evidence_dual_confidence.return_value = (
- _make_dual_evidence()
- )
- mock_analyzer.evaluate_evidence_list.return_value = 0.8
- mock_analyzer_cls.return_value = mock_analyzer
-
- gatherer = Mock(return_value=[{"text": "evidence"}])
- model = Mock()
- checker = ConstraintChecker(model, evidence_gatherer=gatherer)
-
- candidate = _make_candidate()
- c1 = _make_constraint("c1")
- c2 = _make_constraint("c2")
-
- checker.check_candidate(candidate, [c1, c2])
-
- assert gatherer.call_count == 2
- gatherer.assert_any_call(candidate, c1)
- gatherer.assert_any_call(candidate, c2)
-
- @patch(
- "local_deep_research.advanced_search_system.constraint_checking.constraint_checker.EvidenceAnalyzer"
- )
- @patch(
- "local_deep_research.advanced_search_system.constraint_checking.constraint_checker.RejectionEngine"
- )
- def test_no_gatherer_returns_empty(
- self, mock_rejection_cls, mock_analyzer_cls
- ):
- """No evidence gatherer provided returns empty evidence."""
- mock_rejection = Mock()
- mock_rejection.check_all_constraints.return_value = Mock(
- should_reject=False
- )
- mock_rejection_cls.return_value = mock_rejection
-
- model = Mock()
- checker = ConstraintChecker(model) # No gatherer
-
- candidate = _make_candidate()
- constraint = _make_constraint()
-
- result = checker.check_candidate(candidate, [constraint])
-
- # No evidence -> fallback score
- assert result.constraint_scores["test_constraint"]["uncertainty"] == 1.0
-
-
-# ---------------------------------------------------------------------------
-# Rejection override
-# ---------------------------------------------------------------------------
-
-
-class TestRejectionOverride:
- """Rejection sets total_score to 0.0."""
-
- @patch(
- "local_deep_research.advanced_search_system.constraint_checking.constraint_checker.EvidenceAnalyzer"
- )
- @patch(
- "local_deep_research.advanced_search_system.constraint_checking.constraint_checker.RejectionEngine"
- )
- def test_rejection_sets_score_zero(
- self, mock_rejection_cls, mock_analyzer_cls
- ):
- """When rejection_result.should_reject=True, total_score=0.0."""
- mock_rejection = Mock()
- mock_rejection.check_all_constraints.return_value = Mock(
- should_reject=True
- )
- mock_rejection_cls.return_value = mock_rejection
-
- mock_analyzer = Mock()
- mock_analyzer.analyze_evidence_dual_confidence.return_value = (
- _make_dual_evidence(0.9, 0.0, 0.1)
- )
- mock_analyzer.evaluate_evidence_list.return_value = 0.9
- mock_analyzer_cls.return_value = mock_analyzer
-
- model = Mock()
- checker = ConstraintChecker(
- model,
- evidence_gatherer=lambda c, con: [{"text": "strong evidence"}],
- )
-
- candidate = _make_candidate()
- constraint = _make_constraint(weight=1.0)
-
- result = checker.check_candidate(candidate, [constraint])
-
- assert result.total_score == 0.0
- assert result.rejection_result.should_reject is True
-
-
-# ---------------------------------------------------------------------------
-# Weighted average calculation
-# ---------------------------------------------------------------------------
-
-
-class TestWeightedAverage:
- """Non-rejection weighted average score calculation."""
-
- @patch(
- "local_deep_research.advanced_search_system.constraint_checking.constraint_checker.EvidenceAnalyzer"
- )
- @patch(
- "local_deep_research.advanced_search_system.constraint_checking.constraint_checker.RejectionEngine"
- )
- def test_weighted_average_calculation(
- self, mock_rejection_cls, mock_analyzer_cls
- ):
- """(0.8*1.0 + 0.4*2.0) / (1.0+2.0) = 0.533."""
- mock_rejection = Mock()
- mock_rejection.check_all_constraints.return_value = Mock(
- should_reject=False
- )
- mock_rejection_cls.return_value = mock_rejection
-
- mock_analyzer = Mock()
- call_count = [0]
-
- def side_effect_eval(evidence_list, constraint, penalty, neg_weight):
- call_count[0] += 1
- return 0.8 if call_count[0] == 1 else 0.4
-
- mock_analyzer.analyze_evidence_dual_confidence.return_value = (
- _make_dual_evidence()
- )
- mock_analyzer.evaluate_evidence_list.side_effect = side_effect_eval
- mock_analyzer_cls.return_value = mock_analyzer
-
- model = Mock()
- checker = ConstraintChecker(
- model,
- evidence_gatherer=lambda c, con: [{"text": "evidence"}],
- )
-
- candidate = _make_candidate()
- c1 = _make_constraint("c1", weight=1.0)
- c2 = _make_constraint("c2", weight=2.0)
-
- result = checker.check_candidate(candidate, [c1, c2])
-
- expected = (0.8 * 1.0 + 0.4 * 2.0) / (1.0 + 2.0)
- assert result.total_score == pytest.approx(expected, abs=0.01)
-
-
-# ---------------------------------------------------------------------------
-# Empty constraints
-# ---------------------------------------------------------------------------
-
-
-class TestEmptyConstraints:
- """Empty constraints list produces total_score = 0.0."""
-
- @patch(
- "local_deep_research.advanced_search_system.constraint_checking.constraint_checker.EvidenceAnalyzer"
- )
- @patch(
- "local_deep_research.advanced_search_system.constraint_checking.constraint_checker.RejectionEngine"
- )
- def test_empty_constraints_score_zero(
- self, mock_rejection_cls, mock_analyzer_cls
- ):
- """No constraints -> total_score = 0.0."""
- mock_rejection = Mock()
- mock_rejection.check_all_constraints.return_value = Mock(
- should_reject=False
- )
- mock_rejection_cls.return_value = mock_rejection
-
- model = Mock()
- checker = ConstraintChecker(model, evidence_gatherer=lambda c, con: [])
-
- candidate = _make_candidate()
-
- result = checker.check_candidate(candidate, [])
-
- assert result.total_score == 0.0
- assert result.constraint_scores == {}
- assert result.detailed_results == []
-
-
-# ---------------------------------------------------------------------------
-# Result structure
-# ---------------------------------------------------------------------------
-
-
-class TestResultStructure:
- """ConstraintCheckResult has correct fields."""
-
- @patch(
- "local_deep_research.advanced_search_system.constraint_checking.constraint_checker.EvidenceAnalyzer"
- )
- @patch(
- "local_deep_research.advanced_search_system.constraint_checking.constraint_checker.RejectionEngine"
- )
- def test_result_fields(self, mock_rejection_cls, mock_analyzer_cls):
- """Result has candidate, total_score, constraint_scores, detailed_results."""
- mock_rejection = Mock()
- mock_rejection.check_all_constraints.return_value = Mock(
- should_reject=False
- )
- mock_rejection_cls.return_value = mock_rejection
-
- model = Mock()
- checker = ConstraintChecker(model, evidence_gatherer=lambda c, con: [])
-
- candidate = _make_candidate("my_candidate")
- constraint = _make_constraint("my_constraint", weight=1.0)
-
- result = checker.check_candidate(candidate, [constraint])
-
- assert isinstance(result, ConstraintCheckResult)
- assert result.candidate is candidate
- assert isinstance(result.total_score, float)
- assert "my_constraint" in result.constraint_scores
- assert len(result.detailed_results) == 1
- assert result.detailed_results[0]["constraint"] == "my_constraint"
- assert result.detailed_results[0]["weight"] == 1.0
diff --git a/tests/advanced_search_system/constraint_checking/test_dual_confidence_checker.py b/tests/advanced_search_system/constraint_checking/test_dual_confidence_checker.py
deleted file mode 100644
index d2ddd5e57c..0000000000
--- a/tests/advanced_search_system/constraint_checking/test_dual_confidence_checker.py
+++ /dev/null
@@ -1,465 +0,0 @@
-"""
-Tests for the DualConfidenceChecker class.
-
-Tests cover:
-- Initialization with thresholds
-- Dual confidence scoring
-- Re-evaluation logic for uncertain results
-- LLM pre-screening
-- Rejection decisions based on positive/negative evidence
-- Weighted score calculation
-"""
-
-from dataclasses import dataclass
-from enum import Enum
-from unittest.mock import Mock
-
-
-class MockConstraintType(Enum):
- """Mock constraint type for testing."""
-
- PROPERTY = "property"
- NAME_PATTERN = "name_pattern"
-
-
-@dataclass
-class MockCandidate:
- """Mock candidate for testing."""
-
- name: str
- value: str = ""
-
-
-@dataclass
-class MockConstraint:
- """Mock constraint for testing."""
-
- value: str
- weight: float = 1.0
- type: MockConstraintType = MockConstraintType.PROPERTY
-
-
-@dataclass
-class MockConstraintEvidence:
- """Mock constraint evidence for testing."""
-
- positive_confidence: float
- negative_confidence: float
- uncertainty: float
- evidence_text: str = ""
- source: str = "test"
-
-
-class TestDualConfidenceCheckerInit:
- """Tests for DualConfidenceChecker initialization."""
-
- def test_init_with_defaults(self):
- """Initialize with default thresholds."""
- from local_deep_research.advanced_search_system.constraint_checking.dual_confidence_checker import (
- DualConfidenceChecker,
- )
-
- mock_model = Mock()
- checker = DualConfidenceChecker(mock_model)
-
- assert checker.negative_threshold == 0.25
- assert checker.positive_threshold == 0.4
- assert checker.uncertainty_penalty == 0.2
- assert checker.negative_weight == 0.5
- assert checker.uncertainty_threshold == 0.6
- assert checker.max_reevaluations == 2
-
- def test_init_with_custom_negative_threshold(self):
- """Initialize with custom negative threshold."""
- from local_deep_research.advanced_search_system.constraint_checking.dual_confidence_checker import (
- DualConfidenceChecker,
- )
-
- mock_model = Mock()
- checker = DualConfidenceChecker(mock_model, negative_threshold=0.3)
-
- assert checker.negative_threshold == 0.3
-
- def test_init_with_custom_positive_threshold(self):
- """Initialize with custom positive threshold."""
- from local_deep_research.advanced_search_system.constraint_checking.dual_confidence_checker import (
- DualConfidenceChecker,
- )
-
- mock_model = Mock()
- checker = DualConfidenceChecker(mock_model, positive_threshold=0.5)
-
- assert checker.positive_threshold == 0.5
-
- def test_init_with_custom_uncertainty_penalty(self):
- """Initialize with custom uncertainty penalty."""
- from local_deep_research.advanced_search_system.constraint_checking.dual_confidence_checker import (
- DualConfidenceChecker,
- )
-
- mock_model = Mock()
- checker = DualConfidenceChecker(mock_model, uncertainty_penalty=0.3)
-
- assert checker.uncertainty_penalty == 0.3
-
- def test_init_with_custom_max_reevaluations(self):
- """Initialize with custom max reevaluations."""
- from local_deep_research.advanced_search_system.constraint_checking.dual_confidence_checker import (
- DualConfidenceChecker,
- )
-
- mock_model = Mock()
- checker = DualConfidenceChecker(mock_model, max_reevaluations=5)
-
- assert checker.max_reevaluations == 5
-
- def test_init_creates_evidence_analyzer(self):
- """Initializes evidence analyzer."""
- from local_deep_research.advanced_search_system.constraint_checking.dual_confidence_checker import (
- DualConfidenceChecker,
- )
-
- mock_model = Mock()
- checker = DualConfidenceChecker(mock_model)
-
- assert checker.evidence_analyzer is not None
-
- def test_init_stores_model(self):
- """Stores model reference."""
- from local_deep_research.advanced_search_system.constraint_checking.dual_confidence_checker import (
- DualConfidenceChecker,
- )
-
- mock_model = Mock()
- checker = DualConfidenceChecker(mock_model)
-
- assert checker.model is mock_model
-
-
-class TestShouldRejectCandidate:
- """Tests for should_reject_candidate method."""
-
- def test_calculates_averages_from_evidence(self):
- """Calculates averages from dual evidence."""
- from local_deep_research.advanced_search_system.constraint_checking.dual_confidence_checker import (
- DualConfidenceChecker,
- )
-
- mock_model = Mock()
- checker = DualConfidenceChecker(
- mock_model, negative_threshold=0.25, positive_threshold=0.4
- )
-
- candidate = MockCandidate(name="Test")
- constraint = MockConstraint(value="constraint")
-
- evidence = [
- MockConstraintEvidence(0.8, 0.1, 0.1),
- MockConstraintEvidence(0.6, 0.2, 0.2),
- ]
-
- should_reject, _ = checker.should_reject_candidate(
- candidate, constraint, evidence
- )
-
- # Avg positive = 0.7, avg negative = 0.15 - should pass
- assert should_reject is False
-
-
-class TestEvaluateConstraintWithReevaluation:
- """Tests for _evaluate_constraint_with_reevaluation method."""
-
- def test_returns_high_uncertainty_when_no_evidence(self):
- """Returns high uncertainty when no evidence found."""
- from local_deep_research.advanced_search_system.constraint_checking.dual_confidence_checker import (
- DualConfidenceChecker,
- )
-
- mock_model = Mock()
- mock_gatherer = Mock(return_value=[]) # No evidence
- checker = DualConfidenceChecker(
- mock_model, evidence_gatherer=mock_gatherer
- )
-
- candidate = MockCandidate(name="Test")
- constraint = MockConstraint(value="constraint")
-
- result = checker._evaluate_constraint_with_reevaluation(
- candidate, constraint
- )
-
- assert result["uncertainty"] == 1.0
- assert result["positive"] == 0.0
- assert result["negative"] == 0.0
-
- def test_does_not_reevaluate_when_certain(self):
- """Does not re-evaluate when uncertainty is low."""
- from local_deep_research.advanced_search_system.constraint_checking.dual_confidence_checker import (
- DualConfidenceChecker,
- )
-
- mock_model = Mock()
- mock_model.invoke.return_value.content = (
- "POSITIVE: 0.8\nNEGATIVE: 0.1\nUNCERTAINTY: 0.1"
- )
- mock_gatherer = Mock(return_value=[{"text": "evidence"}])
- checker = DualConfidenceChecker(
- mock_model,
- evidence_gatherer=mock_gatherer,
- uncertainty_threshold=0.6,
- )
-
- candidate = MockCandidate(name="Test")
- constraint = MockConstraint(value="constraint")
-
- result = checker._evaluate_constraint_with_reevaluation(
- candidate, constraint
- )
-
- assert result["reevaluation_count"] == 0
-
- def test_tracks_reevaluation_count(self):
- """Tracks number of re-evaluations."""
- from local_deep_research.advanced_search_system.constraint_checking.dual_confidence_checker import (
- DualConfidenceChecker,
- )
-
- mock_model = Mock()
- # First call: high uncertainty, second call: low uncertainty
- mock_model.invoke.return_value.content = (
- "POSITIVE: 0.7\nNEGATIVE: 0.1\nUNCERTAINTY: 0.2"
- )
- mock_gatherer = Mock(return_value=[{"text": "evidence"}])
- checker = DualConfidenceChecker(
- mock_model,
- evidence_gatherer=mock_gatherer,
- uncertainty_threshold=0.6,
- max_reevaluations=2,
- )
-
- candidate = MockCandidate(name="Test")
- constraint = MockConstraint(value="constraint")
-
- result = checker._evaluate_constraint_with_reevaluation(
- candidate, constraint
- )
-
- assert "reevaluation_count" in result
-
-
-class TestCheckCandidate:
- """Tests for check_candidate method."""
-
- def test_returns_constraint_check_result(self):
- """Returns ConstraintCheckResult with all fields."""
- from local_deep_research.advanced_search_system.constraint_checking.dual_confidence_checker import (
- DualConfidenceChecker,
- )
-
- mock_model = Mock()
- mock_model.invoke.return_value.content = (
- "POSITIVE: 0.8\nNEGATIVE: 0.1\nUNCERTAINTY: 0.1"
- )
- mock_model.invoke.return_value = Mock(content="75") # Pre-screen passes
- mock_gatherer = Mock(return_value=[{"text": "evidence"}])
- checker = DualConfidenceChecker(
- mock_model, evidence_gatherer=mock_gatherer
- )
-
- candidate = MockCandidate(name="Test")
- constraints = [MockConstraint(value="c1")]
-
- result = checker.check_candidate(
- candidate, constraints, original_query="test query"
- )
-
- assert hasattr(result, "total_score")
- assert hasattr(result, "should_reject")
- assert hasattr(result, "constraint_scores")
- assert hasattr(result, "detailed_results")
-
- def test_stores_positive_negative_uncertainty(self):
- """Stores positive/negative/uncertainty in constraint scores."""
- from local_deep_research.advanced_search_system.constraint_checking.dual_confidence_checker import (
- DualConfidenceChecker,
- )
-
- mock_model = Mock()
- mock_model.invoke.return_value.content = (
- "POSITIVE: 0.7\nNEGATIVE: 0.1\nUNCERTAINTY: 0.2"
- )
- mock_model.invoke.return_value = Mock(content="80")
- mock_gatherer = Mock(return_value=[{"text": "evidence"}])
- checker = DualConfidenceChecker(
- mock_model, evidence_gatherer=mock_gatherer
- )
-
- candidate = MockCandidate(name="Test")
- constraints = [MockConstraint(value="c1")]
-
- result = checker.check_candidate(
- candidate, constraints, original_query="test"
- )
-
- scores = result.constraint_scores["c1"]
- assert "positive" in scores
- assert "negative" in scores
- assert "uncertainty" in scores
-
- def test_calculates_weighted_total_score(self):
- """Calculates weighted total score from constraints."""
- from local_deep_research.advanced_search_system.constraint_checking.dual_confidence_checker import (
- DualConfidenceChecker,
- )
-
- mock_model = Mock()
- mock_model.invoke.return_value.content = (
- "POSITIVE: 0.8\nNEGATIVE: 0.1\nUNCERTAINTY: 0.1"
- )
- mock_model.invoke.return_value = Mock(content="80")
- mock_gatherer = Mock(return_value=[{"text": "evidence"}])
- checker = DualConfidenceChecker(
- mock_model, evidence_gatherer=mock_gatherer
- )
-
- candidate = MockCandidate(name="Test")
- constraints = [
- MockConstraint(value="c1", weight=2.0),
- MockConstraint(value="c2", weight=1.0),
- ]
-
- result = checker.check_candidate(
- candidate, constraints, original_query="test"
- )
-
- # Should have a weighted score
- assert result.total_score >= 0.0
- assert result.total_score <= 1.0
-
- def test_sets_score_zero_when_rejected(self):
- """Sets total score to 0 when candidate rejected."""
- from local_deep_research.advanced_search_system.constraint_checking.dual_confidence_checker import (
- DualConfidenceChecker,
- )
-
- mock_model = Mock()
- # High negative evidence
- mock_model.invoke.return_value.content = (
- "POSITIVE: 0.1\nNEGATIVE: 0.8\nUNCERTAINTY: 0.1"
- )
- mock_model.invoke.return_value = Mock(content="80")
- mock_gatherer = Mock(return_value=[{"text": "evidence"}])
- checker = DualConfidenceChecker(
- mock_model, evidence_gatherer=mock_gatherer
- )
-
- candidate = MockCandidate(name="Test")
- constraints = [MockConstraint(value="c1")]
-
- result = checker.check_candidate(
- candidate, constraints, original_query="test"
- )
-
- assert result.should_reject is True
- assert result.total_score == 0.0
-
- def test_handles_empty_constraints(self):
- """Handles empty constraints list."""
- from local_deep_research.advanced_search_system.constraint_checking.dual_confidence_checker import (
- DualConfidenceChecker,
- )
-
- mock_model = Mock()
- mock_model.invoke.return_value = Mock(content="80")
- checker = DualConfidenceChecker(mock_model)
-
- candidate = MockCandidate(name="Test")
- constraints = []
-
- result = checker.check_candidate(
- candidate, constraints, original_query="test"
- )
-
- assert result.total_score == 0.0
- assert result.detailed_results == []
-
- def test_records_reevaluation_count_in_results(self):
- """Records reevaluation count in detailed results."""
- from local_deep_research.advanced_search_system.constraint_checking.dual_confidence_checker import (
- DualConfidenceChecker,
- )
-
- mock_model = Mock()
- mock_model.invoke.return_value.content = (
- "POSITIVE: 0.7\nNEGATIVE: 0.1\nUNCERTAINTY: 0.2"
- )
- mock_model.invoke.return_value = Mock(content="80")
- mock_gatherer = Mock(return_value=[{"text": "evidence"}])
- checker = DualConfidenceChecker(
- mock_model, evidence_gatherer=mock_gatherer
- )
-
- candidate = MockCandidate(name="Test")
- constraints = [MockConstraint(value="c1")]
-
- result = checker.check_candidate(
- candidate, constraints, original_query="test"
- )
-
- assert "reevaluation_count" in result.detailed_results[0]
- assert "reevaluation_count" in result.constraint_scores["c1"]
-
-
-class TestLogConstraintResultDetailed:
- """Tests for _log_constraint_result_detailed method."""
-
- def test_logs_high_score_with_checkmark(self):
- """Logs high scores with checkmark symbol."""
- from local_deep_research.advanced_search_system.constraint_checking.dual_confidence_checker import (
- DualConfidenceChecker,
- )
-
- mock_model = Mock()
- checker = DualConfidenceChecker(mock_model)
-
- candidate = MockCandidate(name="Test")
- constraint = MockConstraint(value="constraint")
-
- # Should not raise
- checker._log_constraint_result_detailed(
- candidate, constraint, 0.9, 0.8, 0.1, 0.1, 0
- )
-
- def test_logs_medium_score_with_circle(self):
- """Logs medium scores with circle symbol."""
- from local_deep_research.advanced_search_system.constraint_checking.dual_confidence_checker import (
- DualConfidenceChecker,
- )
-
- mock_model = Mock()
- checker = DualConfidenceChecker(mock_model)
-
- candidate = MockCandidate(name="Test")
- constraint = MockConstraint(value="constraint")
-
- # Should not raise
- checker._log_constraint_result_detailed(
- candidate, constraint, 0.6, 0.5, 0.2, 0.3, 1
- )
-
- def test_logs_low_score_with_x(self):
- """Logs low scores with X symbol."""
- from local_deep_research.advanced_search_system.constraint_checking.dual_confidence_checker import (
- DualConfidenceChecker,
- )
-
- mock_model = Mock()
- checker = DualConfidenceChecker(mock_model)
-
- candidate = MockCandidate(name="Test")
- constraint = MockConstraint(value="constraint")
-
- # Should not raise
- checker._log_constraint_result_detailed(
- candidate, constraint, 0.3, 0.2, 0.5, 0.3, 2
- )
diff --git a/tests/advanced_search_system/constraint_checking/test_dual_confidence_coverage.py b/tests/advanced_search_system/constraint_checking/test_dual_confidence_coverage.py
deleted file mode 100644
index a0ea0bc9ff..0000000000
--- a/tests/advanced_search_system/constraint_checking/test_dual_confidence_coverage.py
+++ /dev/null
@@ -1,300 +0,0 @@
-"""
-Coverage tests for DualConfidenceChecker.
-
-Tests cover missing branches in:
-- _should_early_reject: high negative returns True; low positive returns True; both ok False
-- should_reject_candidate_from_averages: high negative, low positive, both ok
-- should_reject_candidate: empty evidence list; high negative; low positive; both ok
-- _log_constraint_result_detailed: symbol selection (good/medium/bad score)
-- _llm_prescreen_candidate: no original_query short-circuits; quality>=50 accepts;
- quality<50 rejects; parse failure accepts; exception accepts
-"""
-
-from unittest.mock import MagicMock, Mock, patch
-
-from local_deep_research.advanced_search_system.candidates.base_candidate import (
- Candidate,
-)
-from local_deep_research.advanced_search_system.constraints.base_constraint import (
- Constraint,
- ConstraintType,
-)
-from local_deep_research.advanced_search_system.constraint_checking.dual_confidence_checker import (
- DualConfidenceChecker,
-)
-from local_deep_research.advanced_search_system.constraint_checking.evidence_analyzer import (
- ConstraintEvidence,
-)
-
-MODULE = "local_deep_research.advanced_search_system.constraint_checking.dual_confidence_checker"
-
-
-# ---------------------------------------------------------------------------
-# Helpers
-# ---------------------------------------------------------------------------
-
-
-def _make_checker(
- negative_threshold=0.25,
- positive_threshold=0.4,
- uncertainty_threshold=0.6,
- max_reevaluations=2,
-):
- model = MagicMock()
- with patch(
- f"{MODULE}.EvidenceAnalyzer",
- return_value=MagicMock(),
- ):
- checker = DualConfidenceChecker(
- model,
- negative_threshold=negative_threshold,
- positive_threshold=positive_threshold,
- uncertainty_threshold=uncertainty_threshold,
- max_reevaluations=max_reevaluations,
- )
- return checker
-
-
-def _constraint(value="test_constraint"):
- return Constraint(
- id="c1",
- type=ConstraintType.PROPERTY,
- description="A test constraint",
- value=value,
- weight=1.0,
- )
-
-
-def _candidate(name="TestCandidate"):
- return Candidate(name=name)
-
-
-def _evidence(positive=0.5, negative=0.1, uncertainty=0.4):
- ev = ConstraintEvidence(
- positive_confidence=positive,
- negative_confidence=negative,
- uncertainty=uncertainty,
- evidence_text="some evidence",
- source="test_source",
- )
- return ev
-
-
-# ---------------------------------------------------------------------------
-# _should_early_reject
-# ---------------------------------------------------------------------------
-
-
-class TestShouldEarlyReject:
- """_should_early_reject returns True only when thresholds are breached."""
-
- def test_high_negative_returns_true(self):
- checker = _make_checker(negative_threshold=0.25)
- assert (
- checker._should_early_reject(avg_positive=0.6, avg_negative=0.5)
- is True
- )
-
- def test_low_positive_returns_true(self):
- checker = _make_checker(positive_threshold=0.4)
- assert (
- checker._should_early_reject(avg_positive=0.1, avg_negative=0.1)
- is True
- )
-
- def test_both_ok_returns_false(self):
- checker = _make_checker(negative_threshold=0.25, positive_threshold=0.4)
- assert (
- checker._should_early_reject(avg_positive=0.8, avg_negative=0.1)
- is False
- )
-
-
-# ---------------------------------------------------------------------------
-# should_reject_candidate_from_averages
-# ---------------------------------------------------------------------------
-
-
-class TestShouldRejectCandidateFromAverages:
- """should_reject_candidate_from_averages covers all three branches."""
-
- def test_high_negative_rejects(self):
- checker = _make_checker(negative_threshold=0.25)
- reject, reason = checker.should_reject_candidate_from_averages(
- _candidate(), _constraint(), avg_positive=0.8, avg_negative=0.5
- )
- assert reject is True
- assert "negative" in reason.lower()
-
- def test_low_positive_rejects(self):
- checker = _make_checker(positive_threshold=0.4)
- reject, reason = checker.should_reject_candidate_from_averages(
- _candidate(), _constraint(), avg_positive=0.1, avg_negative=0.1
- )
- assert reject is True
- assert "positive" in reason.lower()
-
- def test_both_within_thresholds_accepts(self):
- checker = _make_checker(negative_threshold=0.25, positive_threshold=0.4)
- reject, reason = checker.should_reject_candidate_from_averages(
- _candidate(), _constraint(), avg_positive=0.8, avg_negative=0.1
- )
- assert reject is False
- assert reason == ""
-
-
-# ---------------------------------------------------------------------------
-# should_reject_candidate (evidence list variant)
-# ---------------------------------------------------------------------------
-
-
-class TestShouldRejectCandidateFromEvidenceList:
- """should_reject_candidate with ConstraintEvidence list."""
-
- def test_empty_evidence_returns_false(self):
- checker = _make_checker()
- reject, reason = checker.should_reject_candidate(
- _candidate(), _constraint(), dual_evidence=[]
- )
- assert reject is False
-
- def test_high_negative_evidence_rejects(self):
- checker = _make_checker(negative_threshold=0.25)
- evidence = [_evidence(positive=0.9, negative=0.8)]
- reject, reason = checker.should_reject_candidate(
- _candidate(), _constraint(), dual_evidence=evidence
- )
- assert reject is True
-
- def test_low_positive_evidence_rejects(self):
- checker = _make_checker(positive_threshold=0.4)
- evidence = [_evidence(positive=0.1, negative=0.1)]
- reject, reason = checker.should_reject_candidate(
- _candidate(), _constraint(), dual_evidence=evidence
- )
- assert reject is True
-
- def test_good_evidence_accepts(self):
- checker = _make_checker(negative_threshold=0.25, positive_threshold=0.4)
- evidence = [_evidence(positive=0.9, negative=0.05)]
- reject, reason = checker.should_reject_candidate(
- _candidate(), _constraint(), dual_evidence=evidence
- )
- assert reject is False
-
-
-# ---------------------------------------------------------------------------
-# _log_constraint_result_detailed
-# ---------------------------------------------------------------------------
-
-
-class TestLogConstraintResultDetailed:
- """_log_constraint_result_detailed selects correct symbol."""
-
- def test_high_score_logs_checkmark(self, caplog):
- checker = _make_checker()
- with patch(f"{MODULE}.logger") as mock_logger:
- checker._log_constraint_result_detailed(
- _candidate("X"),
- _constraint(),
- score=0.9,
- positive=0.9,
- negative=0.05,
- uncertainty=0.05,
- )
- assert mock_logger.info.called
- call_str = mock_logger.info.call_args[0][0]
- assert "✓" in call_str
-
- def test_medium_score_logs_circle(self):
- checker = _make_checker()
- with patch(f"{MODULE}.logger") as mock_logger:
- checker._log_constraint_result_detailed(
- _candidate("X"),
- _constraint(),
- score=0.6,
- positive=0.6,
- negative=0.1,
- uncertainty=0.3,
- )
- call_str = mock_logger.info.call_args[0][0]
- assert "○" in call_str
-
- def test_low_score_logs_cross(self):
- checker = _make_checker()
- with patch(f"{MODULE}.logger") as mock_logger:
- checker._log_constraint_result_detailed(
- _candidate("X"),
- _constraint(),
- score=0.3,
- positive=0.3,
- negative=0.4,
- uncertainty=0.3,
- )
- call_str = mock_logger.info.call_args[0][0]
- assert "✗" in call_str
-
- def test_reevaluation_indicator_included(self):
- checker = _make_checker()
- with patch(f"{MODULE}.logger") as mock_logger:
- checker._log_constraint_result_detailed(
- _candidate("X"),
- _constraint(),
- score=0.7,
- positive=0.7,
- negative=0.1,
- uncertainty=0.2,
- reevaluation_count=1,
- )
- call_str = mock_logger.info.call_args[0][0]
- assert "[R1]" in call_str
-
-
-# ---------------------------------------------------------------------------
-# _llm_prescreen_candidate
-# ---------------------------------------------------------------------------
-
-
-class TestLlmPrescreenCandidate:
- """_llm_prescreen_candidate covers all branches."""
-
- def test_no_original_query_accepts_without_model_call(self):
- checker = _make_checker()
- result = checker._llm_prescreen_candidate(
- _candidate(), [], original_query=None
- )
- assert result["should_reject"] is False
- checker.model.invoke.assert_not_called()
-
- def test_quality_above_50_accepts(self):
- checker = _make_checker()
- checker.model.invoke.return_value = Mock(content="75")
- result = checker._llm_prescreen_candidate(
- _candidate(), [], original_query="What is the answer?"
- )
- assert result["should_reject"] is False
-
- def test_quality_below_50_rejects(self):
- checker = _make_checker()
- checker.model.invoke.return_value = Mock(content="20")
- result = checker._llm_prescreen_candidate(
- _candidate(), [], original_query="What is the answer?"
- )
- assert result["should_reject"] is True
- assert "20%" in result["reason"]
-
- def test_parse_failure_accepts(self):
- checker = _make_checker()
- checker.model.invoke.return_value = Mock(content="no number here")
- result = checker._llm_prescreen_candidate(
- _candidate(), [], original_query="What is the answer?"
- )
- assert result["should_reject"] is False
-
- def test_exception_accepts(self):
- checker = _make_checker()
- checker.model.invoke.side_effect = RuntimeError("network error")
- result = checker._llm_prescreen_candidate(
- _candidate(), [], original_query="What is X?"
- )
- assert result["should_reject"] is False
diff --git a/tests/advanced_search_system/constraint_checking/test_evidence_analyzer_extended.py b/tests/advanced_search_system/constraint_checking/test_evidence_analyzer_extended.py
deleted file mode 100644
index a27ccd4c7a..0000000000
--- a/tests/advanced_search_system/constraint_checking/test_evidence_analyzer_extended.py
+++ /dev/null
@@ -1,900 +0,0 @@
-"""
-Extended tests for EvidenceAnalyzer - Dual confidence evidence analysis.
-
-Tests cover:
-- ConstraintEvidence dataclass
-- EvidenceAnalyzer initialization
-- analyze_evidence_dual_confidence method
-- Score extraction
-- evaluate_evidence_list method
-- Normalization
-- Edge cases
-
-These tests import and test the ACTUAL EvidenceAnalyzer class with mocked LLM.
-"""
-
-from unittest.mock import MagicMock
-
-
-from local_deep_research.advanced_search_system.constraint_checking.evidence_analyzer import (
- ConstraintEvidence,
- EvidenceAnalyzer,
-)
-from local_deep_research.advanced_search_system.constraints.base_constraint import (
- Constraint,
- ConstraintType,
-)
-
-
-class TestConstraintEvidenceDataclass:
- """Tests for ConstraintEvidence dataclass."""
-
- def test_has_positive_confidence(self):
- """ConstraintEvidence should have positive_confidence field."""
- evidence = ConstraintEvidence(
- positive_confidence=0.7,
- negative_confidence=0.2,
- uncertainty=0.1,
- evidence_text="text",
- source="search",
- )
- assert evidence.positive_confidence == 0.7
-
- def test_has_negative_confidence(self):
- """ConstraintEvidence should have negative_confidence field."""
- evidence = ConstraintEvidence(
- positive_confidence=0.3,
- negative_confidence=0.5,
- uncertainty=0.2,
- evidence_text="text",
- source="search",
- )
- assert evidence.negative_confidence == 0.5
-
- def test_has_uncertainty(self):
- """ConstraintEvidence should have uncertainty field."""
- evidence = ConstraintEvidence(
- positive_confidence=0.4,
- negative_confidence=0.1,
- uncertainty=0.5,
- evidence_text="text",
- source="search",
- )
- assert evidence.uncertainty == 0.5
-
- def test_has_evidence_text(self):
- """ConstraintEvidence should have evidence_text field."""
- evidence = ConstraintEvidence(
- positive_confidence=0.5,
- negative_confidence=0.3,
- uncertainty=0.2,
- evidence_text="This is evidence text",
- source="search",
- )
- assert evidence.evidence_text == "This is evidence text"
-
- def test_has_source(self):
- """ConstraintEvidence should have source field."""
- evidence = ConstraintEvidence(
- positive_confidence=0.5,
- negative_confidence=0.3,
- uncertainty=0.2,
- evidence_text="text",
- source="web_search",
- )
- assert evidence.source == "web_search"
-
- def test_scores_sum_to_one(self):
- """Confidence scores should approximately sum to 1.0."""
- evidence = ConstraintEvidence(
- positive_confidence=0.5,
- negative_confidence=0.3,
- uncertainty=0.2,
- evidence_text="text",
- source="search",
- )
-
- total = (
- evidence.positive_confidence
- + evidence.negative_confidence
- + evidence.uncertainty
- )
- assert abs(total - 1.0) < 0.001
-
-
-class TestEvidenceAnalyzerInitialization:
- """Tests for EvidenceAnalyzer initialization."""
-
- def test_model_assignment(self):
- """Should assign model on initialization."""
- mock_model = MagicMock()
- analyzer = EvidenceAnalyzer(model=mock_model)
- assert analyzer.model == mock_model
-
- def test_accepts_langchain_model(self):
- """Should accept LangChain BaseChatModel."""
- mock_model = MagicMock()
- mock_model.invoke = MagicMock(return_value=MagicMock(content="test"))
-
- analyzer = EvidenceAnalyzer(model=mock_model)
- assert analyzer.model is not None
-
-
-class TestAnalyzeEvidenceDualConfidence:
- """Tests for analyze_evidence_dual_confidence method."""
-
- def test_extracts_text_from_evidence(self):
- """Should extract text from evidence dict."""
- mock_model = MagicMock()
- mock_response = MagicMock()
- mock_response.content = "POSITIVE: 0.6\nNEGATIVE: 0.2\nUNCERTAINTY: 0.2"
- mock_model.invoke = MagicMock(return_value=mock_response)
-
- analyzer = EvidenceAnalyzer(model=mock_model)
- constraint = Constraint(
- id="c1",
- type=ConstraintType.PROPERTY,
- description="Test constraint",
- value="test value",
- )
- evidence = {"text": "This is evidence text", "source": "search"}
-
- result = analyzer.analyze_evidence_dual_confidence(evidence, constraint)
-
- assert isinstance(result, ConstraintEvidence)
- assert result.evidence_text == "This is evidence text"
-
- def test_handles_missing_text(self):
- """Should handle missing text field."""
- mock_model = MagicMock()
- mock_response = MagicMock()
- mock_response.content = "POSITIVE: 0.5\nNEGATIVE: 0.3\nUNCERTAINTY: 0.2"
- mock_model.invoke = MagicMock(return_value=mock_response)
-
- analyzer = EvidenceAnalyzer(model=mock_model)
- constraint = Constraint(
- id="c1",
- type=ConstraintType.PROPERTY,
- description="Test",
- value="value",
- )
- evidence = {"source": "search"} # No text field
-
- result = analyzer.analyze_evidence_dual_confidence(evidence, constraint)
-
- assert result.evidence_text == ""
-
- def test_truncates_long_text_in_evidence_result(self):
- """Should truncate evidence_text to 500 chars in result."""
- mock_model = MagicMock()
- mock_response = MagicMock()
- mock_response.content = "POSITIVE: 0.5\nNEGATIVE: 0.3\nUNCERTAINTY: 0.2"
- mock_model.invoke = MagicMock(return_value=mock_response)
-
- analyzer = EvidenceAnalyzer(model=mock_model)
- constraint = Constraint(
- id="c1",
- type=ConstraintType.PROPERTY,
- description="Test",
- value="value",
- )
- long_text = "x" * 1000
- evidence = {"text": long_text, "source": "search"}
-
- result = analyzer.analyze_evidence_dual_confidence(evidence, constraint)
-
- assert len(result.evidence_text) == 500
-
- def test_normalizes_scores(self):
- """Should normalize scores to sum to 1.0."""
- mock_model = MagicMock()
- mock_response = MagicMock()
- # Non-normalized scores
- mock_response.content = "POSITIVE: 0.6\nNEGATIVE: 0.3\nUNCERTAINTY: 0.3"
- mock_model.invoke = MagicMock(return_value=mock_response)
-
- analyzer = EvidenceAnalyzer(model=mock_model)
- constraint = Constraint(
- id="c1",
- type=ConstraintType.PROPERTY,
- description="Test",
- value="value",
- )
- evidence = {"text": "test", "source": "search"}
-
- result = analyzer.analyze_evidence_dual_confidence(evidence, constraint)
-
- total = (
- result.positive_confidence
- + result.negative_confidence
- + result.uncertainty
- )
- assert abs(total - 1.0) < 0.001
-
- def test_default_high_uncertainty_on_zero_total(self):
- """Should default to high uncertainty when parsing returns zeros."""
- mock_model = MagicMock()
- mock_response = MagicMock()
- # Return valid format but low confidence values - these get normalized
- mock_response.content = "POSITIVE: 0.1\nNEGATIVE: 0.1\nUNCERTAINTY: 0.1"
- mock_model.invoke = MagicMock(return_value=mock_response)
-
- analyzer = EvidenceAnalyzer(model=mock_model)
- constraint = Constraint(
- id="c1",
- type=ConstraintType.PROPERTY,
- description="Test",
- value="value",
- )
- evidence = {"text": "test", "source": "search"}
-
- result = analyzer.analyze_evidence_dual_confidence(evidence, constraint)
-
- # Scores get normalized to sum to 1.0
- total = (
- result.positive_confidence
- + result.negative_confidence
- + result.uncertainty
- )
- assert abs(total - 1.0) < 0.001
-
- def test_uses_default_source(self):
- """Should use default source when not provided."""
- mock_model = MagicMock()
- mock_response = MagicMock()
- mock_response.content = "POSITIVE: 0.5\nNEGATIVE: 0.3\nUNCERTAINTY: 0.2"
- mock_model.invoke = MagicMock(return_value=mock_response)
-
- analyzer = EvidenceAnalyzer(model=mock_model)
- constraint = Constraint(
- id="c1",
- type=ConstraintType.PROPERTY,
- description="Test",
- value="value",
- )
- evidence = {"text": "test"} # No source
-
- result = analyzer.analyze_evidence_dual_confidence(evidence, constraint)
-
- assert result.source == "search"
-
- def test_handles_exception_with_defaults(self):
- """Should return default values on exception."""
- mock_model = MagicMock()
- mock_model.invoke = MagicMock(side_effect=Exception("API Error"))
-
- analyzer = EvidenceAnalyzer(model=mock_model)
- constraint = Constraint(
- id="c1",
- type=ConstraintType.PROPERTY,
- description="Test",
- value="value",
- )
- evidence = {"text": "test", "source": "search"}
-
- result = analyzer.analyze_evidence_dual_confidence(evidence, constraint)
-
- assert result.positive_confidence == 0.1
- assert result.negative_confidence == 0.1
- assert result.uncertainty == 0.8
-
-
-class TestExtractScore:
- """Tests for _extract_score method."""
-
- def test_extracts_positive_score(self):
- """Should extract POSITIVE score."""
- mock_model = MagicMock()
- analyzer = EvidenceAnalyzer(model=mock_model)
-
- text = "POSITIVE: 0.7\nNEGATIVE: 0.2\nUNCERTAINTY: 0.1"
- score = analyzer._extract_score(text, "POSITIVE")
-
- assert score == 0.7
-
- def test_extracts_negative_score(self):
- """Should extract NEGATIVE score."""
- mock_model = MagicMock()
- analyzer = EvidenceAnalyzer(model=mock_model)
-
- text = "POSITIVE: 0.7\nNEGATIVE: 0.2\nUNCERTAINTY: 0.1"
- score = analyzer._extract_score(text, "NEGATIVE")
-
- assert score == 0.2
-
- def test_extracts_uncertainty_score(self):
- """Should extract UNCERTAINTY score."""
- mock_model = MagicMock()
- analyzer = EvidenceAnalyzer(model=mock_model)
-
- text = "POSITIVE: 0.7\nNEGATIVE: 0.2\nUNCERTAINTY: 0.1"
- score = analyzer._extract_score(text, "UNCERTAINTY")
-
- assert score == 0.1
-
- def test_handles_bracketed_score(self):
- """Should handle score in brackets."""
- mock_model = MagicMock()
- analyzer = EvidenceAnalyzer(model=mock_model)
-
- text = "POSITIVE: [0.8]"
- score = analyzer._extract_score(text, "POSITIVE")
-
- assert score == 0.8
-
- def test_case_insensitive_matching(self):
- """Should match labels case-insensitively."""
- mock_model = MagicMock()
- analyzer = EvidenceAnalyzer(model=mock_model)
-
- text = "positive: 0.6"
- score = analyzer._extract_score(text, "POSITIVE")
-
- assert score == 0.6
-
- def test_returns_default_on_no_match(self):
- """Should return default score on no match."""
- mock_model = MagicMock()
- analyzer = EvidenceAnalyzer(model=mock_model)
-
- text = "No scores here"
- score = analyzer._extract_score(text, "POSITIVE")
-
- assert score == 0.1
-
- def test_handles_integer_score(self):
- """Should handle integer score."""
- mock_model = MagicMock()
- analyzer = EvidenceAnalyzer(model=mock_model)
-
- text = "POSITIVE: 1"
- score = analyzer._extract_score(text, "POSITIVE")
-
- assert score == 1.0
-
- def test_returns_default_for_value_error(self):
- """Should return default when float() raises ValueError (PR #2022).
-
- PR #2022 changed bare `except:` to `except ValueError:` to
- specifically catch float conversion errors.
- """
- mock_model = MagicMock()
- analyzer = EvidenceAnalyzer(model=mock_model)
-
- # The regex (\d*\.?\d+) normally matches valid float strings,
- # but test that the ValueError path works by using a label
- # that won't match, verifying the default return.
- text = "POSITIVE: not_a_number"
- score = analyzer._extract_score(text, "POSITIVE")
- assert score == 0.1 # Default low score
-
- def test_handles_empty_string_input(self):
- """Should return default for empty string input."""
- mock_model = MagicMock()
- analyzer = EvidenceAnalyzer(model=mock_model)
-
- score = analyzer._extract_score("", "POSITIVE")
- assert score == 0.1
-
-
-class TestEvaluateEvidenceList:
- """Tests for evaluate_evidence_list method."""
-
- def test_returns_penalty_for_empty_list(self):
- """Should return 0.5 - penalty for empty list."""
- mock_model = MagicMock()
- analyzer = EvidenceAnalyzer(model=mock_model)
- constraint = Constraint(
- id="c1",
- type=ConstraintType.PROPERTY,
- description="Test",
- value="value",
- )
-
- score = analyzer.evaluate_evidence_list([], constraint)
-
- assert score == 0.3 # 0.5 - 0.2 (default penalty)
-
- def test_calculates_average_scores(self):
- """Should calculate average scores correctly."""
- mock_model = MagicMock()
- mock_response = MagicMock()
- mock_response.content = "POSITIVE: 0.7\nNEGATIVE: 0.2\nUNCERTAINTY: 0.1"
- mock_model.invoke = MagicMock(return_value=mock_response)
-
- analyzer = EvidenceAnalyzer(model=mock_model)
- constraint = Constraint(
- id="c1",
- type=ConstraintType.PROPERTY,
- description="Test",
- value="value",
- )
- evidence_list = [
- {"text": "Evidence 1", "source": "s1"},
- {"text": "Evidence 2", "source": "s2"},
- ]
-
- score = analyzer.evaluate_evidence_list(evidence_list, constraint)
-
- # Score is calculated from the evidence
- assert isinstance(score, float)
- assert 0.0 <= score <= 1.0
-
- def test_applies_uncertainty_penalty(self):
- """Should apply uncertainty penalty."""
- mock_model = MagicMock()
- mock_response = MagicMock()
- mock_response.content = "POSITIVE: 0.3\nNEGATIVE: 0.1\nUNCERTAINTY: 0.6"
- mock_model.invoke = MagicMock(return_value=mock_response)
-
- analyzer = EvidenceAnalyzer(model=mock_model)
- constraint = Constraint(
- id="c1",
- type=ConstraintType.PROPERTY,
- description="Test",
- value="value",
- )
- evidence_list = [{"text": "High uncertainty", "source": "s1"}]
-
- score = analyzer.evaluate_evidence_list(evidence_list, constraint)
-
- # High uncertainty should result in lower score
- assert score < 0.5
-
- def test_applies_negative_weight(self):
- """Should apply negative weight in calculation."""
- mock_model = MagicMock()
- mock_response = MagicMock()
- mock_response.content = "POSITIVE: 0.5\nNEGATIVE: 0.4\nUNCERTAINTY: 0.1"
- mock_model.invoke = MagicMock(return_value=mock_response)
-
- analyzer = EvidenceAnalyzer(model=mock_model)
- constraint = Constraint(
- id="c1",
- type=ConstraintType.PROPERTY,
- description="Test",
- value="value",
- )
- evidence_list = [{"text": "Some negative evidence", "source": "s1"}]
-
- score = analyzer.evaluate_evidence_list(evidence_list, constraint)
-
- # Negative evidence should reduce score
- assert isinstance(score, float)
- assert 0.0 <= score <= 1.0
-
- def test_clamps_score_to_zero(self):
- """Should clamp score to minimum 0.0."""
- mock_model = MagicMock()
- mock_response = MagicMock()
- # Very negative result
- mock_response.content = "POSITIVE: 0.1\nNEGATIVE: 0.8\nUNCERTAINTY: 0.1"
- mock_model.invoke = MagicMock(return_value=mock_response)
-
- analyzer = EvidenceAnalyzer(model=mock_model)
- constraint = Constraint(
- id="c1",
- type=ConstraintType.PROPERTY,
- description="Test",
- value="value",
- )
- evidence_list = [{"text": "Very negative", "source": "s1"}]
-
- score = analyzer.evaluate_evidence_list(evidence_list, constraint)
-
- assert score >= 0.0
-
- def test_clamps_score_to_one(self):
- """Should clamp score to maximum 1.0."""
- mock_model = MagicMock()
- mock_response = MagicMock()
- mock_response.content = (
- "POSITIVE: 0.95\nNEGATIVE: 0.03\nUNCERTAINTY: 0.02"
- )
- mock_model.invoke = MagicMock(return_value=mock_response)
-
- analyzer = EvidenceAnalyzer(model=mock_model)
- constraint = Constraint(
- id="c1",
- type=ConstraintType.PROPERTY,
- description="Test",
- value="value",
- )
- evidence_list = [{"text": "Very positive", "source": "s1"}]
-
- score = analyzer.evaluate_evidence_list(evidence_list, constraint)
-
- assert score <= 1.0
-
- def test_custom_uncertainty_penalty(self):
- """Should use custom uncertainty penalty."""
- mock_model = MagicMock()
- mock_response = MagicMock()
- mock_response.content = "POSITIVE: 0.5\nNEGATIVE: 0.1\nUNCERTAINTY: 0.4"
- mock_model.invoke = MagicMock(return_value=mock_response)
-
- analyzer = EvidenceAnalyzer(model=mock_model)
- constraint = Constraint(
- id="c1",
- type=ConstraintType.PROPERTY,
- description="Test",
- value="value",
- )
- evidence_list = [{"text": "test", "source": "s1"}]
-
- # Compare with different penalties
- score_default = analyzer.evaluate_evidence_list(
- evidence_list, constraint, uncertainty_penalty=0.2
- )
- score_high = analyzer.evaluate_evidence_list(
- evidence_list, constraint, uncertainty_penalty=0.5
- )
-
- # Higher penalty should result in lower score
- assert score_high < score_default
-
- def test_custom_negative_weight(self):
- """Should use custom negative weight."""
- mock_model = MagicMock()
- mock_response = MagicMock()
- mock_response.content = "POSITIVE: 0.5\nNEGATIVE: 0.3\nUNCERTAINTY: 0.2"
- mock_model.invoke = MagicMock(return_value=mock_response)
-
- analyzer = EvidenceAnalyzer(model=mock_model)
- constraint = Constraint(
- id="c1",
- type=ConstraintType.PROPERTY,
- description="Test",
- value="value",
- )
- evidence_list = [{"text": "test", "source": "s1"}]
-
- # Compare with different weights
- score_default = analyzer.evaluate_evidence_list(
- evidence_list, constraint, negative_weight=0.5
- )
- score_high = analyzer.evaluate_evidence_list(
- evidence_list, constraint, negative_weight=1.0
- )
-
- # Higher negative weight should result in lower score
- assert score_high < score_default
-
-
-class TestScoreNormalization:
- """Tests for score normalization."""
-
- def test_normalizes_when_total_exceeds_one(self):
- """Should normalize when total > 1."""
- mock_model = MagicMock()
- mock_response = MagicMock()
- mock_response.content = "POSITIVE: 0.6\nNEGATIVE: 0.5\nUNCERTAINTY: 0.4"
- mock_model.invoke = MagicMock(return_value=mock_response)
-
- analyzer = EvidenceAnalyzer(model=mock_model)
- constraint = Constraint(
- id="c1",
- type=ConstraintType.PROPERTY,
- description="Test",
- value="value",
- )
- evidence = {"text": "test", "source": "search"}
-
- result = analyzer.analyze_evidence_dual_confidence(evidence, constraint)
-
- total = (
- result.positive_confidence
- + result.negative_confidence
- + result.uncertainty
- )
- assert abs(total - 1.0) < 0.001
-
- def test_preserves_ratios(self):
- """Should preserve score ratios during normalization."""
- mock_model = MagicMock()
- mock_response = MagicMock()
- mock_response.content = "POSITIVE: 0.6\nNEGATIVE: 0.3\nUNCERTAINTY: 0.3"
- mock_model.invoke = MagicMock(return_value=mock_response)
-
- analyzer = EvidenceAnalyzer(model=mock_model)
- constraint = Constraint(
- id="c1",
- type=ConstraintType.PROPERTY,
- description="Test",
- value="value",
- )
- evidence = {"text": "test", "source": "search"}
-
- result = analyzer.analyze_evidence_dual_confidence(evidence, constraint)
-
- # Original ratio 0.6 / 0.3 = 2.0
- # Should be preserved
- ratio = result.positive_confidence / result.negative_confidence
- assert abs(ratio - 2.0) < 0.001
-
-
-class TestDefaultValues:
- """Tests for default value handling."""
-
- def test_default_uncertainty_penalty(self):
- """Default uncertainty_penalty should be 0.2."""
- mock_model = MagicMock()
- mock_response = MagicMock()
- mock_response.content = "POSITIVE: 0.5\nNEGATIVE: 0.1\nUNCERTAINTY: 0.4"
- mock_model.invoke = MagicMock(return_value=mock_response)
-
- analyzer = EvidenceAnalyzer(model=mock_model)
- constraint = Constraint(
- id="c1",
- type=ConstraintType.PROPERTY,
- description="Test",
- value="value",
- )
- evidence_list = [{"text": "test", "source": "s1"}]
-
- # Call with default parameters
- score = analyzer.evaluate_evidence_list(evidence_list, constraint)
-
- # Should use 0.2 penalty (default)
- assert isinstance(score, float)
-
- def test_default_negative_weight(self):
- """Default negative_weight should be 0.5."""
- mock_model = MagicMock()
- mock_response = MagicMock()
- mock_response.content = "POSITIVE: 0.5\nNEGATIVE: 0.3\nUNCERTAINTY: 0.2"
- mock_model.invoke = MagicMock(return_value=mock_response)
-
- analyzer = EvidenceAnalyzer(model=mock_model)
- constraint = Constraint(
- id="c1",
- type=ConstraintType.PROPERTY,
- description="Test",
- value="value",
- )
- evidence_list = [{"text": "test", "source": "s1"}]
-
- # Call with default parameters
- score = analyzer.evaluate_evidence_list(evidence_list, constraint)
-
- # Should use 0.5 negative weight (default)
- assert isinstance(score, float)
-
-
-class TestEdgeCases:
- """Tests for edge cases."""
-
- def test_single_evidence_item(self):
- """Should handle single evidence item."""
- mock_model = MagicMock()
- mock_response = MagicMock()
- mock_response.content = "POSITIVE: 0.8\nNEGATIVE: 0.1\nUNCERTAINTY: 0.1"
- mock_model.invoke = MagicMock(return_value=mock_response)
-
- analyzer = EvidenceAnalyzer(model=mock_model)
- constraint = Constraint(
- id="c1",
- type=ConstraintType.PROPERTY,
- description="Test",
- value="value",
- )
- evidence_list = [{"text": "single item", "source": "s1"}]
-
- score = analyzer.evaluate_evidence_list(evidence_list, constraint)
-
- assert isinstance(score, float)
- assert 0.0 <= score <= 1.0
-
- def test_all_high_uncertainty(self):
- """Should handle all high uncertainty evidence."""
- mock_model = MagicMock()
- mock_response = MagicMock()
- mock_response.content = "POSITIVE: 0.1\nNEGATIVE: 0.1\nUNCERTAINTY: 0.8"
- mock_model.invoke = MagicMock(return_value=mock_response)
-
- analyzer = EvidenceAnalyzer(model=mock_model)
- constraint = Constraint(
- id="c1",
- type=ConstraintType.PROPERTY,
- description="Test",
- value="value",
- )
- evidence_list = [
- {"text": "uncertain 1", "source": "s1"},
- {"text": "uncertain 2", "source": "s2"},
- ]
-
- score = analyzer.evaluate_evidence_list(evidence_list, constraint)
-
- # High uncertainty should result in low score
- assert score < 0.5
-
- def test_all_positive_evidence(self):
- """Should handle all positive evidence."""
- mock_model = MagicMock()
- mock_response = MagicMock()
- mock_response.content = (
- "POSITIVE: 0.9\nNEGATIVE: 0.05\nUNCERTAINTY: 0.05"
- )
- mock_model.invoke = MagicMock(return_value=mock_response)
-
- analyzer = EvidenceAnalyzer(model=mock_model)
- constraint = Constraint(
- id="c1",
- type=ConstraintType.PROPERTY,
- description="Test",
- value="value",
- )
- evidence_list = [
- {"text": "positive 1", "source": "s1"},
- {"text": "positive 2", "source": "s2"},
- ]
-
- score = analyzer.evaluate_evidence_list(evidence_list, constraint)
-
- # High positive should result in high score
- assert score > 0.7
-
- def test_all_negative_evidence(self):
- """Should handle all negative evidence."""
- mock_model = MagicMock()
- mock_response = MagicMock()
- mock_response.content = "POSITIVE: 0.1\nNEGATIVE: 0.8\nUNCERTAINTY: 0.1"
- mock_model.invoke = MagicMock(return_value=mock_response)
-
- analyzer = EvidenceAnalyzer(model=mock_model)
- constraint = Constraint(
- id="c1",
- type=ConstraintType.PROPERTY,
- description="Test",
- value="value",
- )
- evidence_list = [
- {"text": "negative 1", "source": "s1"},
- {"text": "negative 2", "source": "s2"},
- ]
-
- score = analyzer.evaluate_evidence_list(evidence_list, constraint)
-
- # High negative should result in low score
- assert score < 0.3
-
- def test_unicode_evidence_text(self):
- """Should handle unicode evidence text."""
- mock_model = MagicMock()
- mock_response = MagicMock()
- mock_response.content = "POSITIVE: 0.5\nNEGATIVE: 0.3\nUNCERTAINTY: 0.2"
- mock_model.invoke = MagicMock(return_value=mock_response)
-
- analyzer = EvidenceAnalyzer(model=mock_model)
- constraint = Constraint(
- id="c1",
- type=ConstraintType.PROPERTY,
- description="Test",
- value="value",
- )
- evidence = {
- "text": "Evidence with unicode: \u65e5\u672c\u8a9e \u4e2d\u6587 \ud55c\uad6d\uc5b4",
- "source": "search",
- }
-
- result = analyzer.analyze_evidence_dual_confidence(evidence, constraint)
-
- assert "\u65e5\u672c\u8a9e" in result.evidence_text
-
- def test_empty_evidence_text(self):
- """Should handle empty evidence text."""
- mock_model = MagicMock()
- mock_response = MagicMock()
- mock_response.content = "POSITIVE: 0.5\nNEGATIVE: 0.3\nUNCERTAINTY: 0.2"
- mock_model.invoke = MagicMock(return_value=mock_response)
-
- analyzer = EvidenceAnalyzer(model=mock_model)
- constraint = Constraint(
- id="c1",
- type=ConstraintType.PROPERTY,
- description="Test",
- value="value",
- )
- evidence = {"text": "", "source": "search"}
-
- result = analyzer.analyze_evidence_dual_confidence(evidence, constraint)
-
- assert result.evidence_text == ""
-
-
-class TestLLMIntegration:
- """Tests for LLM integration behavior."""
-
- def test_invokes_model_with_prompt(self):
- """Should invoke model with formatted prompt."""
- mock_model = MagicMock()
- mock_response = MagicMock()
- mock_response.content = "POSITIVE: 0.5\nNEGATIVE: 0.3\nUNCERTAINTY: 0.2"
- mock_model.invoke = MagicMock(return_value=mock_response)
-
- analyzer = EvidenceAnalyzer(model=mock_model)
- constraint = Constraint(
- id="c1",
- type=ConstraintType.PROPERTY,
- description="Test constraint",
- value="test value",
- )
- evidence = {"text": "Test evidence text", "source": "search"}
-
- analyzer.analyze_evidence_dual_confidence(evidence, constraint)
-
- # Verify model was called
- mock_model.invoke.assert_called_once()
- # Verify prompt contains key elements
- call_args = mock_model.invoke.call_args[0][0]
- assert "test value" in call_args
- assert "Test evidence text" in call_args
-
- def test_handles_various_response_formats(self):
- """Should handle various LLM response formats."""
- mock_model = MagicMock()
- analyzer = EvidenceAnalyzer(model=mock_model)
- constraint = Constraint(
- id="c1",
- type=ConstraintType.PROPERTY,
- description="Test",
- value="value",
- )
- evidence = {"text": "test", "source": "search"}
-
- # Test different response formats
- formats = [
- "POSITIVE: 0.5\nNEGATIVE: 0.3\nUNCERTAINTY: 0.2",
- "POSITIVE: [0.5]\nNEGATIVE: [0.3]\nUNCERTAINTY: [0.2]",
- "positive: 0.5\nnegative: 0.3\nuncertainty: 0.2",
- "Positive: 0.5 Negative: 0.3 Uncertainty: 0.2",
- ]
-
- for fmt in formats:
- mock_response = MagicMock()
- mock_response.content = fmt
- mock_model.invoke = MagicMock(return_value=mock_response)
-
- result = analyzer.analyze_evidence_dual_confidence(
- evidence, constraint
- )
- assert isinstance(result, ConstraintEvidence)
-
-
-class TestConstraintTypeHandling:
- """Tests for handling different constraint types."""
-
- def test_handles_all_constraint_types(self):
- """Should handle all constraint types."""
- mock_model = MagicMock()
- mock_response = MagicMock()
- mock_response.content = "POSITIVE: 0.6\nNEGATIVE: 0.2\nUNCERTAINTY: 0.2"
- mock_model.invoke = MagicMock(return_value=mock_response)
-
- analyzer = EvidenceAnalyzer(model=mock_model)
- evidence = {"text": "test", "source": "search"}
-
- types = [
- ConstraintType.PROPERTY,
- ConstraintType.NAME_PATTERN,
- ConstraintType.EVENT,
- ConstraintType.STATISTIC,
- ConstraintType.TEMPORAL,
- ConstraintType.LOCATION,
- ConstraintType.COMPARISON,
- ConstraintType.EXISTENCE,
- ]
-
- for ctype in types:
- constraint = Constraint(
- id="c1",
- type=ctype,
- description="Test",
- value="value",
- )
-
- result = analyzer.analyze_evidence_dual_confidence(
- evidence, constraint
- )
- assert isinstance(result, ConstraintEvidence)
diff --git a/tests/advanced_search_system/constraint_checking/test_rejection_engine_check_all.py b/tests/advanced_search_system/constraint_checking/test_rejection_engine_check_all.py
deleted file mode 100644
index a2bd839e65..0000000000
--- a/tests/advanced_search_system/constraint_checking/test_rejection_engine_check_all.py
+++ /dev/null
@@ -1,165 +0,0 @@
-"""
-Pure-logic tests for RejectionEngine.check_all_constraints.
-
-These tests actually call check_all_constraints with non-empty constraint
-dicts, using a hashable Constraint subclass to work around the default
-dataclass unhashability. This covers lines 130-143 which are not reached
-by the sibling test file that only calls should_reject_candidate in a loop.
-"""
-
-from unittest.mock import patch
-
-from local_deep_research.advanced_search_system.constraint_checking.evidence_analyzer import (
- ConstraintEvidence,
-)
-from local_deep_research.advanced_search_system.constraint_checking.rejection_engine import (
- RejectionEngine,
-)
-from local_deep_research.advanced_search_system.candidates.base_candidate import (
- Candidate,
-)
-from local_deep_research.advanced_search_system.constraints.base_constraint import (
- Constraint,
- ConstraintType,
-)
-
-
-class HashableConstraint(Constraint):
- """Constraint subclass that can be used as a dict key."""
-
- def __hash__(self):
- return hash(self.id)
-
-
-def _constraint(cid, value="test", ctype=ConstraintType.PROPERTY):
- return HashableConstraint(
- id=cid, type=ctype, description=value, value=value, weight=1.0
- )
-
-
-def _evidence(pos=0.8, neg=0.1):
- return ConstraintEvidence(
- positive_confidence=pos,
- negative_confidence=neg,
- uncertainty=1.0 - pos - neg,
- evidence_text="text",
- source="src",
- )
-
-
-class TestCheckAllConstraintsActual:
- """Call check_all_constraints directly (not via should_reject_candidate)."""
-
- def test_empty_dict_returns_none(self):
- """Empty constraint_results returns None (accepted)."""
- engine = RejectionEngine()
- candidate = Candidate(name="Test")
- with patch(
- "local_deep_research.advanced_search_system.constraint_checking.rejection_engine.logger"
- ):
- result = engine.check_all_constraints(candidate, {})
- assert result is None
-
- def test_single_constraint_passes(self):
- """Single constraint with good evidence returns None."""
- engine = RejectionEngine()
- candidate = Candidate(name="Good Candidate")
- c = _constraint("c1")
- constraint_results = {c: [_evidence(pos=0.8, neg=0.1)]}
- with patch(
- "local_deep_research.advanced_search_system.constraint_checking.rejection_engine.logger"
- ):
- result = engine.check_all_constraints(candidate, constraint_results)
- assert result is None
-
- def test_single_constraint_rejects_high_negative(self):
- """Single constraint with high negative evidence triggers rejection."""
- engine = RejectionEngine(negative_threshold=0.25)
- candidate = Candidate(name="Bad Candidate")
- c = _constraint("c1")
- constraint_results = {c: [_evidence(pos=0.2, neg=0.5)]}
- with patch(
- "local_deep_research.advanced_search_system.constraint_checking.rejection_engine.logger"
- ):
- result = engine.check_all_constraints(candidate, constraint_results)
- assert result is not None
- assert result.should_reject is True
- assert "High negative evidence" in result.reason
-
- def test_single_constraint_rejects_low_positive(self):
- """Single constraint with low positive evidence triggers rejection."""
- engine = RejectionEngine(positive_threshold=0.4)
- candidate = Candidate(name="Weak Candidate")
- c = _constraint("c1")
- constraint_results = {c: [_evidence(pos=0.2, neg=0.1)]}
- with patch(
- "local_deep_research.advanced_search_system.constraint_checking.rejection_engine.logger"
- ):
- result = engine.check_all_constraints(candidate, constraint_results)
- assert result is not None
- assert result.should_reject is True
-
- def test_multiple_constraints_all_pass(self):
- """Multiple constraints all passing returns None."""
- engine = RejectionEngine()
- candidate = Candidate(name="Great Candidate")
- constraint_results = {
- _constraint("c1", "height"): [_evidence(pos=0.8, neg=0.1)],
- _constraint("c2", "weight"): [_evidence(pos=0.7, neg=0.1)],
- _constraint("c3", "color"): [_evidence(pos=0.9, neg=0.05)],
- }
- with patch(
- "local_deep_research.advanced_search_system.constraint_checking.rejection_engine.logger"
- ):
- result = engine.check_all_constraints(candidate, constraint_results)
- assert result is None
-
- def test_stops_at_first_rejection(self):
- """Returns the first rejected constraint, not all of them."""
- engine = RejectionEngine(negative_threshold=0.25)
- candidate = Candidate(name="Test")
- c1 = _constraint("c1", "passes")
- c2 = _constraint("c2", "fails")
- c3 = _constraint("c3", "also_fails")
- constraint_results = {
- c1: [_evidence(pos=0.8, neg=0.1)],
- c2: [_evidence(pos=0.2, neg=0.5)],
- c3: [_evidence(pos=0.1, neg=0.7)],
- }
- with patch(
- "local_deep_research.advanced_search_system.constraint_checking.rejection_engine.logger"
- ):
- result = engine.check_all_constraints(candidate, constraint_results)
- assert result is not None
- assert result.should_reject is True
-
- def test_no_evidence_does_not_reject(self):
- """Constraint with empty evidence list does not trigger rejection."""
- engine = RejectionEngine()
- candidate = Candidate(name="Unknown")
- c = _constraint("c1")
- constraint_results = {c: []}
- with patch(
- "local_deep_research.advanced_search_system.constraint_checking.rejection_engine.logger"
- ):
- result = engine.check_all_constraints(candidate, constraint_results)
- assert result is None
-
- def test_multiple_evidence_per_constraint(self):
- """Multiple evidence items are averaged correctly."""
- engine = RejectionEngine(negative_threshold=0.25)
- candidate = Candidate(name="Test")
- c = _constraint("c1")
- constraint_results = {
- c: [
- _evidence(pos=0.6, neg=0.1),
- _evidence(pos=0.8, neg=0.05),
- _evidence(pos=0.7, neg=0.15),
- ]
- }
- with patch(
- "local_deep_research.advanced_search_system.constraint_checking.rejection_engine.logger"
- ):
- result = engine.check_all_constraints(candidate, constraint_results)
- # avg_pos = 0.7, avg_neg = 0.1 -> should pass
- assert result is None
diff --git a/tests/advanced_search_system/constraint_checking/test_rejection_engine_extended.py b/tests/advanced_search_system/constraint_checking/test_rejection_engine_extended.py
deleted file mode 100644
index b906f313fe..0000000000
--- a/tests/advanced_search_system/constraint_checking/test_rejection_engine_extended.py
+++ /dev/null
@@ -1,745 +0,0 @@
-"""
-Extended tests for RejectionEngine - Constraint-based candidate filtering.
-
-Tests cover:
-- RejectionResult dataclass
-- RejectionEngine initialization
-- should_reject_candidate method
-- check_all_constraints method
-- Threshold logic
-- Edge cases
-
-These tests import and test the ACTUAL RejectionEngine class.
-"""
-
-from local_deep_research.advanced_search_system.candidates.base_candidate import (
- Candidate,
-)
-from local_deep_research.advanced_search_system.constraints.base_constraint import (
- Constraint,
- ConstraintType,
-)
-from local_deep_research.advanced_search_system.constraint_checking.rejection_engine import (
- RejectionEngine,
- RejectionResult,
-)
-from local_deep_research.advanced_search_system.constraint_checking.evidence_analyzer import (
- ConstraintEvidence,
-)
-
-
-class TestRejectionResultDataclass:
- """Tests for RejectionResult dataclass."""
-
- def test_has_should_reject(self):
- """RejectionResult should have should_reject field."""
- result = RejectionResult(
- should_reject=True,
- reason="Test reason",
- constraint_value="value",
- positive_confidence=0.3,
- negative_confidence=0.7,
- )
- assert result.should_reject is True
-
- def test_has_reason(self):
- """RejectionResult should have reason field."""
- result = RejectionResult(
- should_reject=True,
- reason="High negative evidence",
- constraint_value="value",
- positive_confidence=0.3,
- negative_confidence=0.7,
- )
- assert result.reason == "High negative evidence"
-
- def test_has_constraint_value(self):
- """RejectionResult should have constraint_value field."""
- result = RejectionResult(
- should_reject=False,
- reason="OK",
- constraint_value="test_value",
- positive_confidence=0.6,
- negative_confidence=0.2,
- )
- assert result.constraint_value == "test_value"
-
- def test_has_positive_confidence(self):
- """RejectionResult should have positive_confidence field."""
- result = RejectionResult(
- should_reject=False,
- reason="OK",
- constraint_value="value",
- positive_confidence=0.6,
- negative_confidence=0.2,
- )
- assert result.positive_confidence == 0.6
-
- def test_has_negative_confidence(self):
- """RejectionResult should have negative_confidence field."""
- result = RejectionResult(
- should_reject=True,
- reason="Test",
- constraint_value="value",
- positive_confidence=0.2,
- negative_confidence=0.4,
- )
- assert result.negative_confidence == 0.4
-
-
-class TestRejectionEngineInitialization:
- """Tests for RejectionEngine initialization."""
-
- def test_default_negative_threshold(self):
- """Default negative_threshold should be 0.25."""
- engine = RejectionEngine()
- assert engine.negative_threshold == 0.25
-
- def test_default_positive_threshold(self):
- """Default positive_threshold should be 0.4."""
- engine = RejectionEngine()
- assert engine.positive_threshold == 0.4
-
- def test_custom_negative_threshold(self):
- """Should accept custom negative_threshold."""
- engine = RejectionEngine(negative_threshold=0.3)
- assert engine.negative_threshold == 0.3
-
- def test_custom_positive_threshold(self):
- """Should accept custom positive_threshold."""
- engine = RejectionEngine(positive_threshold=0.5)
- assert engine.positive_threshold == 0.5
-
- def test_both_custom_thresholds(self):
- """Should accept both custom thresholds."""
- engine = RejectionEngine(negative_threshold=0.2, positive_threshold=0.6)
- assert engine.negative_threshold == 0.2
- assert engine.positive_threshold == 0.6
-
-
-class TestShouldRejectCandidate:
- """Tests for should_reject_candidate method."""
-
- def test_no_evidence_does_not_reject(self):
- """Should not reject when no evidence available."""
- engine = RejectionEngine()
- candidate = Candidate(name="Test Candidate")
- constraint = Constraint(
- id="c1",
- type=ConstraintType.PROPERTY,
- description="Test constraint",
- value="test_value",
- )
-
- result = engine.should_reject_candidate(candidate, constraint, [])
-
- assert result.should_reject is False
- assert result.reason == "No evidence available"
- assert result.positive_confidence == 0.0
- assert result.negative_confidence == 0.0
-
- def test_calculates_average_positive(self):
- """Should calculate average positive confidence."""
- engine = RejectionEngine()
- candidate = Candidate(name="Test")
- constraint = Constraint(
- id="c1",
- type=ConstraintType.PROPERTY,
- description="Test",
- value="value",
- )
-
- evidence_list = [
- ConstraintEvidence(
- positive_confidence=0.6,
- negative_confidence=0.1,
- uncertainty=0.3,
- evidence_text="text1",
- source="s1",
- ),
- ConstraintEvidence(
- positive_confidence=0.8,
- negative_confidence=0.1,
- uncertainty=0.1,
- evidence_text="text2",
- source="s2",
- ),
- ConstraintEvidence(
- positive_confidence=0.5,
- negative_confidence=0.2,
- uncertainty=0.3,
- evidence_text="text3",
- source="s3",
- ),
- ]
-
- result = engine.should_reject_candidate(
- candidate, constraint, evidence_list
- )
-
- # Average: (0.6 + 0.8 + 0.5) / 3 = 0.633
- assert abs(result.positive_confidence - 0.633) < 0.01
-
- def test_calculates_average_negative(self):
- """Should calculate average negative confidence."""
- engine = RejectionEngine()
- candidate = Candidate(name="Test")
- constraint = Constraint(
- id="c1",
- type=ConstraintType.PROPERTY,
- description="Test",
- value="value",
- )
-
- evidence_list = [
- ConstraintEvidence(
- positive_confidence=0.5,
- negative_confidence=0.2,
- uncertainty=0.3,
- evidence_text="text1",
- source="s1",
- ),
- ConstraintEvidence(
- positive_confidence=0.5,
- negative_confidence=0.1,
- uncertainty=0.4,
- evidence_text="text2",
- source="s2",
- ),
- ConstraintEvidence(
- positive_confidence=0.5,
- negative_confidence=0.3,
- uncertainty=0.2,
- evidence_text="text3",
- source="s3",
- ),
- ]
-
- result = engine.should_reject_candidate(
- candidate, constraint, evidence_list
- )
-
- # Average: (0.2 + 0.1 + 0.3) / 3 = 0.2
- assert abs(result.negative_confidence - 0.2) < 0.001
-
- def test_rejects_high_negative_evidence(self):
- """Should reject when negative evidence exceeds threshold."""
- engine = RejectionEngine(negative_threshold=0.25)
- candidate = Candidate(name="Test")
- constraint = Constraint(
- id="c1",
- type=ConstraintType.PROPERTY,
- description="Test",
- value="test_value",
- )
-
- evidence_list = [
- ConstraintEvidence(
- positive_confidence=0.5,
- negative_confidence=0.3, # Above 0.25 threshold
- uncertainty=0.2,
- evidence_text="text",
- source="s1",
- ),
- ]
-
- result = engine.should_reject_candidate(
- candidate, constraint, evidence_list
- )
-
- assert result.should_reject is True
- assert "High negative evidence" in result.reason
-
- def test_rejects_low_positive_evidence(self):
- """Should reject when positive evidence below threshold."""
- engine = RejectionEngine(positive_threshold=0.4)
- candidate = Candidate(name="Test")
- constraint = Constraint(
- id="c1",
- type=ConstraintType.PROPERTY,
- description="Test",
- value="test_value",
- )
-
- evidence_list = [
- ConstraintEvidence(
- positive_confidence=0.3, # Below 0.4 threshold
- negative_confidence=0.2, # Below negative threshold
- uncertainty=0.5,
- evidence_text="text",
- source="s1",
- ),
- ]
-
- result = engine.should_reject_candidate(
- candidate, constraint, evidence_list
- )
-
- assert result.should_reject is True
- assert "Insufficient positive evidence" in result.reason
-
- def test_accepts_when_constraints_satisfied(self):
- """Should accept when constraints satisfied."""
- engine = RejectionEngine(
- negative_threshold=0.25, positive_threshold=0.4
- )
- candidate = Candidate(name="Test")
- constraint = Constraint(
- id="c1",
- type=ConstraintType.PROPERTY,
- description="Test",
- value="test_value",
- )
-
- evidence_list = [
- ConstraintEvidence(
- positive_confidence=0.6, # Above 0.4
- negative_confidence=0.1, # Below 0.25
- uncertainty=0.3,
- evidence_text="text",
- source="s1",
- ),
- ]
-
- result = engine.should_reject_candidate(
- candidate, constraint, evidence_list
- )
-
- assert result.should_reject is False
- assert result.reason == "Constraints satisfied"
-
- def test_primary_rule_takes_precedence(self):
- """Primary rejection rule (high negative) should take precedence."""
- engine = RejectionEngine(
- negative_threshold=0.25, positive_threshold=0.4
- )
- candidate = Candidate(name="Test")
- constraint = Constraint(
- id="c1",
- type=ConstraintType.PROPERTY,
- description="Test",
- value="test_value",
- )
-
- evidence_list = [
- ConstraintEvidence(
- positive_confidence=0.3, # Would trigger secondary rule
- negative_confidence=0.5, # Would trigger primary rule
- uncertainty=0.2,
- evidence_text="text",
- source="s1",
- ),
- ]
-
- result = engine.should_reject_candidate(
- candidate, constraint, evidence_list
- )
-
- assert result.should_reject is True
- assert "High negative evidence" in result.reason
-
-
-class TestThresholdBehavior:
- """Tests for threshold behavior."""
-
- def test_exactly_at_negative_threshold(self):
- """Should not reject when exactly at negative threshold."""
- engine = RejectionEngine(
- negative_threshold=0.25, positive_threshold=0.4
- )
- candidate = Candidate(name="Test")
- constraint = Constraint(
- id="c1",
- type=ConstraintType.PROPERTY,
- description="Test",
- value="value",
- )
-
- evidence_list = [
- ConstraintEvidence(
- positive_confidence=0.5,
- negative_confidence=0.25, # Exactly at threshold
- uncertainty=0.25,
- evidence_text="text",
- source="s1",
- ),
- ]
-
- result = engine.should_reject_candidate(
- candidate, constraint, evidence_list
- )
-
- # > not >= so exactly at threshold should not reject
- assert result.should_reject is False
-
- def test_exactly_at_positive_threshold(self):
- """Should not reject when exactly at positive threshold."""
- engine = RejectionEngine(
- negative_threshold=0.25, positive_threshold=0.4
- )
- candidate = Candidate(name="Test")
- constraint = Constraint(
- id="c1",
- type=ConstraintType.PROPERTY,
- description="Test",
- value="value",
- )
-
- evidence_list = [
- ConstraintEvidence(
- positive_confidence=0.4, # Exactly at threshold
- negative_confidence=0.2,
- uncertainty=0.4,
- evidence_text="text",
- source="s1",
- ),
- ]
-
- result = engine.should_reject_candidate(
- candidate, constraint, evidence_list
- )
-
- # < not <= so exactly at threshold should not reject
- assert result.should_reject is False
-
- def test_just_above_negative_threshold(self):
- """Should reject when just above negative threshold."""
- engine = RejectionEngine(negative_threshold=0.25)
- candidate = Candidate(name="Test")
- constraint = Constraint(
- id="c1",
- type=ConstraintType.PROPERTY,
- description="Test",
- value="value",
- )
-
- evidence_list = [
- ConstraintEvidence(
- positive_confidence=0.5,
- negative_confidence=0.251, # Just above threshold
- uncertainty=0.249,
- evidence_text="text",
- source="s1",
- ),
- ]
-
- result = engine.should_reject_candidate(
- candidate, constraint, evidence_list
- )
-
- assert result.should_reject is True
-
- def test_just_below_positive_threshold(self):
- """Should reject when just below positive threshold."""
- engine = RejectionEngine(
- negative_threshold=0.25, positive_threshold=0.4
- )
- candidate = Candidate(name="Test")
- constraint = Constraint(
- id="c1",
- type=ConstraintType.PROPERTY,
- description="Test",
- value="value",
- )
-
- evidence_list = [
- ConstraintEvidence(
- positive_confidence=0.399, # Just below threshold
- negative_confidence=0.1,
- uncertainty=0.501,
- evidence_text="text",
- source="s1",
- ),
- ]
-
- result = engine.should_reject_candidate(
- candidate, constraint, evidence_list
- )
-
- assert result.should_reject is True
-
-
-class TestReasonFormatting:
- """Tests for reason formatting."""
-
- def test_negative_evidence_percentage_format(self):
- """Should format negative evidence as percentage."""
- engine = RejectionEngine(negative_threshold=0.25)
- candidate = Candidate(name="Test")
- constraint = Constraint(
- id="c1",
- type=ConstraintType.PROPERTY,
- description="Test",
- value="value",
- )
-
- evidence_list = [
- ConstraintEvidence(
- positive_confidence=0.5,
- negative_confidence=0.35,
- uncertainty=0.15,
- evidence_text="text",
- source="s1",
- ),
- ]
-
- result = engine.should_reject_candidate(
- candidate, constraint, evidence_list
- )
-
- assert "35%" in result.reason
-
- def test_positive_evidence_percentage_format(self):
- """Should format positive evidence as percentage."""
- engine = RejectionEngine(
- negative_threshold=0.25, positive_threshold=0.4
- )
- candidate = Candidate(name="Test")
- constraint = Constraint(
- id="c1",
- type=ConstraintType.PROPERTY,
- description="Test",
- value="value",
- )
-
- evidence_list = [
- ConstraintEvidence(
- positive_confidence=0.25, # Below threshold
- negative_confidence=0.1,
- uncertainty=0.65,
- evidence_text="text",
- source="s1",
- ),
- ]
-
- result = engine.should_reject_candidate(
- candidate, constraint, evidence_list
- )
-
- assert "25%" in result.reason
-
-
-class TestEdgeCases:
- """Tests for edge cases."""
-
- def test_single_evidence_item(self):
- """Should handle single evidence item."""
- engine = RejectionEngine()
- candidate = Candidate(name="Test")
- constraint = Constraint(
- id="c1",
- type=ConstraintType.PROPERTY,
- description="Test",
- value="value",
- )
-
- evidence_list = [
- ConstraintEvidence(
- positive_confidence=0.7,
- negative_confidence=0.1,
- uncertainty=0.2,
- evidence_text="text",
- source="s1",
- ),
- ]
-
- result = engine.should_reject_candidate(
- candidate, constraint, evidence_list
- )
-
- assert result.positive_confidence == 0.7
- assert result.negative_confidence == 0.1
-
- def test_many_evidence_items(self):
- """Should handle many evidence items."""
- engine = RejectionEngine()
- candidate = Candidate(name="Test")
- constraint = Constraint(
- id="c1",
- type=ConstraintType.PROPERTY,
- description="Test",
- value="value",
- )
-
- evidence_list = [
- ConstraintEvidence(
- positive_confidence=0.5,
- negative_confidence=0.2,
- uncertainty=0.3,
- evidence_text=f"text{i}",
- source=f"s{i}",
- )
- for i in range(100)
- ]
-
- result = engine.should_reject_candidate(
- candidate, constraint, evidence_list
- )
-
- assert result.positive_confidence == 0.5
- assert result.negative_confidence == 0.2
-
- def test_all_zero_confidence(self):
- """Should handle all zero confidence."""
- engine = RejectionEngine(positive_threshold=0.4)
- candidate = Candidate(name="Test")
- constraint = Constraint(
- id="c1",
- type=ConstraintType.PROPERTY,
- description="Test",
- value="value",
- )
-
- evidence_list = [
- ConstraintEvidence(
- positive_confidence=0.0,
- negative_confidence=0.0,
- uncertainty=1.0,
- evidence_text="text",
- source="s1",
- ),
- ]
-
- result = engine.should_reject_candidate(
- candidate, constraint, evidence_list
- )
-
- # Should reject due to low positive
- assert result.should_reject is True
-
- def test_all_high_positive(self):
- """Should handle all high positive evidence."""
- engine = RejectionEngine()
- candidate = Candidate(name="Test")
- constraint = Constraint(
- id="c1",
- type=ConstraintType.PROPERTY,
- description="Test",
- value="value",
- )
-
- evidence_list = [
- ConstraintEvidence(
- positive_confidence=0.9,
- negative_confidence=0.05,
- uncertainty=0.05,
- evidence_text="text1",
- source="s1",
- ),
- ConstraintEvidence(
- positive_confidence=0.95,
- negative_confidence=0.03,
- uncertainty=0.02,
- evidence_text="text2",
- source="s2",
- ),
- ]
-
- result = engine.should_reject_candidate(
- candidate, constraint, evidence_list
- )
-
- assert result.should_reject is False
-
- def test_all_high_negative(self):
- """Should handle all high negative evidence."""
- engine = RejectionEngine()
- candidate = Candidate(name="Test")
- constraint = Constraint(
- id="c1",
- type=ConstraintType.PROPERTY,
- description="Test",
- value="value",
- )
-
- evidence_list = [
- ConstraintEvidence(
- positive_confidence=0.1,
- negative_confidence=0.8,
- uncertainty=0.1,
- evidence_text="text1",
- source="s1",
- ),
- ConstraintEvidence(
- positive_confidence=0.15,
- negative_confidence=0.75,
- uncertainty=0.1,
- evidence_text="text2",
- source="s2",
- ),
- ]
-
- result = engine.should_reject_candidate(
- candidate, constraint, evidence_list
- )
-
- assert result.should_reject is True
-
-
-class TestCandidateLogging:
- """Tests for candidate logging.
-
- Note: Logging is tested via should_reject_candidate results since
- check_all_constraints is the one that logs. We verify the result
- format which would trigger specific log messages.
- """
-
- def test_rejection_result_contains_info_for_logging(self):
- """Rejection result should contain info needed for logging."""
- engine = RejectionEngine()
- candidate = Candidate(name="Test Candidate")
- constraint = Constraint(
- id="c1",
- type=ConstraintType.PROPERTY,
- description="Test constraint",
- value="test_constraint",
- )
-
- evidence_list = [
- ConstraintEvidence(
- positive_confidence=0.1,
- negative_confidence=0.8,
- uncertainty=0.1,
- evidence_text="text",
- source="s1",
- ),
- ]
-
- result = engine.should_reject_candidate(
- candidate, constraint, evidence_list
- )
-
- # Verify result has all info needed for logging
- assert result.should_reject is True
- assert result.constraint_value == "test_constraint"
- assert "High negative evidence" in result.reason
-
- def test_acceptance_result_contains_info_for_logging(self):
- """Acceptance result should contain info needed for logging."""
- engine = RejectionEngine()
- candidate = Candidate(name="Test Candidate")
- constraint = Constraint(
- id="c1",
- type=ConstraintType.PROPERTY,
- description="Test constraint",
- value="test_constraint",
- )
-
- evidence_list = [
- ConstraintEvidence(
- positive_confidence=0.8,
- negative_confidence=0.1,
- uncertainty=0.1,
- evidence_text="text",
- source="s1",
- ),
- ]
-
- result = engine.should_reject_candidate(
- candidate, constraint, evidence_list
- )
-
- # Verify result has all info needed for logging
- assert result.should_reject is False
- assert result.constraint_value == "test_constraint"
- assert result.reason == "Constraints satisfied"
diff --git a/tests/advanced_search_system/constraint_checking/test_strict_checker.py b/tests/advanced_search_system/constraint_checking/test_strict_checker.py
deleted file mode 100644
index 97ffac395c..0000000000
--- a/tests/advanced_search_system/constraint_checking/test_strict_checker.py
+++ /dev/null
@@ -1,649 +0,0 @@
-"""
-Tests for the StrictChecker class.
-
-Tests cover:
-- Initialization with strict thresholds
-- NAME_PATTERN constraint handling
-- Body part name pattern checking
-- Strict evaluation criteria
-- LLM prompt generation
-- Rejection decisions
-"""
-
-from dataclasses import dataclass
-from enum import Enum
-from unittest.mock import Mock
-
-
-class MockConstraintType(Enum):
- """Mock constraint type for testing."""
-
- PROPERTY = "property"
- NAME_PATTERN = "name_pattern"
- EVENT = "event"
-
-
-@dataclass
-class MockCandidate:
- """Mock candidate for testing."""
-
- name: str
- value: str = ""
-
-
-@dataclass
-class MockConstraint:
- """Mock constraint for testing."""
-
- value: str
- weight: float = 1.0
- type: MockConstraintType = MockConstraintType.PROPERTY
-
-
-class TestStrictCheckerInit:
- """Tests for StrictChecker initialization."""
-
- def test_init_with_defaults(self):
- """Initialize with default strict thresholds."""
- from local_deep_research.advanced_search_system.constraint_checking.strict_checker import (
- StrictChecker,
- )
-
- mock_model = Mock()
- checker = StrictChecker(mock_model)
-
- assert checker.strict_threshold == 0.9
- assert checker.name_pattern_required is True
-
- def test_init_with_custom_strict_threshold(self):
- """Initialize with custom strict threshold."""
- from local_deep_research.advanced_search_system.constraint_checking.strict_checker import (
- StrictChecker,
- )
-
- mock_model = Mock()
- checker = StrictChecker(mock_model, strict_threshold=0.95)
-
- assert checker.strict_threshold == 0.95
-
- def test_init_with_name_pattern_not_required(self):
- """Initialize with name_pattern_required False."""
- from local_deep_research.advanced_search_system.constraint_checking.strict_checker import (
- StrictChecker,
- )
-
- mock_model = Mock()
- checker = StrictChecker(mock_model, name_pattern_required=False)
-
- assert checker.name_pattern_required is False
-
- def test_init_stores_model(self):
- """Initialization stores model reference."""
- from local_deep_research.advanced_search_system.constraint_checking.strict_checker import (
- StrictChecker,
- )
-
- mock_model = Mock()
- checker = StrictChecker(mock_model)
-
- assert checker.model is mock_model
-
- def test_init_stores_evidence_gatherer(self):
- """Initialization stores evidence gatherer."""
- from local_deep_research.advanced_search_system.constraint_checking.strict_checker import (
- StrictChecker,
- )
-
- mock_model = Mock()
- mock_gatherer = Mock()
- checker = StrictChecker(mock_model, evidence_gatherer=mock_gatherer)
-
- assert checker.evidence_gatherer is mock_gatherer
-
-
-class TestCheckNamePatternStrictly:
- """Tests for _check_name_pattern_strictly method."""
-
- def test_finds_body_part_arm(self):
- """Finds 'arm' body part in name."""
- from local_deep_research.advanced_search_system.constraint_checking.strict_checker import (
- StrictChecker,
- )
-
- mock_model = Mock()
- checker = StrictChecker(mock_model)
-
- score = checker._check_name_pattern_strictly(
- "Strong Arm Mountain", "contains body part"
- )
-
- assert score == 1.0
-
- def test_finds_body_part_foot(self):
- """Finds 'foot' body part in name."""
- from local_deep_research.advanced_search_system.constraint_checking.strict_checker import (
- StrictChecker,
- )
-
- mock_model = Mock()
- checker = StrictChecker(mock_model)
-
- score = checker._check_name_pattern_strictly(
- "Bigfoot Trail", "body part in name"
- )
-
- assert score == 1.0
-
- def test_finds_body_part_heart(self):
- """Finds 'heart' body part in name."""
- from local_deep_research.advanced_search_system.constraint_checking.strict_checker import (
- StrictChecker,
- )
-
- mock_model = Mock()
- checker = StrictChecker(mock_model)
-
- score = checker._check_name_pattern_strictly(
- "Heart Lake", "must contain body part"
- )
-
- assert score == 1.0
-
- def test_finds_body_part_knee(self):
- """Finds 'knee' body part in name."""
- from local_deep_research.advanced_search_system.constraint_checking.strict_checker import (
- StrictChecker,
- )
-
- mock_model = Mock()
- checker = StrictChecker(mock_model)
-
- score = checker._check_name_pattern_strictly(
- "Wounded Knee Creek", "body part"
- )
-
- assert score == 1.0
-
- def test_no_body_part_returns_zero(self):
- """Returns 0.0 when no body part found."""
- from local_deep_research.advanced_search_system.constraint_checking.strict_checker import (
- StrictChecker,
- )
-
- mock_model = Mock()
- checker = StrictChecker(mock_model)
-
- score = checker._check_name_pattern_strictly(
- "Pine Mountain Trail", "contains body part"
- )
-
- assert score == 0.0
-
- def test_body_part_case_insensitive(self):
- """Body part check is case insensitive."""
- from local_deep_research.advanced_search_system.constraint_checking.strict_checker import (
- StrictChecker,
- )
-
- mock_model = Mock()
- checker = StrictChecker(mock_model)
-
- score = checker._check_name_pattern_strictly(
- "HAND CREEK TRAIL", "body part"
- )
-
- assert score == 1.0
-
- def test_uses_llm_for_non_body_part_patterns(self):
- """Uses LLM for non-body-part patterns."""
- from local_deep_research.advanced_search_system.constraint_checking.strict_checker import (
- StrictChecker,
- )
-
- mock_model = Mock()
- mock_model.invoke.return_value.content = "Score: 0.95"
- checker = StrictChecker(mock_model)
-
- score = checker._check_name_pattern_strictly(
- "Crystal Lake", "name must start with C"
- )
-
- assert score == 0.95
- mock_model.invoke.assert_called_once()
-
- def test_llm_pattern_returns_uncertain_on_exception(self):
- """Returns 0.5 (uncertain) when LLM fails for pattern check."""
- from local_deep_research.advanced_search_system.constraint_checking.strict_checker import (
- StrictChecker,
- )
-
- mock_model = Mock()
- mock_model.invoke.side_effect = Exception("LLM error")
- checker = StrictChecker(mock_model)
-
- score = checker._check_name_pattern_strictly(
- "Test Name", "starts with T"
- )
-
- assert score == 0.5
-
-
-class TestEvaluateConstraintStrictly:
- """Tests for _evaluate_constraint_strictly method."""
-
- def test_returns_zero_for_empty_evidence(self):
- """Returns 0.0 when no evidence provided."""
- from local_deep_research.advanced_search_system.constraint_checking.strict_checker import (
- StrictChecker,
- )
-
- mock_model = Mock()
- checker = StrictChecker(mock_model)
-
- candidate = MockCandidate(name="Test")
- constraint = MockConstraint(value="must be valid")
-
- score = checker._evaluate_constraint_strictly(candidate, constraint, [])
-
- assert score == 0.0
-
- def test_uses_name_pattern_check_for_name_pattern_type(self):
- """Uses name pattern check for NAME_PATTERN constraints."""
- from local_deep_research.advanced_search_system.constraint_checking.strict_checker import (
- StrictChecker,
- )
- from local_deep_research.advanced_search_system.constraints.base_constraint import (
- ConstraintType,
- Constraint,
- )
-
- mock_model = Mock()
- checker = StrictChecker(mock_model)
-
- candidate = MockCandidate(name="Heart Mountain")
- constraint = Constraint(
- id="c1",
- type=ConstraintType.NAME_PATTERN,
- description="Contains body part",
- value="body part in name",
- )
- evidence = [{"text": "some evidence"}]
-
- score = checker._evaluate_constraint_strictly(
- candidate, constraint, evidence
- )
-
- assert score == 1.0 # Heart is a body part
-
- def test_uses_llm_for_property_constraints(self):
- """Uses LLM evaluation for PROPERTY constraints."""
- from local_deep_research.advanced_search_system.constraint_checking.strict_checker import (
- StrictChecker,
- )
- from local_deep_research.advanced_search_system.constraints.base_constraint import (
- ConstraintType,
- Constraint,
- )
-
- mock_model = Mock()
- mock_model.invoke.return_value.content = "0.92"
- checker = StrictChecker(mock_model)
-
- candidate = MockCandidate(name="Test Candidate")
- constraint = Constraint(
- id="c1",
- type=ConstraintType.PROPERTY,
- description="Must be old",
- value="formed during ice age",
- )
- evidence = [{"text": "Formed during the ice age"}]
-
- score = checker._evaluate_constraint_strictly(
- candidate, constraint, evidence
- )
-
- assert score == 0.92
-
- def test_strict_prompt_mentions_strict(self):
- """LLM prompt emphasizes strict evaluation."""
- from local_deep_research.advanced_search_system.constraint_checking.strict_checker import (
- StrictChecker,
- )
- from local_deep_research.advanced_search_system.constraints.base_constraint import (
- ConstraintType,
- Constraint,
- )
-
- mock_model = Mock()
- mock_model.invoke.return_value.content = "0.8"
- checker = StrictChecker(mock_model)
-
- candidate = MockCandidate(name="Test")
- constraint = Constraint(
- id="c1",
- type=ConstraintType.PROPERTY,
- description="test",
- value="test",
- )
- evidence = [{"text": "evidence"}]
-
- checker._evaluate_constraint_strictly(candidate, constraint, evidence)
-
- call_args = mock_model.invoke.call_args[0][0]
- assert "STRICT" in call_args or "strict" in call_args
-
- def test_truncates_evidence_text(self):
- """Truncates long evidence text in prompt."""
- from local_deep_research.advanced_search_system.constraint_checking.strict_checker import (
- StrictChecker,
- )
- from local_deep_research.advanced_search_system.constraints.base_constraint import (
- ConstraintType,
- Constraint,
- )
-
- mock_model = Mock()
- mock_model.invoke.return_value.content = "0.9"
- checker = StrictChecker(mock_model)
-
- candidate = MockCandidate(name="Test")
- constraint = Constraint(
- id="c1",
- type=ConstraintType.PROPERTY,
- description="test",
- value="test",
- )
- evidence = [{"text": "A" * 1000}] # Very long text
-
- checker._evaluate_constraint_strictly(candidate, constraint, evidence)
-
- # Verify evidence is truncated (uses first 300 chars per evidence, 2 evidences max)
- call_args = mock_model.invoke.call_args[0][0]
- # The code truncates to 300 chars, but may include up to 2 evidence items
- assert call_args.count("A") <= 600 # Max 2 evidence * 300 chars each
-
-
-class TestShouldRejectCandidate:
- """Tests for should_reject_candidate method."""
-
- def test_rejects_when_no_evidence(self):
- """Rejects candidate when no evidence available."""
- from local_deep_research.advanced_search_system.constraint_checking.strict_checker import (
- StrictChecker,
- )
-
- mock_model = Mock()
- checker = StrictChecker(mock_model)
-
- candidate = MockCandidate(name="Test")
- constraint = MockConstraint(value="constraint")
-
- should_reject, reason = checker.should_reject_candidate(
- candidate, constraint, []
- )
-
- assert should_reject is True
- assert "No evidence" in reason
-
- def test_rejects_name_pattern_below_095(self):
- """Rejects NAME_PATTERN constraints below 0.95."""
- from local_deep_research.advanced_search_system.constraint_checking.strict_checker import (
- StrictChecker,
- )
- from local_deep_research.advanced_search_system.constraints.base_constraint import (
- ConstraintType,
- Constraint,
- )
-
- mock_model = Mock()
- mock_model.invoke.return_value.content = "0.9"
- checker = StrictChecker(mock_model)
-
- candidate = MockCandidate(name="Pine Trail")
- constraint = Constraint(
- id="c1",
- type=ConstraintType.NAME_PATTERN,
- description="body part",
- value="contains body part",
- )
- evidence = [{"text": "evidence"}]
-
- should_reject, reason = checker.should_reject_candidate(
- candidate, constraint, evidence
- )
-
- assert should_reject is True
- assert "NAME_PATTERN" in reason
-
- def test_accepts_name_pattern_at_095_or_above(self):
- """Accepts NAME_PATTERN constraints at 0.95 or above."""
- from local_deep_research.advanced_search_system.constraint_checking.strict_checker import (
- StrictChecker,
- )
- from local_deep_research.advanced_search_system.constraints.base_constraint import (
- ConstraintType,
- Constraint,
- )
-
- mock_model = Mock()
- checker = StrictChecker(mock_model)
-
- candidate = MockCandidate(name="Heart Mountain")
- constraint = Constraint(
- id="c1",
- type=ConstraintType.NAME_PATTERN,
- description="body part",
- value="body part",
- )
- evidence = [{"text": "evidence"}]
-
- should_reject, _ = checker.should_reject_candidate(
- candidate, constraint, evidence
- )
-
- assert should_reject is False
-
- def test_rejects_below_strict_threshold(self):
- """Rejects when score below strict threshold."""
- from local_deep_research.advanced_search_system.constraint_checking.strict_checker import (
- StrictChecker,
- )
- from local_deep_research.advanced_search_system.constraints.base_constraint import (
- ConstraintType,
- Constraint,
- )
-
- mock_model = Mock()
- mock_model.invoke.return_value.content = "0.85" # Below 0.9
- checker = StrictChecker(mock_model)
-
- candidate = MockCandidate(name="Test")
- constraint = Constraint(
- id="c1",
- type=ConstraintType.PROPERTY,
- description="test",
- value="test",
- )
- evidence = [{"text": "evidence"}]
-
- should_reject, reason = checker.should_reject_candidate(
- candidate, constraint, evidence
- )
-
- assert should_reject is True
- assert "strict threshold" in reason.lower()
-
- def test_name_pattern_not_required_uses_standard_threshold(self):
- """When name_pattern_required=False, uses standard 0.9 threshold instead of 0.95."""
- from local_deep_research.advanced_search_system.constraint_checking.strict_checker import (
- StrictChecker,
- )
- from local_deep_research.advanced_search_system.constraints.base_constraint import (
- ConstraintType,
- Constraint,
- )
-
- mock_model = Mock()
- # For NAME_PATTERN with body part, it uses _check_name_pattern_strictly
- # which returns 1.0 for "Heart Trail" (has body part)
- checker = StrictChecker(mock_model, name_pattern_required=False)
-
- # Use a name that has a body part so the pattern check passes
- candidate = MockCandidate(name="Heart Trail")
- constraint = Constraint(
- id="c1",
- type=ConstraintType.NAME_PATTERN,
- description="body part",
- value="body part",
- )
- evidence = [{"text": "evidence"}]
-
- should_reject, _ = checker.should_reject_candidate(
- candidate, constraint, evidence
- )
-
- # Should pass - body part "heart" found, returns 1.0 which is >= 0.9
- assert should_reject is False
-
-
-class TestCheckCandidate:
- """Tests for check_candidate method."""
-
- def test_returns_constraint_check_result(self):
- """Returns ConstraintCheckResult with all fields."""
- from local_deep_research.advanced_search_system.constraint_checking.strict_checker import (
- StrictChecker,
- )
-
- mock_model = Mock()
- mock_model.invoke.return_value.content = "0.95"
- mock_gatherer = Mock(return_value=[{"text": "evidence"}])
- checker = StrictChecker(mock_model, evidence_gatherer=mock_gatherer)
-
- candidate = MockCandidate(name="Test")
- constraints = [MockConstraint(value="c1")]
-
- result = checker.check_candidate(candidate, constraints)
-
- assert hasattr(result, "total_score")
- assert hasattr(result, "should_reject")
- assert hasattr(result, "constraint_scores")
-
- def test_total_score_1_when_all_pass_strict(self):
- """Total score is 1.0 when all constraints pass strict threshold."""
- from local_deep_research.advanced_search_system.constraint_checking.strict_checker import (
- StrictChecker,
- )
-
- mock_model = Mock()
- mock_model.invoke.return_value.content = "0.95"
- mock_gatherer = Mock(return_value=[{"text": "evidence"}])
- checker = StrictChecker(mock_model, evidence_gatherer=mock_gatherer)
-
- candidate = MockCandidate(name="Test")
- constraints = [MockConstraint(value="c1"), MockConstraint(value="c2")]
-
- result = checker.check_candidate(candidate, constraints)
-
- assert result.should_reject is False
- assert result.total_score == 1.0
-
- def test_total_score_0_when_any_fail_strict(self):
- """Total score is 0.0 when any constraint fails strict threshold."""
- from local_deep_research.advanced_search_system.constraint_checking.strict_checker import (
- StrictChecker,
- )
-
- mock_model = Mock()
- mock_model.invoke.return_value.content = "0.85" # Below 0.9
- mock_gatherer = Mock(return_value=[{"text": "evidence"}])
- checker = StrictChecker(mock_model, evidence_gatherer=mock_gatherer)
-
- candidate = MockCandidate(name="Test")
- constraints = [MockConstraint(value="c1")]
-
- result = checker.check_candidate(candidate, constraints)
-
- assert result.should_reject is True
- assert result.total_score == 0.0
-
- def test_stores_strict_pass_in_constraint_scores(self):
- """Stores strict_pass boolean in constraint scores."""
- from local_deep_research.advanced_search_system.constraint_checking.strict_checker import (
- StrictChecker,
- )
-
- mock_model = Mock()
- mock_model.invoke.return_value.content = "0.92"
- mock_gatherer = Mock(return_value=[{"text": "evidence"}])
- checker = StrictChecker(mock_model, evidence_gatherer=mock_gatherer)
-
- candidate = MockCandidate(name="Test")
- constraints = [MockConstraint(value="c1")]
-
- result = checker.check_candidate(candidate, constraints)
-
- assert "strict_pass" in result.constraint_scores["c1"]
- assert (
- result.constraint_scores["c1"]["strict_pass"] is True
- ) # 0.92 >= 0.9
-
- def test_detailed_results_contain_strict_pass(self):
- """Detailed results contain strict_pass field."""
- from local_deep_research.advanced_search_system.constraint_checking.strict_checker import (
- StrictChecker,
- )
-
- mock_model = Mock()
- mock_model.invoke.return_value.content = "0.88"
- mock_gatherer = Mock(return_value=[{"text": "evidence"}])
- checker = StrictChecker(mock_model, evidence_gatherer=mock_gatherer)
-
- candidate = MockCandidate(name="Test")
- constraints = [MockConstraint(value="c1")]
-
- result = checker.check_candidate(candidate, constraints)
-
- assert result.detailed_results[0]["strict_pass"] is False # 0.88 < 0.9
-
- def test_records_first_rejection_reason(self):
- """Records first rejection reason when multiple constraints fail."""
- from local_deep_research.advanced_search_system.constraint_checking.strict_checker import (
- StrictChecker,
- )
-
- mock_model = Mock()
- mock_model.invoke.return_value.content = "0.5" # Below threshold
- mock_gatherer = Mock(return_value=[{"text": "evidence"}])
- checker = StrictChecker(mock_model, evidence_gatherer=mock_gatherer)
-
- candidate = MockCandidate(name="Test")
- constraints = [MockConstraint(value="c1"), MockConstraint(value="c2")]
-
- result = checker.check_candidate(candidate, constraints)
-
- assert result.should_reject is True
- assert result.rejection_reason is not None
- assert "c1" in result.rejection_reason # First constraint
-
- def test_uses_custom_strict_threshold(self):
- """Uses custom strict threshold for evaluation."""
- from local_deep_research.advanced_search_system.constraint_checking.strict_checker import (
- StrictChecker,
- )
-
- mock_model = Mock()
- mock_model.invoke.return_value.content = "0.8"
- mock_gatherer = Mock(return_value=[{"text": "evidence"}])
- checker = StrictChecker(
- mock_model, evidence_gatherer=mock_gatherer, strict_threshold=0.75
- )
-
- candidate = MockCandidate(name="Test")
- constraints = [MockConstraint(value="c1")]
-
- result = checker.check_candidate(candidate, constraints)
-
- # 0.8 >= 0.75, so should pass
- assert result.should_reject is False
- assert result.constraint_scores["c1"]["strict_pass"] is True
diff --git a/tests/advanced_search_system/constraint_checking/test_threshold_checker.py b/tests/advanced_search_system/constraint_checking/test_threshold_checker.py
deleted file mode 100644
index 69f38e0008..0000000000
--- a/tests/advanced_search_system/constraint_checking/test_threshold_checker.py
+++ /dev/null
@@ -1,600 +0,0 @@
-"""
-Tests for the ThresholdChecker class.
-
-Tests cover:
-- Initialization with custom thresholds
-- Constraint satisfaction checking
-- Candidate rejection decisions
-- Evidence handling
-- Score calculation
-- LLM response parsing
-"""
-
-from dataclasses import dataclass
-from enum import Enum
-from unittest.mock import Mock
-
-
-class MockConstraintType(Enum):
- """Mock constraint type for testing."""
-
- PROPERTY = "property"
- NAME_PATTERN = "name_pattern"
-
-
-@dataclass
-class MockCandidate:
- """Mock candidate for testing."""
-
- name: str
- value: str = ""
-
-
-@dataclass
-class MockConstraint:
- """Mock constraint for testing."""
-
- value: str
- weight: float = 1.0
- type: MockConstraintType = MockConstraintType.PROPERTY
-
-
-class TestThresholdCheckerInit:
- """Tests for ThresholdChecker initialization."""
-
- def test_init_with_defaults(self):
- """Initialize with default thresholds."""
- from local_deep_research.advanced_search_system.constraint_checking.threshold_checker import (
- ThresholdChecker,
- )
-
- mock_model = Mock()
- checker = ThresholdChecker(mock_model)
-
- assert checker.satisfaction_threshold == 0.7
- assert checker.required_satisfaction_rate == 0.8
-
- def test_init_with_custom_satisfaction_threshold(self):
- """Initialize with custom satisfaction threshold."""
- from local_deep_research.advanced_search_system.constraint_checking.threshold_checker import (
- ThresholdChecker,
- )
-
- mock_model = Mock()
- checker = ThresholdChecker(mock_model, satisfaction_threshold=0.5)
-
- assert checker.satisfaction_threshold == 0.5
-
- def test_init_with_custom_required_satisfaction_rate(self):
- """Initialize with custom required satisfaction rate."""
- from local_deep_research.advanced_search_system.constraint_checking.threshold_checker import (
- ThresholdChecker,
- )
-
- mock_model = Mock()
- checker = ThresholdChecker(mock_model, required_satisfaction_rate=0.6)
-
- assert checker.required_satisfaction_rate == 0.6
-
- def test_init_stores_model(self):
- """Initialization stores model reference."""
- from local_deep_research.advanced_search_system.constraint_checking.threshold_checker import (
- ThresholdChecker,
- )
-
- mock_model = Mock()
- checker = ThresholdChecker(mock_model)
-
- assert checker.model is mock_model
-
- def test_init_stores_evidence_gatherer(self):
- """Initialization stores evidence gatherer."""
- from local_deep_research.advanced_search_system.constraint_checking.threshold_checker import (
- ThresholdChecker,
- )
-
- mock_model = Mock()
- mock_gatherer = Mock()
- checker = ThresholdChecker(mock_model, evidence_gatherer=mock_gatherer)
-
- assert checker.evidence_gatherer is mock_gatherer
-
-
-class TestCheckConstraintSatisfaction:
- """Tests for _check_constraint_satisfaction method."""
-
- def test_extracts_score_from_llm_response(self):
- """Extracts score from LLM response."""
- from local_deep_research.advanced_search_system.constraint_checking.threshold_checker import (
- ThresholdChecker,
- )
-
- mock_model = Mock()
- mock_model.invoke.return_value.content = "Score: 0.85"
- checker = ThresholdChecker(mock_model)
-
- candidate = MockCandidate(name="Test Candidate")
- constraint = MockConstraint(value="must be valid")
- evidence = [{"text": "Evidence text"}]
-
- score = checker._check_constraint_satisfaction(
- candidate, constraint, evidence
- )
-
- assert score == 0.85
-
- def test_extracts_integer_score(self):
- """Extracts integer score from LLM response."""
- from local_deep_research.advanced_search_system.constraint_checking.threshold_checker import (
- ThresholdChecker,
- )
-
- mock_model = Mock()
- mock_model.invoke.return_value.content = "1"
- checker = ThresholdChecker(mock_model)
-
- candidate = MockCandidate(name="Test")
- constraint = MockConstraint(value="constraint")
- evidence = [{"text": "text"}]
-
- score = checker._check_constraint_satisfaction(
- candidate, constraint, evidence
- )
-
- assert score == 1.0
-
- def test_clamps_score_to_max_1(self):
- """Clamps score to maximum 1.0."""
- from local_deep_research.advanced_search_system.constraint_checking.threshold_checker import (
- ThresholdChecker,
- )
-
- mock_model = Mock()
- mock_model.invoke.return_value.content = "Score: 1.5"
- checker = ThresholdChecker(mock_model)
-
- candidate = MockCandidate(name="Test")
- constraint = MockConstraint(value="constraint")
- evidence = [{"text": "text"}]
-
- score = checker._check_constraint_satisfaction(
- candidate, constraint, evidence
- )
-
- assert score == 1.0
-
- def test_negative_score_returns_default(self):
- """Negative scores in LLM response are not matched, returns default 0.5."""
- from local_deep_research.advanced_search_system.constraint_checking.threshold_checker import (
- ThresholdChecker,
- )
-
- mock_model = Mock()
- # Regex only matches positive numbers, so "-0.5" doesn't match
- mock_model.invoke.return_value.content = "Score: -0.5"
- checker = ThresholdChecker(mock_model)
-
- candidate = MockCandidate(name="Test")
- constraint = MockConstraint(value="constraint")
- evidence = [{"text": "text"}]
-
- score = checker._check_constraint_satisfaction(
- candidate, constraint, evidence
- )
-
- # Returns default 0.5 since regex doesn't match negative numbers
- assert score == 0.5
-
- def test_returns_default_on_parse_failure(self):
- """Returns 0.5 default when parsing fails."""
- from local_deep_research.advanced_search_system.constraint_checking.threshold_checker import (
- ThresholdChecker,
- )
-
- mock_model = Mock()
- mock_model.invoke.return_value.content = "no score here"
- checker = ThresholdChecker(mock_model)
-
- candidate = MockCandidate(name="Test")
- constraint = MockConstraint(value="constraint")
- evidence = [{"text": "text"}]
-
- score = checker._check_constraint_satisfaction(
- candidate, constraint, evidence
- )
-
- assert score == 0.5
-
- def test_returns_default_on_exception(self):
- """Returns 0.5 default on exception."""
- from local_deep_research.advanced_search_system.constraint_checking.threshold_checker import (
- ThresholdChecker,
- )
-
- mock_model = Mock()
- mock_model.invoke.side_effect = Exception("LLM error")
- checker = ThresholdChecker(mock_model)
-
- candidate = MockCandidate(name="Test")
- constraint = MockConstraint(value="constraint")
- evidence = [{"text": "text"}]
-
- score = checker._check_constraint_satisfaction(
- candidate, constraint, evidence
- )
-
- assert score == 0.5
-
- def test_combines_evidence_texts(self):
- """Combines multiple evidence texts in prompt."""
- from local_deep_research.advanced_search_system.constraint_checking.threshold_checker import (
- ThresholdChecker,
- )
-
- mock_model = Mock()
- mock_model.invoke.return_value.content = "0.9"
- checker = ThresholdChecker(mock_model)
-
- candidate = MockCandidate(name="Test")
- constraint = MockConstraint(value="constraint")
- evidence = [
- {"text": "Evidence 1"},
- {"text": "Evidence 2"},
- {"text": "Evidence 3"},
- ]
-
- checker._check_constraint_satisfaction(candidate, constraint, evidence)
-
- # Verify prompt contains evidence
- call_args = mock_model.invoke.call_args[0][0]
- assert "Evidence 1" in call_args
- assert "Evidence 2" in call_args
- assert "Evidence 3" in call_args
-
- def test_truncates_evidence_text(self):
- """Truncates long evidence texts."""
- from local_deep_research.advanced_search_system.constraint_checking.threshold_checker import (
- ThresholdChecker,
- )
-
- mock_model = Mock()
- mock_model.invoke.return_value.content = "0.7"
- checker = ThresholdChecker(mock_model)
-
- candidate = MockCandidate(name="Test")
- constraint = MockConstraint(value="constraint")
- evidence = [{"text": "A" * 500}] # Long text
-
- checker._check_constraint_satisfaction(candidate, constraint, evidence)
-
- call_args = mock_model.invoke.call_args[0][0]
- # Evidence should be truncated to 200 chars
- assert len(call_args) < 500 + 200 # Some buffer for prompt
-
-
-class TestShouldRejectCandidate:
- """Tests for should_reject_candidate method."""
-
- def test_rejects_when_no_evidence(self):
- """Rejects candidate when no evidence available."""
- from local_deep_research.advanced_search_system.constraint_checking.threshold_checker import (
- ThresholdChecker,
- )
-
- mock_model = Mock()
- checker = ThresholdChecker(mock_model)
-
- candidate = MockCandidate(name="Test")
- constraint = MockConstraint(value="constraint")
-
- should_reject, reason = checker.should_reject_candidate(
- candidate, constraint, []
- )
-
- assert should_reject is True
- assert "No evidence" in reason
-
- def test_rejects_when_score_below_threshold(self):
- """Rejects when satisfaction score below threshold."""
- from local_deep_research.advanced_search_system.constraint_checking.threshold_checker import (
- ThresholdChecker,
- )
-
- mock_model = Mock()
- mock_model.invoke.return_value.content = "0.3" # Below 0.7 default
- checker = ThresholdChecker(mock_model)
-
- candidate = MockCandidate(name="Test")
- constraint = MockConstraint(value="constraint")
- evidence = [{"text": "some evidence"}]
-
- should_reject, reason = checker.should_reject_candidate(
- candidate, constraint, evidence
- )
-
- assert should_reject is True
- assert "not satisfied" in reason
-
- def test_accepts_when_score_above_threshold(self):
- """Accepts when satisfaction score above threshold."""
- from local_deep_research.advanced_search_system.constraint_checking.threshold_checker import (
- ThresholdChecker,
- )
-
- mock_model = Mock()
- mock_model.invoke.return_value.content = "0.85"
- checker = ThresholdChecker(mock_model)
-
- candidate = MockCandidate(name="Test")
- constraint = MockConstraint(value="constraint")
- evidence = [{"text": "good evidence"}]
-
- should_reject, reason = checker.should_reject_candidate(
- candidate, constraint, evidence
- )
-
- assert should_reject is False
- assert reason == ""
-
- def test_uses_custom_threshold(self):
- """Uses custom satisfaction threshold."""
- from local_deep_research.advanced_search_system.constraint_checking.threshold_checker import (
- ThresholdChecker,
- )
-
- mock_model = Mock()
- mock_model.invoke.return_value.content = "0.5"
- checker = ThresholdChecker(mock_model, satisfaction_threshold=0.4)
-
- candidate = MockCandidate(name="Test")
- constraint = MockConstraint(value="constraint")
- evidence = [{"text": "evidence"}]
-
- should_reject, _ = checker.should_reject_candidate(
- candidate, constraint, evidence
- )
-
- assert should_reject is False # 0.5 >= 0.4
-
-
-class TestCheckCandidate:
- """Tests for check_candidate method."""
-
- def test_returns_constraint_check_result(self):
- """Returns ConstraintCheckResult with all fields."""
- from local_deep_research.advanced_search_system.constraint_checking.threshold_checker import (
- ThresholdChecker,
- )
-
- mock_model = Mock()
- mock_model.invoke.return_value.content = "0.9"
- mock_gatherer = Mock(return_value=[{"text": "evidence"}])
- checker = ThresholdChecker(mock_model, evidence_gatherer=mock_gatherer)
-
- candidate = MockCandidate(name="Test")
- constraints = [MockConstraint(value="c1")]
-
- result = checker.check_candidate(candidate, constraints)
-
- assert hasattr(result, "total_score")
- assert hasattr(result, "should_reject")
- assert hasattr(result, "constraint_scores")
- assert hasattr(result, "detailed_results")
-
- def test_checks_all_constraints(self):
- """Checks all provided constraints."""
- from local_deep_research.advanced_search_system.constraint_checking.threshold_checker import (
- ThresholdChecker,
- )
-
- mock_model = Mock()
- mock_model.invoke.return_value.content = "0.8"
- mock_gatherer = Mock(return_value=[{"text": "evidence"}])
- checker = ThresholdChecker(mock_model, evidence_gatherer=mock_gatherer)
-
- candidate = MockCandidate(name="Test")
- constraints = [
- MockConstraint(value="c1"),
- MockConstraint(value="c2"),
- MockConstraint(value="c3"),
- ]
-
- result = checker.check_candidate(candidate, constraints)
-
- assert len(result.detailed_results) == 3
- assert "c1" in result.constraint_scores
- assert "c2" in result.constraint_scores
- assert "c3" in result.constraint_scores
-
- def test_rejects_when_satisfaction_rate_too_low(self):
- """Rejects when satisfaction rate below threshold."""
- from local_deep_research.advanced_search_system.constraint_checking.threshold_checker import (
- ThresholdChecker,
- )
-
- mock_model = Mock()
- # First constraint passes (0.9), others fail (0.3)
- mock_model.invoke.return_value.content = "0.3"
- mock_gatherer = Mock(return_value=[{"text": "evidence"}])
- checker = ThresholdChecker(
- mock_model,
- evidence_gatherer=mock_gatherer,
- satisfaction_threshold=0.7,
- required_satisfaction_rate=0.8,
- )
-
- candidate = MockCandidate(name="Test")
- constraints = [
- MockConstraint(value="c1"),
- MockConstraint(value="c2"),
- MockConstraint(value="c3"),
- ]
-
- result = checker.check_candidate(candidate, constraints)
-
- # 0/3 constraints satisfied = 0% < 80%
- assert result.should_reject is True
- assert "0/3" in result.rejection_reason
-
- def test_accepts_when_satisfaction_rate_sufficient(self):
- """Accepts when satisfaction rate meets threshold."""
- from local_deep_research.advanced_search_system.constraint_checking.threshold_checker import (
- ThresholdChecker,
- )
-
- mock_model = Mock()
- mock_model.invoke.return_value.content = "0.85"
- mock_gatherer = Mock(return_value=[{"text": "evidence"}])
- checker = ThresholdChecker(mock_model, evidence_gatherer=mock_gatherer)
-
- candidate = MockCandidate(name="Test")
- constraints = [MockConstraint(value="c1")]
-
- result = checker.check_candidate(candidate, constraints)
-
- assert result.should_reject is False
- assert result.rejection_reason is None
-
- def test_handles_no_evidence_for_constraint(self):
- """Handles missing evidence for constraint."""
- from local_deep_research.advanced_search_system.constraint_checking.threshold_checker import (
- ThresholdChecker,
- )
-
- mock_model = Mock()
- mock_gatherer = Mock(return_value=[]) # No evidence
- checker = ThresholdChecker(mock_model, evidence_gatherer=mock_gatherer)
-
- candidate = MockCandidate(name="Test")
- constraints = [MockConstraint(value="c1")]
-
- result = checker.check_candidate(candidate, constraints)
-
- assert result.constraint_scores["c1"]["total"] == 0.0
- assert result.constraint_scores["c1"]["satisfied"] is False
-
- def test_calculates_total_score_as_satisfaction_rate(self):
- """Total score equals satisfaction rate when not rejected."""
- from local_deep_research.advanced_search_system.constraint_checking.threshold_checker import (
- ThresholdChecker,
- )
-
- mock_model = Mock()
- mock_model.invoke.return_value.content = "0.9"
- mock_gatherer = Mock(return_value=[{"text": "evidence"}])
- checker = ThresholdChecker(
- mock_model,
- evidence_gatherer=mock_gatherer,
- required_satisfaction_rate=0.5,
- )
-
- candidate = MockCandidate(name="Test")
- constraints = [
- MockConstraint(value="c1"),
- MockConstraint(value="c2"),
- ]
-
- result = checker.check_candidate(candidate, constraints)
-
- # Both satisfied, so 100% satisfaction rate
- assert result.total_score == 1.0
-
- def test_sets_total_score_zero_when_rejected(self):
- """Total score is zero when rejected."""
- from local_deep_research.advanced_search_system.constraint_checking.threshold_checker import (
- ThresholdChecker,
- )
-
- mock_model = Mock()
- mock_model.invoke.return_value.content = "0.3" # Below threshold
- mock_gatherer = Mock(return_value=[{"text": "evidence"}])
- checker = ThresholdChecker(mock_model, evidence_gatherer=mock_gatherer)
-
- candidate = MockCandidate(name="Test")
- constraints = [MockConstraint(value="c1")]
-
- result = checker.check_candidate(candidate, constraints)
-
- assert result.should_reject is True
- assert result.total_score == 0.0
-
- def test_stores_weight_in_constraint_scores(self):
- """Stores constraint weight in scores."""
- from local_deep_research.advanced_search_system.constraint_checking.threshold_checker import (
- ThresholdChecker,
- )
-
- mock_model = Mock()
- mock_model.invoke.return_value.content = "0.9"
- mock_gatherer = Mock(return_value=[{"text": "evidence"}])
- checker = ThresholdChecker(mock_model, evidence_gatherer=mock_gatherer)
-
- candidate = MockCandidate(name="Test")
- constraints = [MockConstraint(value="c1", weight=2.5)]
-
- result = checker.check_candidate(candidate, constraints)
-
- assert result.constraint_scores["c1"]["weight"] == 2.5
-
- def test_handles_empty_constraints_list(self):
- """Handles empty constraints list."""
- from local_deep_research.advanced_search_system.constraint_checking.threshold_checker import (
- ThresholdChecker,
- )
-
- mock_model = Mock()
- checker = ThresholdChecker(mock_model)
-
- candidate = MockCandidate(name="Test")
- constraints = []
-
- result = checker.check_candidate(candidate, constraints)
-
- assert result.total_score == 0 # 0/0 division handled
- assert result.should_reject is True # 0 < 0.8
-
-
-class TestDetailedResults:
- """Tests for detailed_results structure."""
-
- def test_detailed_results_contains_constraint_info(self):
- """Detailed results contain constraint information."""
- from local_deep_research.advanced_search_system.constraint_checking.threshold_checker import (
- ThresholdChecker,
- )
-
- mock_model = Mock()
- mock_model.invoke.return_value.content = "0.75"
- mock_gatherer = Mock(return_value=[{"text": "evidence"}])
- checker = ThresholdChecker(mock_model, evidence_gatherer=mock_gatherer)
-
- candidate = MockCandidate(name="Test")
- constraints = [MockConstraint(value="test constraint", weight=1.5)]
-
- result = checker.check_candidate(candidate, constraints)
-
- detail = result.detailed_results[0]
- assert detail["constraint"] == "test constraint"
- assert detail["weight"] == 1.5
- assert detail["type"] == "property"
- assert "score" in detail
- assert "satisfied" in detail
-
- def test_detailed_results_score_matches_satisfaction_check(self):
- """Score in detailed results matches satisfaction check."""
- from local_deep_research.advanced_search_system.constraint_checking.threshold_checker import (
- ThresholdChecker,
- )
-
- mock_model = Mock()
- mock_model.invoke.return_value.content = "0.82"
- mock_gatherer = Mock(return_value=[{"text": "evidence"}])
- checker = ThresholdChecker(mock_model, evidence_gatherer=mock_gatherer)
-
- candidate = MockCandidate(name="Test")
- constraints = [MockConstraint(value="c1")]
-
- result = checker.check_candidate(candidate, constraints)
-
- assert result.detailed_results[0]["score"] == 0.82
- assert result.detailed_results[0]["satisfied"] is True # 0.82 >= 0.7
diff --git a/tests/advanced_search_system/strategies/test_adaptive_decomp_pure_logic.py b/tests/advanced_search_system/strategies/test_adaptive_decomp_pure_logic.py
deleted file mode 100644
index 287afc160b..0000000000
--- a/tests/advanced_search_system/strategies/test_adaptive_decomp_pure_logic.py
+++ /dev/null
@@ -1,83 +0,0 @@
-"""
-Pure-logic tests for AdaptiveDecompositionStrategy._calculate_confidence.
-
-Tests the confidence ratio calculation with candidate boost and cap,
-requiring no LLM or search calls.
-"""
-
-from unittest.mock import Mock
-
-from local_deep_research.advanced_search_system.strategies.adaptive_decomposition_strategy import (
- AdaptiveDecompositionStrategy,
-)
-
-
-def _make_strategy(constraints=None, verified_facts=None, candidates=None):
- """Build a minimal Mock with the working_knowledge dict."""
- s = Mock(spec=[])
- s.working_knowledge = {
- "constraints": constraints or [],
- "verified_facts": verified_facts or [],
- "candidates": candidates or [],
- }
- return s
-
-
-class TestCalculateConfidence:
- """Verify confidence calculation: verified/total ratio + candidate boost, capped at 0.95."""
-
- def test_no_constraints(self):
- """No constraints -> 0.0."""
- s = _make_strategy(constraints=[], verified_facts=["a"])
- result = AdaptiveDecompositionStrategy._calculate_confidence(s)
- assert result == 0.0
-
- def test_half_verified(self):
- """2 verified out of 4 constraints -> 0.5."""
- s = _make_strategy(
- constraints=["c1", "c2", "c3", "c4"],
- verified_facts=["f1", "f2"],
- )
- result = AdaptiveDecompositionStrategy._calculate_confidence(s)
- assert result == 0.5
-
- def test_candidate_boost(self):
- """Having candidates adds 0.1 boost."""
- s = _make_strategy(
- constraints=["c1", "c2", "c3", "c4"],
- verified_facts=["f1", "f2"],
- candidates=["cand1"],
- )
- result = AdaptiveDecompositionStrategy._calculate_confidence(s)
- assert abs(result - 0.6) < 1e-9
-
- def test_cap_at_095(self):
- """Confidence should never exceed 0.95."""
- s = _make_strategy(
- constraints=["c1"],
- verified_facts=["f1"],
- candidates=["cand1"],
- )
- # 1/1 + 0.1 = 1.1, but capped at 0.95
- result = AdaptiveDecompositionStrategy._calculate_confidence(s)
- assert result == 0.95
-
- def test_all_verified_no_candidates(self):
- """All verified, no candidates -> base ratio (capped at 0.95)."""
- s = _make_strategy(
- constraints=["c1", "c2"],
- verified_facts=["f1", "f2"],
- )
- result = AdaptiveDecompositionStrategy._calculate_confidence(s)
- assert result == 0.95
-
- def test_none_verified(self):
- """No verified facts -> 0.0 (no candidate boost since 0+0.1 stays)."""
- s = _make_strategy(
- constraints=["c1", "c2"],
- verified_facts=[],
- candidates=["cand1"],
- )
- # 0/2 + 0.1 = 0.1
- result = AdaptiveDecompositionStrategy._calculate_confidence(s)
- assert abs(result - 0.1) < 1e-9
diff --git a/tests/advanced_search_system/strategies/test_adaptive_decomposition_high_value.py b/tests/advanced_search_system/strategies/test_adaptive_decomposition_high_value.py
deleted file mode 100644
index fec8080111..0000000000
--- a/tests/advanced_search_system/strategies/test_adaptive_decomposition_high_value.py
+++ /dev/null
@@ -1,284 +0,0 @@
-"""High-value pure logic tests for AdaptiveDecompositionStrategy.
-
-Tests cover:
-- StepType enum values
-- StepResult dataclass fields and defaults
-- _calculate_confidence() pure math logic
-- _execute_step() routing logic
-"""
-
-from unittest.mock import MagicMock, patch
-
-import pytest
-
-from local_deep_research.advanced_search_system.strategies.adaptive_decomposition_strategy import (
- AdaptiveDecompositionStrategy,
- StepResult,
- StepType,
-)
-
-
-# ---------------------------------------------------------------------------
-# StepType enum
-# ---------------------------------------------------------------------------
-class TestStepTypeEnum:
- """Tests for the StepType enum values."""
-
- def test_constraint_extraction_value(self):
- assert StepType.CONSTRAINT_EXTRACTION.value == "constraint_extraction"
-
- def test_initial_search_value(self):
- assert StepType.INITIAL_SEARCH.value == "initial_search"
-
- def test_verification_value(self):
- assert StepType.VERIFICATION.value == "verification"
-
- def test_refinement_value(self):
- assert StepType.REFINEMENT.value == "refinement"
-
- def test_synthesis_value(self):
- assert StepType.SYNTHESIS.value == "synthesis"
-
- def test_enum_has_exactly_five_members(self):
- assert len(StepType) == 5
-
-
-# ---------------------------------------------------------------------------
-# StepResult dataclass
-# ---------------------------------------------------------------------------
-class TestStepResultDataclass:
- """Tests for the StepResult dataclass fields and defaults."""
-
- def test_required_fields(self):
- result = StepResult(
- step_type=StepType.SYNTHESIS,
- description="test desc",
- findings={"key": "val"},
- )
- assert result.step_type == StepType.SYNTHESIS
- assert result.description == "test desc"
- assert result.findings == {"key": "val"}
-
- def test_default_next_action_is_none(self):
- result = StepResult(
- step_type=StepType.VERIFICATION,
- description="",
- findings={},
- )
- assert result.next_action is None
-
- def test_default_confidence_is_zero(self):
- result = StepResult(
- step_type=StepType.REFINEMENT,
- description="",
- findings={},
- )
- assert result.confidence == 0.0
-
- def test_custom_next_action(self):
- result = StepResult(
- step_type=StepType.INITIAL_SEARCH,
- description="d",
- findings={},
- next_action="refine",
- )
- assert result.next_action == "refine"
-
- def test_custom_confidence(self):
- result = StepResult(
- step_type=StepType.INITIAL_SEARCH,
- description="d",
- findings={},
- confidence=0.75,
- )
- assert result.confidence == 0.75
-
-
-# ---------------------------------------------------------------------------
-# Helpers for strategy tests
-# ---------------------------------------------------------------------------
-def _make_strategy() -> AdaptiveDecompositionStrategy:
- """Create a strategy instance with __init__ bypassed."""
- with patch.object(
- AdaptiveDecompositionStrategy, "__init__", lambda self, *a, **kw: None
- ):
- strategy = AdaptiveDecompositionStrategy()
- # Provide the minimal state that _calculate_confidence needs
- strategy.working_knowledge = {
- "constraints": [],
- "candidates": [],
- "verified_facts": [],
- "uncertainties": [],
- }
- return strategy
-
-
-# ---------------------------------------------------------------------------
-# _calculate_confidence
-# ---------------------------------------------------------------------------
-class TestCalculateConfidence:
- """Tests for the _calculate_confidence pure math method."""
-
- def test_empty_constraints_returns_zero(self):
- strategy = _make_strategy()
- strategy.working_knowledge["constraints"] = []
- assert strategy._calculate_confidence() == 0.0
-
- def test_no_verified_facts_returns_zero(self):
- strategy = _make_strategy()
- strategy.working_knowledge["constraints"] = ["c1", "c2"]
- strategy.working_knowledge["verified_facts"] = []
- strategy.working_knowledge["candidates"] = []
- assert strategy._calculate_confidence() == 0.0
-
- def test_ratio_half(self):
- strategy = _make_strategy()
- strategy.working_knowledge["constraints"] = ["c1", "c2"]
- strategy.working_knowledge["verified_facts"] = ["f1"]
- strategy.working_knowledge["candidates"] = []
- assert strategy._calculate_confidence() == pytest.approx(0.5)
-
- def test_ratio_full_no_candidates(self):
- strategy = _make_strategy()
- strategy.working_knowledge["constraints"] = ["c1"]
- strategy.working_knowledge["verified_facts"] = ["f1"]
- strategy.working_knowledge["candidates"] = []
- # 1/1 = 1.0, no boost, capped at 0.95
- assert strategy._calculate_confidence() == pytest.approx(0.95)
-
- def test_candidate_boost_adds_point_one(self):
- strategy = _make_strategy()
- strategy.working_knowledge["constraints"] = ["c1", "c2"]
- strategy.working_knowledge["verified_facts"] = ["f1"]
- strategy.working_knowledge["candidates"] = ["loc1"]
- # 1/2 + 0.1 = 0.6
- assert strategy._calculate_confidence() == pytest.approx(0.6)
-
- def test_candidate_boost_with_full_ratio_caps_at_095(self):
- strategy = _make_strategy()
- strategy.working_knowledge["constraints"] = ["c1"]
- strategy.working_knowledge["verified_facts"] = ["f1"]
- strategy.working_knowledge["candidates"] = ["loc1"]
- # 1/1 + 0.1 = 1.1, capped at 0.95
- assert strategy._calculate_confidence() == pytest.approx(0.95)
-
- def test_verified_exceeds_constraints_caps_at_095(self):
- strategy = _make_strategy()
- strategy.working_knowledge["constraints"] = ["c1"]
- strategy.working_knowledge["verified_facts"] = ["f1", "f2", "f3"]
- strategy.working_knowledge["candidates"] = []
- # 3/1 = 3.0, capped at 0.95
- assert strategy._calculate_confidence() == pytest.approx(0.95)
-
- def test_many_constraints_low_verified(self):
- strategy = _make_strategy()
- strategy.working_knowledge["constraints"] = [
- "c1",
- "c2",
- "c3",
- "c4",
- "c5",
- ]
- strategy.working_knowledge["verified_facts"] = ["f1"]
- strategy.working_knowledge["candidates"] = []
- # 1/5 = 0.2
- assert strategy._calculate_confidence() == pytest.approx(0.2)
-
- def test_many_constraints_low_verified_with_candidates(self):
- strategy = _make_strategy()
- strategy.working_knowledge["constraints"] = [
- "c1",
- "c2",
- "c3",
- "c4",
- "c5",
- ]
- strategy.working_knowledge["verified_facts"] = ["f1"]
- strategy.working_knowledge["candidates"] = ["loc1"]
- # 1/5 + 0.1 = 0.3
- assert strategy._calculate_confidence() == pytest.approx(0.3)
-
- def test_empty_candidates_list_no_boost(self):
- """An empty list is falsy, so no +0.1 boost."""
- strategy = _make_strategy()
- strategy.working_knowledge["constraints"] = ["c1", "c2"]
- strategy.working_knowledge["verified_facts"] = ["f1"]
- strategy.working_knowledge["candidates"] = []
- assert strategy._calculate_confidence() == pytest.approx(0.5)
-
-
-# ---------------------------------------------------------------------------
-# _execute_step routing
-# ---------------------------------------------------------------------------
-class TestExecuteStepRouting:
- """Tests that _execute_step dispatches to the correct method."""
-
- def _strategy_with_mocks(self):
- strategy = _make_strategy()
- strategy._extract_constraints = MagicMock(
- return_value="constraints_result"
- )
- strategy._perform_initial_search = MagicMock(
- return_value="search_result"
- )
- strategy._verify_candidates = MagicMock(return_value="verify_result")
- strategy._refine_search = MagicMock(return_value="refine_result")
- strategy._synthesize_current_knowledge = MagicMock(
- return_value="synthesis_result"
- )
- return strategy
-
- def test_routes_constraint_extraction(self):
- strategy = self._strategy_with_mocks()
- step = StepResult(
- step_type=StepType.CONSTRAINT_EXTRACTION,
- description="desc",
- findings={},
- )
- result = strategy._execute_step(step, "query")
- assert result == "constraints_result"
- strategy._extract_constraints.assert_called_once_with("query")
-
- def test_routes_initial_search(self):
- strategy = self._strategy_with_mocks()
- step = StepResult(
- step_type=StepType.INITIAL_SEARCH,
- description="search desc",
- findings={},
- )
- result = strategy._execute_step(step, "query")
- assert result == "search_result"
- strategy._perform_initial_search.assert_called_once_with("search desc")
-
- def test_routes_verification(self):
- strategy = self._strategy_with_mocks()
- step = StepResult(
- step_type=StepType.VERIFICATION,
- description="verify desc",
- findings={},
- )
- result = strategy._execute_step(step, "query")
- assert result == "verify_result"
- strategy._verify_candidates.assert_called_once_with("verify desc")
-
- def test_routes_refinement(self):
- strategy = self._strategy_with_mocks()
- step = StepResult(
- step_type=StepType.REFINEMENT,
- description="refine desc",
- findings={},
- )
- result = strategy._execute_step(step, "query")
- assert result == "refine_result"
- strategy._refine_search.assert_called_once_with("refine desc")
-
- def test_routes_synthesis(self):
- strategy = self._strategy_with_mocks()
- step = StepResult(
- step_type=StepType.SYNTHESIS,
- description="synth desc",
- findings={},
- )
- result = strategy._execute_step(step, "query")
- assert result == "synthesis_result"
- strategy._synthesize_current_knowledge.assert_called_once_with("query")
diff --git a/tests/advanced_search_system/strategies/test_browsecomp_entity_high_value.py b/tests/advanced_search_system/strategies/test_browsecomp_entity_high_value.py
deleted file mode 100644
index 3cab7669d6..0000000000
--- a/tests/advanced_search_system/strategies/test_browsecomp_entity_high_value.py
+++ /dev/null
@@ -1,297 +0,0 @@
-"""High-value pure logic tests for EntityCandidate and EntityKnowledgeGraph."""
-
-from local_deep_research.advanced_search_system.strategies.browsecomp_entity_strategy import (
- EntityCandidate,
- EntityKnowledgeGraph,
-)
-
-
-class TestEntityCandidateDefaults:
- """Test EntityCandidate dataclass field defaults and __post_init__."""
-
- def test_none_aliases_initialized_to_empty_list(self):
- entity = EntityCandidate(name="Acme", entity_type="company")
- assert entity.aliases == []
-
- def test_none_properties_initialized_to_empty_dict(self):
- entity = EntityCandidate(name="Acme", entity_type="company")
- assert entity.properties == {}
-
- def test_none_sources_initialized_to_empty_list(self):
- entity = EntityCandidate(name="Acme", entity_type="company")
- assert entity.sources == []
-
- def test_none_constraint_matches_initialized_to_empty_dict(self):
- entity = EntityCandidate(name="Acme", entity_type="company")
- assert entity.constraint_matches == {}
-
- def test_default_confidence_is_zero(self):
- entity = EntityCandidate(name="Acme", entity_type="company")
- assert entity.confidence == 0.0
-
- def test_explicit_values_preserved(self):
- entity = EntityCandidate(
- name="TestCorp",
- entity_type="company",
- aliases=["TC"],
- properties={"founded": "2000"},
- sources=["http://example.com"],
- confidence=0.9,
- constraint_matches={"size": 0.8},
- )
- assert entity.aliases == ["TC"]
- assert entity.properties == {"founded": "2000"}
- assert entity.sources == ["http://example.com"]
- assert entity.confidence == 0.9
- assert entity.constraint_matches == {"size": 0.8}
-
- def test_required_fields_stored(self):
- entity = EntityCandidate(name="Alice", entity_type="person")
- assert entity.name == "Alice"
- assert entity.entity_type == "person"
-
-
-class TestEntityKnowledgeGraphAddEntity:
- """Test EntityKnowledgeGraph.add_entity() for new and merged entities."""
-
- def test_add_new_entity(self):
- graph = EntityKnowledgeGraph()
- entity = EntityCandidate(name="Acme", entity_type="company")
- graph.add_entity(entity)
- assert "Acme" in graph.entities
- assert graph.entities["Acme"] is entity
-
- def test_add_multiple_distinct_entities(self):
- graph = EntityKnowledgeGraph()
- graph.add_entity(EntityCandidate(name="A", entity_type="company"))
- graph.add_entity(EntityCandidate(name="B", entity_type="person"))
- assert len(graph.entities) == 2
-
- def test_merge_aliases_deduplicates(self):
- graph = EntityKnowledgeGraph()
- graph.add_entity(
- EntityCandidate(
- name="Acme", entity_type="company", aliases=["AC", "AcmeCo"]
- )
- )
- graph.add_entity(
- EntityCandidate(
- name="Acme", entity_type="company", aliases=["AC", "AcmeInc"]
- )
- )
- aliases = graph.entities["Acme"].aliases
- assert sorted(aliases) == sorted(["AC", "AcmeCo", "AcmeInc"])
-
- def test_merge_properties_updates(self):
- graph = EntityKnowledgeGraph()
- graph.add_entity(
- EntityCandidate(
- name="Acme",
- entity_type="company",
- properties={"founded": "2000"},
- )
- )
- graph.add_entity(
- EntityCandidate(
- name="Acme",
- entity_type="company",
- properties={"founded": "2001", "hq": "NYC"},
- )
- )
- props = graph.entities["Acme"].properties
- assert props["founded"] == "2001" # overwritten by second add
- assert props["hq"] == "NYC"
-
- def test_merge_sources_deduplicates(self):
- graph = EntityKnowledgeGraph()
- graph.add_entity(
- EntityCandidate(
- name="Acme",
- entity_type="company",
- sources=["http://a.com", "http://b.com"],
- )
- )
- graph.add_entity(
- EntityCandidate(
- name="Acme",
- entity_type="company",
- sources=["http://b.com", "http://c.com"],
- )
- )
- sources = graph.entities["Acme"].sources
- assert len(sources) == 3
- assert set(sources) == {"http://a.com", "http://b.com", "http://c.com"}
-
- def test_merge_constraint_matches_updates(self):
- graph = EntityKnowledgeGraph()
- graph.add_entity(
- EntityCandidate(
- name="Acme",
- entity_type="company",
- constraint_matches={"size": 0.5},
- )
- )
- graph.add_entity(
- EntityCandidate(
- name="Acme",
- entity_type="company",
- constraint_matches={"size": 0.9, "age": 0.7},
- )
- )
- matches = graph.entities["Acme"].constraint_matches
- assert matches["size"] == 0.9
- assert matches["age"] == 0.7
-
- def test_merge_does_not_replace_entity_object(self):
- graph = EntityKnowledgeGraph()
- first = EntityCandidate(name="Acme", entity_type="company")
- graph.add_entity(first)
- graph.add_entity(EntityCandidate(name="Acme", entity_type="company"))
- assert graph.entities["Acme"] is first
-
- def test_merge_with_empty_new_entity(self):
- graph = EntityKnowledgeGraph()
- graph.add_entity(
- EntityCandidate(
- name="Acme",
- entity_type="company",
- aliases=["AC"],
- properties={"k": "v"},
- sources=["http://x.com"],
- )
- )
- # Merge entity with all defaults (empty lists/dicts)
- graph.add_entity(EntityCandidate(name="Acme", entity_type="company"))
- assert graph.entities["Acme"].aliases == ["AC"]
- assert graph.entities["Acme"].properties == {"k": "v"}
- assert graph.entities["Acme"].sources == ["http://x.com"]
-
-
-class TestEntityKnowledgeGraphConstraintEvidence:
- """Test add_constraint_evidence() and evidence storage."""
-
- def test_add_single_evidence(self):
- graph = EntityKnowledgeGraph()
- graph.add_constraint_evidence(
- "large_size", "Acme", {"score": 0.8, "text": "big"}
- )
- assert graph.constraint_evidence["large_size"]["Acme"]["score"] == 0.8
-
- def test_add_evidence_multiple_entities_same_constraint(self):
- graph = EntityKnowledgeGraph()
- graph.add_constraint_evidence("large_size", "Acme", {"score": 0.8})
- graph.add_constraint_evidence("large_size", "Beta", {"score": 0.6})
- assert len(graph.constraint_evidence["large_size"]) == 2
-
- def test_add_evidence_multiple_constraints_same_entity(self):
- graph = EntityKnowledgeGraph()
- graph.add_constraint_evidence("size", "Acme", {"score": 0.8})
- graph.add_constraint_evidence("age", "Acme", {"score": 0.5})
- assert graph.constraint_evidence["size"]["Acme"]["score"] == 0.8
- assert graph.constraint_evidence["age"]["Acme"]["score"] == 0.5
-
- def test_overwrite_evidence_for_same_pair(self):
- graph = EntityKnowledgeGraph()
- graph.add_constraint_evidence("size", "Acme", {"score": 0.3})
- graph.add_constraint_evidence("size", "Acme", {"score": 0.9})
- assert graph.constraint_evidence["size"]["Acme"]["score"] == 0.9
-
-
-class TestEntityKnowledgeGraphGetEntitiesByConstraint:
- """Test get_entities_by_constraint() filtering and sorting."""
-
- def _make_graph_with_entities(self, entity_specs):
- """Helper: create a graph populated with entities.
-
- entity_specs is a list of (name, constraint_matches_dict) tuples.
- """
- graph = EntityKnowledgeGraph()
- for name, matches in entity_specs:
- graph.add_entity(
- EntityCandidate(
- name=name,
- entity_type="company",
- constraint_matches=matches,
- )
- )
- return graph
-
- def test_returns_matching_entities_above_threshold(self):
- graph = self._make_graph_with_entities(
- [
- ("A", {"size": 0.8}),
- ("B", {"size": 0.3}),
- ("C", {"size": 0.6}),
- ]
- )
- result = graph.get_entities_by_constraint("size", min_confidence=0.5)
- names = [ent.name for ent in result]
- assert "A" in names
- assert "C" in names
- assert "B" not in names
-
- def test_sorted_descending_by_constraint_score(self):
- graph = self._make_graph_with_entities(
- [
- ("A", {"size": 0.6}),
- ("B", {"size": 0.9}),
- ("C", {"size": 0.7}),
- ]
- )
- result = graph.get_entities_by_constraint("size", min_confidence=0.5)
- names = [ent.name for ent in result]
- assert names == ["B", "C", "A"]
-
- def test_no_matches_returns_empty(self):
- graph = self._make_graph_with_entities(
- [
- ("A", {"size": 0.2}),
- ("B", {"size": 0.1}),
- ]
- )
- result = graph.get_entities_by_constraint("size", min_confidence=0.5)
- assert result == []
-
- def test_constraint_not_present_returns_empty(self):
- graph = self._make_graph_with_entities(
- [
- ("A", {"age": 0.9}),
- ]
- )
- result = graph.get_entities_by_constraint("size", min_confidence=0.5)
- assert result == []
-
- def test_empty_graph_returns_empty(self):
- graph = EntityKnowledgeGraph()
- result = graph.get_entities_by_constraint("size", min_confidence=0.5)
- assert result == []
-
- def test_boundary_confidence_equal_to_threshold_included(self):
- graph = self._make_graph_with_entities(
- [
- ("A", {"size": 0.5}),
- ]
- )
- result = graph.get_entities_by_constraint("size", min_confidence=0.5)
- assert len(result) == 1
- assert result[0].name == "A"
-
- def test_boundary_confidence_just_below_threshold_excluded(self):
- graph = self._make_graph_with_entities(
- [
- ("A", {"size": 0.4999}),
- ]
- )
- result = graph.get_entities_by_constraint("size", min_confidence=0.5)
- assert result == []
-
- def test_default_min_confidence_is_half(self):
- graph = self._make_graph_with_entities(
- [
- ("A", {"size": 0.5}),
- ("B", {"size": 0.49}),
- ]
- )
- result = graph.get_entities_by_constraint("size")
- assert len(result) == 1
- assert result[0].name == "A"
diff --git a/tests/advanced_search_system/strategies/test_browsecomp_entity_methods_high_value.py b/tests/advanced_search_system/strategies/test_browsecomp_entity_methods_high_value.py
deleted file mode 100644
index bfe3e9f9cf..0000000000
--- a/tests/advanced_search_system/strategies/test_browsecomp_entity_methods_high_value.py
+++ /dev/null
@@ -1,408 +0,0 @@
-"""High-value pure logic tests for BrowseCompEntityStrategy methods.
-
-Covers:
-- entity_patterns dict completeness
-- _identify_entity_type() keyword matching and fallback logic
-- _generate_entity_searches() type-specific and constraint-based queries
-"""
-
-from unittest.mock import patch
-
-
-from local_deep_research.advanced_search_system.constraints.base_constraint import (
- Constraint,
- ConstraintType,
-)
-from local_deep_research.advanced_search_system.strategies.browsecomp_entity_strategy import (
- BrowseCompEntityStrategy,
-)
-
-# ---------------------------------------------------------------------------
-# Helpers
-# ---------------------------------------------------------------------------
-
-ENTITY_PATTERNS = {
- "company": [
- "company",
- "corporation",
- "group",
- "firm",
- "business",
- "conglomerate",
- ],
- "person": ["person", "individual", "character", "figure", "people"],
- "event": [
- "event",
- "incident",
- "occurrence",
- "game",
- "match",
- "competition",
- ],
- "location": [
- "place",
- "location",
- "city",
- "country",
- "region",
- "area",
- ],
- "product": ["product", "item", "device", "software", "app", "tool"],
-}
-
-
-def _make_strategy():
- """Create a BrowseCompEntityStrategy with __init__ bypassed."""
- with patch.object(
- BrowseCompEntityStrategy, "__init__", lambda self, *a, **kw: None
- ):
- strategy = BrowseCompEntityStrategy()
- strategy.entity_patterns = {k: list(v) for k, v in ENTITY_PATTERNS.items()}
- return strategy
-
-
-def _make_constraint(
- constraint_type, value, cid="c1", description="test", weight=1.0
-):
- """Create a Constraint with minimal boilerplate."""
- return Constraint(
- id=cid,
- type=constraint_type,
- description=description,
- value=value,
- weight=weight,
- )
-
-
-# ---------------------------------------------------------------------------
-# entity_patterns dict
-# ---------------------------------------------------------------------------
-
-
-class TestEntityPatternsDict:
- """Verify entity_patterns contains all 5 entity types with correct keywords."""
-
- def test_has_all_five_entity_types(self):
- strategy = _make_strategy()
- assert set(strategy.entity_patterns.keys()) == {
- "company",
- "person",
- "event",
- "location",
- "product",
- }
-
- def test_company_keywords(self):
- strategy = _make_strategy()
- expected = {
- "company",
- "corporation",
- "group",
- "firm",
- "business",
- "conglomerate",
- }
- assert set(strategy.entity_patterns["company"]) == expected
-
- def test_person_keywords(self):
- strategy = _make_strategy()
- expected = {"person", "individual", "character", "figure", "people"}
- assert set(strategy.entity_patterns["person"]) == expected
-
- def test_event_keywords(self):
- strategy = _make_strategy()
- expected = {
- "event",
- "incident",
- "occurrence",
- "game",
- "match",
- "competition",
- }
- assert set(strategy.entity_patterns["event"]) == expected
-
- def test_location_keywords(self):
- strategy = _make_strategy()
- expected = {"place", "location", "city", "country", "region", "area"}
- assert set(strategy.entity_patterns["location"]) == expected
-
- def test_product_keywords(self):
- strategy = _make_strategy()
- expected = {"product", "item", "device", "software", "app", "tool"}
- assert set(strategy.entity_patterns["product"]) == expected
-
-
-# ---------------------------------------------------------------------------
-# _identify_entity_type
-# ---------------------------------------------------------------------------
-
-
-class TestIdentifyEntityType:
- """Test _identify_entity_type() keyword matching and fallback branches."""
-
- # -- Direct keyword matches --
-
- def test_company_keyword_corporation(self):
- strategy = _make_strategy()
- assert (
- strategy._identify_entity_type("Which corporation merged?")
- == "company"
- )
-
- def test_company_keyword_business(self):
- strategy = _make_strategy()
- assert (
- strategy._identify_entity_type("What business failed?") == "company"
- )
-
- def test_company_keyword_conglomerate(self):
- strategy = _make_strategy()
- assert (
- strategy._identify_entity_type("Name the conglomerate") == "company"
- )
-
- def test_person_keyword_individual(self):
- strategy = _make_strategy()
- assert (
- strategy._identify_entity_type("Which individual won?") == "person"
- )
-
- def test_person_keyword_character(self):
- strategy = _make_strategy()
- assert strategy._identify_entity_type("Name the character") == "person"
-
- def test_event_keyword_competition(self):
- strategy = _make_strategy()
- assert (
- strategy._identify_entity_type("Which competition was held?")
- == "event"
- )
-
- def test_event_keyword_game(self):
- strategy = _make_strategy()
- assert (
- strategy._identify_entity_type("What game was played?") == "event"
- )
-
- def test_location_keyword_city(self):
- strategy = _make_strategy()
- assert (
- strategy._identify_entity_type("Which city hosted it?")
- == "location"
- )
-
- def test_product_keyword_software(self):
- strategy = _make_strategy()
- assert (
- strategy._identify_entity_type("Which software was released?")
- == "product"
- )
-
- def test_case_insensitive_matching(self):
- strategy = _make_strategy()
- assert (
- strategy._identify_entity_type("THE CORPORATION announced")
- == "company"
- )
-
- # -- Fallback branches (no keyword match) --
-
- def test_fallback_who_returns_person(self):
- strategy = _make_strategy()
- assert (
- strategy._identify_entity_type("Who discovered penicillin?")
- == "person"
- )
-
- def test_fallback_which_returns_product(self):
- strategy = _make_strategy()
- assert (
- strategy._identify_entity_type("Which one was recalled?")
- == "product"
- )
-
- def test_fallback_what_plus_company_returns_company(self):
- strategy = _make_strategy()
- assert (
- strategy._identify_entity_type("What company went bankrupt?")
- == "company"
- )
-
- def test_fallback_else_returns_entity(self):
- strategy = _make_strategy()
- assert (
- strategy._identify_entity_type("Identify the unknown xyz")
- == "entity"
- )
-
- def test_empty_query_returns_entity(self):
- strategy = _make_strategy()
- assert strategy._identify_entity_type("") == "entity"
-
- # -- First-match priority --
-
- def test_first_type_wins_when_multiple_keywords_present(self):
- """entity_patterns is iterated in dict insertion order; company comes first."""
- strategy = _make_strategy()
- # Contains both "company" (company) and "person" (person)
- result = strategy._identify_entity_type("company person")
- assert result == "company"
-
-
-# ---------------------------------------------------------------------------
-# _generate_entity_searches
-# ---------------------------------------------------------------------------
-
-
-class TestGenerateEntitySearches:
- """Test _generate_entity_searches() base queries and constraint expansion."""
-
- # -- Base queries by entity type --
-
- def test_company_base_queries(self):
- strategy = _make_strategy()
- searches = strategy._generate_entity_searches("company", [])
- assert len(searches) == 3
- assert any("companies" in s for s in searches)
- assert any("corporation" in s for s in searches)
-
- def test_person_base_queries(self):
- strategy = _make_strategy()
- searches = strategy._generate_entity_searches("person", [])
- assert len(searches) == 3
- assert any("people" in s for s in searches)
-
- def test_event_base_queries(self):
- strategy = _make_strategy()
- searches = strategy._generate_entity_searches("event", [])
- assert len(searches) == 3
- assert any("events" in s for s in searches)
-
- def test_unknown_type_returns_empty_base(self):
- strategy = _make_strategy()
- searches = strategy._generate_entity_searches("entity", [])
- assert searches == []
-
- # -- Constraint type matching uses constraint.type.value (e.g. "temporal")
- # compared against uppercase strings ("TEMPORAL") in the source code,
- # so the branches currently never fire. We test both the actual behavior
- # and document what *would* happen with a case-matched custom constraint.
-
- # -- TEMPORAL constraints (actual enum value is lowercase "temporal") --
-
- def test_temporal_constraint_enum_value_is_lowercase(self):
- """ConstraintType.TEMPORAL.value is 'temporal', not 'TEMPORAL'."""
- assert ConstraintType.TEMPORAL.value == "temporal"
-
- def test_temporal_constraint_no_match_due_to_case(self):
- """Source compares .value == 'TEMPORAL' but enum value is 'temporal',
- so TEMPORAL constraints do NOT add year searches with the standard enum."""
- strategy = _make_strategy()
- constraint = _make_constraint(
- ConstraintType.TEMPORAL, "Founded in 1995"
- )
- searches = strategy._generate_entity_searches("company", [constraint])
- # Only the 3 base queries -- the TEMPORAL branch is dead code
- assert len(searches) == 3
-
- def test_temporal_constraint_no_year_adds_nothing(self):
- strategy = _make_strategy()
- constraint = _make_constraint(ConstraintType.TEMPORAL, "recently")
- searches = strategy._generate_entity_searches("event", [constraint])
- # Only 3 base queries
- assert len(searches) == 3
-
- # -- LOCATION constraints (actual enum value is lowercase "location") --
-
- def test_location_constraint_no_match_due_to_case(self):
- """Source compares .value == 'LOCATION' but enum value is 'location',
- so LOCATION constraints do NOT add place searches with the standard enum."""
- strategy = _make_strategy()
- constraint = _make_constraint(ConstraintType.LOCATION, "in New York")
- searches = strategy._generate_entity_searches("company", [constraint])
- assert len(searches) == 3
-
- def test_location_constraint_no_proper_noun_adds_nothing(self):
- strategy = _make_strategy()
- constraint = _make_constraint(ConstraintType.LOCATION, "in the north")
- searches = strategy._generate_entity_searches("company", [constraint])
- assert len(searches) == 3
-
- # -- STATISTIC constraints (actual enum value is lowercase "statistic") --
-
- def test_statistic_constraint_no_match_due_to_case(self):
- """Source compares .value == 'STATISTIC' but enum value is 'statistic',
- so STATISTIC constraints do NOT add number searches with the standard enum."""
- strategy = _make_strategy()
- constraint = _make_constraint(
- ConstraintType.STATISTIC, "revenue of 500 million"
- )
- searches = strategy._generate_entity_searches("company", [constraint])
- assert len(searches) == 3
-
- # -- Constraint matching with a mock type whose .value IS uppercase --
- # This verifies the branch logic *would* work if the case matched.
-
- def test_temporal_branch_fires_with_uppercase_value(self):
- """When constraint.type.value literally equals 'TEMPORAL', years are extracted."""
- strategy = _make_strategy()
- mock_type = type("MockType", (), {"value": "TEMPORAL"})()
- constraint = _make_constraint(
- ConstraintType.TEMPORAL, "Founded in 1995"
- )
- constraint.type = mock_type
- searches = strategy._generate_entity_searches("company", [constraint])
- assert "company 1995" in searches
-
- def test_location_branch_fires_with_uppercase_value(self):
- """When constraint.type.value literally equals 'LOCATION', locations are extracted."""
- strategy = _make_strategy()
- mock_type = type("MockType", (), {"value": "LOCATION"})()
- constraint = _make_constraint(ConstraintType.LOCATION, "in New York")
- constraint.type = mock_type
- searches = strategy._generate_entity_searches("company", [constraint])
- assert any("New York" in s for s in searches)
-
- def test_statistic_branch_fires_with_uppercase_value(self):
- """When constraint.type.value literally equals 'STATISTIC', numbers are extracted."""
- strategy = _make_strategy()
- mock_type = type("MockType", (), {"value": "STATISTIC"})()
- constraint = _make_constraint(
- ConstraintType.STATISTIC, "revenue of 500 million"
- )
- constraint.type = mock_type
- searches = strategy._generate_entity_searches("company", [constraint])
- assert "company 500" in searches
-
- def test_multiple_uppercase_constraints_accumulate(self):
- """Multiple constraint branches fire when type.value is uppercase."""
- strategy = _make_strategy()
- temporal = _make_constraint(
- ConstraintType.TEMPORAL, "in 2020", cid="c1"
- )
- temporal.type = type("MockType", (), {"value": "TEMPORAL"})()
- location = _make_constraint(
- ConstraintType.LOCATION, "in Paris", cid="c2"
- )
- location.type = type("MockType", (), {"value": "LOCATION"})()
- searches = strategy._generate_entity_searches(
- "company", [temporal, location]
- )
- assert "company 2020" in searches
- assert any("Paris" in s for s in searches)
-
- # -- Empty constraints --
-
- def test_empty_constraints_returns_only_base(self):
- strategy = _make_strategy()
- searches = strategy._generate_entity_searches("person", [])
- assert len(searches) == 3
-
- # -- Non-matching constraint type passes through silently --
-
- def test_property_constraint_adds_nothing(self):
- """PROPERTY type does not match any branch, so no extra searches."""
- strategy = _make_strategy()
- constraint = _make_constraint(ConstraintType.PROPERTY, "is very large")
- searches = strategy._generate_entity_searches("company", [constraint])
- assert len(searches) == 3
diff --git a/tests/advanced_search_system/strategies/test_browsecomp_entity_pure_logic.py b/tests/advanced_search_system/strategies/test_browsecomp_entity_pure_logic.py
deleted file mode 100644
index 751f08f369..0000000000
--- a/tests/advanced_search_system/strategies/test_browsecomp_entity_pure_logic.py
+++ /dev/null
@@ -1,453 +0,0 @@
-"""
-Pure-logic tests for BrowseCompEntityStrategy and EntityKnowledgeGraph.
-
-Tests entity graph operations, entity type identification, specificity
-scoring, constraint term extraction, entity candidate extraction, entity
-search generation, and knowledge summarization — no LLM or search calls.
-"""
-
-from unittest.mock import Mock
-
-from local_deep_research.advanced_search_system.constraints.base_constraint import (
- Constraint,
- ConstraintType,
-)
-from local_deep_research.advanced_search_system.strategies.browsecomp_entity_strategy import (
- BrowseCompEntityStrategy,
- EntityCandidate,
- EntityKnowledgeGraph,
-)
-
-
-def _entity(name, entity_type="company", **kwargs):
- """Build an EntityCandidate with sensible defaults."""
- return EntityCandidate(
- name=name,
- entity_type=entity_type,
- aliases=kwargs.get("aliases", []),
- properties=kwargs.get("properties", {}),
- sources=kwargs.get("sources", []),
- confidence=kwargs.get("confidence", 0.0),
- constraint_matches=kwargs.get("constraint_matches", {}),
- )
-
-
-def _constraint(id, ctype=ConstraintType.PROPERTY, value="v"):
- return Constraint(id=id, type=ctype, description="", value=value)
-
-
-def _make_strategy():
- """Build a minimal Mock with entity_patterns matching the real init."""
- s = Mock(spec=[])
- s.entity_patterns = {
- "company": [
- "company",
- "corporation",
- "group",
- "firm",
- "business",
- "conglomerate",
- ],
- "person": ["person", "individual", "character", "figure", "people"],
- "event": [
- "event",
- "incident",
- "occurrence",
- "game",
- "match",
- "competition",
- ],
- "location": [
- "place",
- "location",
- "city",
- "country",
- "region",
- "area",
- ],
- "product": ["product", "item", "device", "software", "app", "tool"],
- }
- s.knowledge_graph = EntityKnowledgeGraph()
- return s
-
-
-# ---------------------------------------------------------------------------
-# EntityKnowledgeGraph.add_entity
-# ---------------------------------------------------------------------------
-
-
-class TestEntityKnowledgeGraphAddEntity:
- """Verify merge-on-add and fresh-insert logic."""
-
- def test_add_new_entity(self):
- """New entity is stored by name."""
- g = EntityKnowledgeGraph()
- e = _entity("Acme Corp")
- g.add_entity(e)
- assert "Acme Corp" in g.entities
-
- def test_merge_aliases(self):
- """Repeated add merges and deduplicates aliases."""
- g = EntityKnowledgeGraph()
- g.add_entity(_entity("X", aliases=["a", "b"]))
- g.add_entity(_entity("X", aliases=["b", "c"]))
- assert set(g.entities["X"].aliases) == {"a", "b", "c"}
-
- def test_merge_properties(self):
- """Properties dict is updated on merge."""
- g = EntityKnowledgeGraph()
- g.add_entity(_entity("X", properties={"k1": "v1"}))
- g.add_entity(_entity("X", properties={"k2": "v2"}))
- assert g.entities["X"].properties == {"k1": "v1", "k2": "v2"}
-
- def test_merge_sources(self):
- """Sources are merged and deduplicated."""
- g = EntityKnowledgeGraph()
- g.add_entity(_entity("X", sources=["s1", "s2"]))
- g.add_entity(_entity("X", sources=["s2", "s3"]))
- assert set(g.entities["X"].sources) == {"s1", "s2", "s3"}
-
- def test_merge_constraint_matches(self):
- """Constraint matches are updated on merge."""
- g = EntityKnowledgeGraph()
- g.add_entity(_entity("X", constraint_matches={"c1": 0.5}))
- g.add_entity(_entity("X", constraint_matches={"c2": 0.9}))
- assert g.entities["X"].constraint_matches == {"c1": 0.5, "c2": 0.9}
-
-
-# ---------------------------------------------------------------------------
-# EntityKnowledgeGraph.get_entities_by_constraint
-# ---------------------------------------------------------------------------
-
-
-class TestGetEntitiesByConstraint:
- """Verify threshold filtering and confidence-descending sort."""
-
- def test_filters_below_threshold(self):
- """Entities below min_confidence are excluded."""
- g = EntityKnowledgeGraph()
- g.add_entity(_entity("A", constraint_matches={"c1": 0.3}))
- g.add_entity(_entity("B", constraint_matches={"c1": 0.7}))
- result = g.get_entities_by_constraint("c1", min_confidence=0.5)
- assert [e.name for e in result] == ["B"]
-
- def test_sorted_descending(self):
- """Results are sorted by confidence descending."""
- g = EntityKnowledgeGraph()
- g.add_entity(_entity("A", constraint_matches={"c1": 0.6}))
- g.add_entity(_entity("B", constraint_matches={"c1": 0.9}))
- g.add_entity(_entity("C", constraint_matches={"c1": 0.75}))
- result = g.get_entities_by_constraint("c1", min_confidence=0.5)
- assert [e.name for e in result] == ["B", "C", "A"]
-
- def test_no_matching_constraint(self):
- """Entities without the constraint are excluded."""
- g = EntityKnowledgeGraph()
- g.add_entity(_entity("A", constraint_matches={"c2": 0.9}))
- assert g.get_entities_by_constraint("c1") == []
-
- def test_empty_graph(self):
- """Empty graph returns empty list."""
- g = EntityKnowledgeGraph()
- assert g.get_entities_by_constraint("c1") == []
-
-
-# ---------------------------------------------------------------------------
-# _identify_entity_type
-# ---------------------------------------------------------------------------
-
-
-class TestIdentifyEntityType:
- """Verify keyword-based entity type identification."""
-
- def _call(self, query):
- s = _make_strategy()
- return BrowseCompEntityStrategy._identify_entity_type(s, query)
-
- def test_company_keyword(self):
- """'corporation' -> 'company'."""
- assert self._call("Which corporation was founded in 1990?") == "company"
-
- def test_person_keyword(self):
- """'individual' -> 'person'."""
- assert self._call("Which individual won the award?") == "person"
-
- def test_event_keyword(self):
- """'competition' -> 'event'."""
- assert self._call("What competition took place in 2020?") == "event"
-
- def test_location_keyword(self):
- """'city' -> 'location'."""
- assert self._call("What city is known for X?") == "location"
-
- def test_product_keyword(self):
- """'software' -> 'product'."""
- assert self._call("Which software was released?") == "product"
-
- def test_who_fallback(self):
- """'who' without other keywords -> 'person'."""
- assert self._call("Who did this?") == "person"
-
- def test_which_fallback(self):
- """'which' without other keywords -> 'product'."""
- assert self._call("Which one is best?") == "product"
-
- def test_what_company_fallback(self):
- """'what' + 'company' -> 'company'."""
- assert self._call("What company does this?") == "company"
-
- def test_generic_fallback(self):
- """No keywords at all -> 'entity'."""
- assert self._call("Tell me about the answer") == "entity"
-
-
-# ---------------------------------------------------------------------------
-# entity_specificity
-# ---------------------------------------------------------------------------
-
-
-class TestEntitySpecificity:
- """Verify multi-factor specificity scoring."""
-
- def _call(self, entity):
- return BrowseCompEntityStrategy.entity_specificity(Mock(), entity)
-
- def test_single_short_word(self):
- """Short single word: length * 0.1 + 1 word * 2.0."""
- score = self._call("Abc")
- assert abs(score - (3 * 0.1 + 1 * 2.0)) < 1e-9
-
- def test_company_suffix_bonus(self):
- """Company suffix adds 10.0."""
- score = self._call("Acme Corp")
- assert score >= 10.0
-
- def test_hyphen_bonus(self):
- """Hyphenated entity gets +5.0."""
- base = self._call("PRAN")
- with_hyphen = self._call("PRAN-RFL")
- # Hyphen adds 5.0 (and possibly more from length/words)
- assert with_hyphen > base + 4.0
-
- def test_all_uppercase_bonus(self):
- """All-uppercase entity >= 3 chars gets +8.0."""
- score = self._call("IBM")
- # 3 * 0.1 + 1 * 2.0 + 8.0 = 10.3
- assert abs(score - 10.3) < 1e-9
-
- def test_multi_word_higher(self):
- """More words -> higher score due to word_count * 2.0."""
- one_word = self._call("Apple")
- two_words = self._call("Apple Inc")
- assert two_words > one_word
-
-
-# ---------------------------------------------------------------------------
-# _extract_constraint_terms
-# ---------------------------------------------------------------------------
-
-
-class TestExtractConstraintTerms:
- """Verify prefix stripping, regex extraction, and word filtering."""
-
- def _call(self, value, ctype=ConstraintType.PROPERTY):
- c = _constraint("c1", ctype, value)
- # Use real ConstraintType enum values (lowercase)
- # The method checks constraint.type.value against uppercase strings
- return BrowseCompEntityStrategy._extract_constraint_terms(Mock(), c)
-
- def test_long_words_extracted(self):
- """Words > 4 chars (not stopwords) are extracted."""
- result = self._call("something really interesting")
- assert "something" in result
- assert "really" in result
- assert "interesting" in result
-
- def test_capped_at_five(self):
- """No more than 5 terms returned."""
- result = self._call("alpha bravo charlie delta echo foxtrot")
- assert len(result) <= 5
-
- def test_prefix_stripped(self):
- """'Must be' prefix is removed before extraction."""
- result = self._call("Must be a large entity")
- # "Must" and "be" are stripped; remaining words > 4 chars kept
- assert "large" in result
- assert "entity" in result
-
- def test_short_words_excluded(self):
- """Words <= 4 chars are not included as general terms."""
- result = self._call("a big cat")
- # None of these words > 4 chars
- assert all(len(t) > 4 or t.isdigit() for t in result) or result == []
-
- def test_stopword_excluded(self):
- """Modal verbs in the stopword list are excluded."""
- result = self._call("should would could must")
- # All 4-5 char words that are in the exclusion list
- assert "should" not in result
- assert "would" not in result
- assert "could" not in result
-
-
-# ---------------------------------------------------------------------------
-# extract_entity_candidates
-# ---------------------------------------------------------------------------
-
-
-class TestExtractEntityCandidates:
- """Verify regex-based candidate extraction and specificity sort."""
-
- def _call(self, constraint_values):
- s = _make_strategy()
- # Bind the real entity_specificity method so sorted() can use it
- s.entity_specificity = (
- BrowseCompEntityStrategy.entity_specificity.__get__(s)
- )
- constraints = [
- _constraint(f"c{i}", value=v)
- for i, v in enumerate(constraint_values)
- ]
- return BrowseCompEntityStrategy.extract_entity_candidates(
- s, constraints
- )
-
- def test_extracts_proper_nouns(self):
- """Capitalized multi-word names are extracted."""
- result = self._call(["John Smith is the founder"])
- assert "John Smith" in result or "John" in result
-
- def test_extracts_company_patterns(self):
- """Company suffixes (Group, Inc, etc.) are captured."""
- result = self._call(["Founded by Acme Corp in 2000"])
- assert any("Acme" in r for r in result)
-
- def test_extracts_acronyms(self):
- """All-uppercase acronyms >= 2 chars are extracted."""
- result = self._call(["The PRAN-RFL group"])
- # Should find PRAN-RFL or PRAN or RFL
- assert any("PRAN" in r or "RFL" in r for r in result)
-
- def test_deduplicated(self):
- """Duplicate names across constraints are removed."""
- result = self._call(["John Smith", "John Smith again"])
- john_count = sum(1 for r in result if r == "John Smith")
- assert john_count <= 1
-
- def test_sorted_by_specificity(self):
- """Results are sorted by specificity score descending."""
- s = _make_strategy()
- s.entity_specificity = (
- BrowseCompEntityStrategy.entity_specificity.__get__(s)
- )
- constraints = [_constraint("c1", value="IBM Corp or Apple")]
- result = BrowseCompEntityStrategy.extract_entity_candidates(
- s, constraints
- )
- if len(result) >= 2:
- scores = [
- BrowseCompEntityStrategy.entity_specificity(s, r)
- for r in result
- ]
- assert scores == sorted(scores, reverse=True)
-
-
-# ---------------------------------------------------------------------------
-# _generate_entity_searches
-# ---------------------------------------------------------------------------
-
-
-class TestGenerateEntitySearches:
- """Verify type-based search query generation with regex extraction."""
-
- def _call(self, entity_type, constraints):
- return BrowseCompEntityStrategy._generate_entity_searches(
- Mock(), entity_type, constraints
- )
-
- def test_company_base_searches(self):
- """Company type produces company-related base queries."""
- result = self._call("company", [])
- assert any("companies" in q or "corporation" in q for q in result)
-
- def test_person_base_searches(self):
- """Person type produces person-related base queries."""
- result = self._call("person", [])
- assert any("people" in q or "person" in q for q in result)
-
- def test_event_base_searches(self):
- """Event type produces event-related base queries."""
- result = self._call("event", [])
- assert any("events" in q or "event" in q for q in result)
-
- def test_unknown_type_no_base(self):
- """Unknown entity type produces no base searches."""
- result = self._call("widget", [])
- assert len(result) == 0
-
- def test_constraint_type_branches_use_uppercase_comparison(self):
- """Constraint type branches compare against uppercase strings but
- ConstraintType enum values are lowercase, so these branches are
- currently unreachable. Verify only base searches are generated."""
- c = _constraint("c1", ConstraintType.STATISTIC, "has 42 employees")
- result = self._call("company", [c])
- # The "STATISTIC" uppercase comparison doesn't match "statistic",
- # so no number-extraction queries are added — only the 3 base queries
- assert len(result) == 3
-
-
-# ---------------------------------------------------------------------------
-# _summarize_knowledge
-# ---------------------------------------------------------------------------
-
-
-class TestSummarizeKnowledge:
- """Verify knowledge summary formatting."""
-
- def test_empty_graph(self):
- """Empty graph -> empty summary."""
- s = _make_strategy()
- result = BrowseCompEntityStrategy._summarize_knowledge(s)
- assert result == ""
-
- def test_entities_listed(self):
- """Entities are listed with confidence percentages."""
- s = _make_strategy()
- s.knowledge_graph.add_entity(
- _entity("Acme", confidence=0.85, entity_type="company")
- )
- result = BrowseCompEntityStrategy._summarize_knowledge(s)
- assert "Acme" in result
- assert "85" in result # 0.85 formatted as 85.00%
-
- def test_top_five_only(self):
- """Only top 5 entities by confidence are shown."""
- s = _make_strategy()
- for i in range(8):
- s.knowledge_graph.add_entity(
- _entity(f"E{i}", confidence=i * 0.1, entity_type="company")
- )
- result = BrowseCompEntityStrategy._summarize_knowledge(s)
- # Top 5 are E7, E6, E5, E4, E3
- assert "E7" in result
- assert "E0" not in result
-
- def test_properties_shown(self):
- """Entity properties are displayed."""
- s = _make_strategy()
- s.knowledge_graph.add_entity(
- _entity("X", confidence=0.5, properties={"color": "blue"})
- )
- result = BrowseCompEntityStrategy._summarize_knowledge(s)
- assert "color=blue" in result
-
- def test_constraint_evidence_shown(self):
- """Constraint evidence section is included when present."""
- s = _make_strategy()
- s.knowledge_graph.add_entity(_entity("X", confidence=0.5))
- s.knowledge_graph.constraint_evidence["some constraint"] = {
- "X": {"score": 0.75}
- }
- result = BrowseCompEntityStrategy._summarize_knowledge(s)
- assert "Constraint verification" in result
- assert "75" in result # 0.75 formatted as 75.00%
diff --git a/tests/advanced_search_system/strategies/test_browsecomp_entity_strategy.py b/tests/advanced_search_system/strategies/test_browsecomp_entity_strategy.py
deleted file mode 100644
index 8750d7f123..0000000000
--- a/tests/advanced_search_system/strategies/test_browsecomp_entity_strategy.py
+++ /dev/null
@@ -1,541 +0,0 @@
-"""
-Tests for BrowseCompEntityStrategy.
-
-Tests cover:
-- Initialization and configuration
-- Entity candidate management
-- Entity knowledge graph
-- Constraint checking integration
-- Entity pattern matching
-- Error handling
-"""
-
-from unittest.mock import Mock, patch
-import pytest
-
-
-class TestEntityCandidate:
- """Tests for EntityCandidate dataclass."""
-
- def test_create_entity_candidate(self):
- """Create entity candidate with required fields."""
- from local_deep_research.advanced_search_system.strategies.browsecomp_entity_strategy import (
- EntityCandidate,
- )
-
- candidate = EntityCandidate(
- name="Test Entity",
- entity_type="company",
- )
-
- assert candidate.name == "Test Entity"
- assert candidate.entity_type == "company"
- assert candidate.aliases == []
- assert candidate.properties == {}
- assert candidate.sources == []
- assert candidate.confidence == 0.0
- assert candidate.constraint_matches == {}
-
- def test_create_entity_candidate_with_all_fields(self):
- """Create entity candidate with all fields."""
- from local_deep_research.advanced_search_system.strategies.browsecomp_entity_strategy import (
- EntityCandidate,
- )
-
- candidate = EntityCandidate(
- name="Test Entity",
- entity_type="person",
- aliases=["Alias 1", "Alias 2"],
- properties={"key": "value"},
- sources=["http://source1.com"],
- confidence=0.85,
- constraint_matches={"c1": 0.9},
- )
-
- assert candidate.name == "Test Entity"
- assert len(candidate.aliases) == 2
- assert candidate.properties["key"] == "value"
- assert len(candidate.sources) == 1
- assert candidate.confidence == 0.85
- assert candidate.constraint_matches["c1"] == 0.9
-
-
-class TestEntityKnowledgeGraph:
- """Tests for EntityKnowledgeGraph class."""
-
- def test_init(self):
- """Initialize knowledge graph."""
- from local_deep_research.advanced_search_system.strategies.browsecomp_entity_strategy import (
- EntityKnowledgeGraph,
- )
-
- graph = EntityKnowledgeGraph()
-
- assert graph.entities == {}
- assert len(graph.constraint_evidence) == 0
- assert graph.search_cache == {}
-
- def test_add_entity(self):
- """Add entity to knowledge graph."""
- from local_deep_research.advanced_search_system.strategies.browsecomp_entity_strategy import (
- EntityKnowledgeGraph,
- EntityCandidate,
- )
-
- graph = EntityKnowledgeGraph()
- entity = EntityCandidate(name="Test", entity_type="company")
-
- graph.add_entity(entity)
-
- assert "Test" in graph.entities
- assert graph.entities["Test"] is entity
-
- def test_add_entity_merges_duplicate(self):
- """Add entity merges duplicate entries."""
- from local_deep_research.advanced_search_system.strategies.browsecomp_entity_strategy import (
- EntityKnowledgeGraph,
- EntityCandidate,
- )
-
- graph = EntityKnowledgeGraph()
-
- entity1 = EntityCandidate(
- name="Test",
- entity_type="company",
- aliases=["Alias1"],
- sources=["http://source1.com"],
- )
- entity2 = EntityCandidate(
- name="Test",
- entity_type="company",
- aliases=["Alias2"],
- sources=["http://source2.com"],
- )
-
- graph.add_entity(entity1)
- graph.add_entity(entity2)
-
- # Should merge aliases and sources
- assert len(graph.entities) == 1
- merged = graph.entities["Test"]
- assert "Alias1" in merged.aliases
- assert "Alias2" in merged.aliases
- assert len(merged.sources) == 2
-
- def test_add_constraint_evidence(self):
- """Add constraint evidence to graph."""
- from local_deep_research.advanced_search_system.strategies.browsecomp_entity_strategy import (
- EntityKnowledgeGraph,
- )
-
- graph = EntityKnowledgeGraph()
-
- graph.add_constraint_evidence(
- "constraint1",
- "entity1",
- {"text": "Evidence text", "confidence": 0.8},
- )
-
- assert "constraint1" in graph.constraint_evidence
- assert "entity1" in graph.constraint_evidence["constraint1"]
-
- def test_get_entities_by_constraint(self):
- """Get entities that match a constraint."""
- from local_deep_research.advanced_search_system.strategies.browsecomp_entity_strategy import (
- EntityKnowledgeGraph,
- EntityCandidate,
- )
-
- graph = EntityKnowledgeGraph()
-
- entity1 = EntityCandidate(
- name="Entity1",
- entity_type="company",
- constraint_matches={"c1": 0.9},
- )
- entity2 = EntityCandidate(
- name="Entity2",
- entity_type="company",
- constraint_matches={"c1": 0.3},
- )
-
- graph.add_entity(entity1)
- graph.add_entity(entity2)
-
- matches = graph.get_entities_by_constraint("c1", min_confidence=0.5)
-
- assert len(matches) == 1
- assert matches[0].name == "Entity1"
-
- def test_get_entities_by_constraint_sorted(self):
- """Get entities sorted by confidence."""
- from local_deep_research.advanced_search_system.strategies.browsecomp_entity_strategy import (
- EntityKnowledgeGraph,
- EntityCandidate,
- )
-
- graph = EntityKnowledgeGraph()
-
- entity1 = EntityCandidate(
- name="Low",
- entity_type="company",
- constraint_matches={"c1": 0.6},
- )
- entity2 = EntityCandidate(
- name="High",
- entity_type="company",
- constraint_matches={"c1": 0.9},
- )
-
- graph.add_entity(entity1)
- graph.add_entity(entity2)
-
- matches = graph.get_entities_by_constraint("c1", min_confidence=0.5)
-
- assert len(matches) == 2
- assert matches[0].name == "High" # Higher confidence first
-
-
-class TestBrowseCompEntityStrategyInit:
- """Tests for BrowseCompEntityStrategy initialization."""
-
- def test_init_with_required_params(self):
- """Initialize with required parameters."""
- from local_deep_research.advanced_search_system.strategies.browsecomp_entity_strategy import (
- BrowseCompEntityStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = BrowseCompEntityStrategy(
- model=mock_model,
- search=mock_search,
- )
-
- assert strategy.model is mock_model
- assert strategy.search_engine is mock_search
-
- def test_init_creates_knowledge_graph(self):
- """Initialize creates knowledge graph."""
- from local_deep_research.advanced_search_system.strategies.browsecomp_entity_strategy import (
- BrowseCompEntityStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = BrowseCompEntityStrategy(
- model=mock_model,
- search=mock_search,
- )
-
- assert strategy.knowledge_graph is not None
-
- def test_init_creates_components_with_model(self):
- """Initialize creates components when model provided."""
- from local_deep_research.advanced_search_system.strategies.browsecomp_entity_strategy import (
- BrowseCompEntityStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = BrowseCompEntityStrategy(
- model=mock_model,
- search=mock_search,
- )
-
- assert strategy.constraint_analyzer is not None
- assert strategy.question_generator is not None
- assert strategy.constraint_checker is not None
-
- def test_init_entity_patterns(self):
- """Initialize includes entity patterns."""
- from local_deep_research.advanced_search_system.strategies.browsecomp_entity_strategy import (
- BrowseCompEntityStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = BrowseCompEntityStrategy(
- model=mock_model,
- search=mock_search,
- )
-
- assert "company" in strategy.entity_patterns
- assert "person" in strategy.entity_patterns
- assert "event" in strategy.entity_patterns
- assert "location" in strategy.entity_patterns
- assert "product" in strategy.entity_patterns
-
-
-class TestBrowseCompEntityStrategySearch:
- """Tests for search method."""
-
- @pytest.mark.asyncio
- async def test_search_returns_tuple(self):
- """Search method returns tuple of (str, dict)."""
- from local_deep_research.advanced_search_system.strategies.browsecomp_entity_strategy import (
- BrowseCompEntityStrategy,
- )
-
- mock_search = Mock()
- mock_search.run.return_value = []
- mock_model = Mock()
- mock_model.invoke.return_value = Mock(content="Test response")
-
- strategy = BrowseCompEntityStrategy(
- model=mock_model,
- search=mock_search,
- )
-
- # Mock constraint analyzer
- with patch.object(
- strategy.constraint_analyzer, "extract_constraints", return_value=[]
- ):
- with patch.object(
- strategy.question_generator,
- "generate_questions",
- return_value=[],
- ):
- result = await strategy.search("test query")
-
- assert isinstance(result, tuple)
- assert len(result) == 2
-
- @pytest.mark.asyncio
- async def test_search_calls_progress_callback(self):
- """Search calls progress callback."""
- from local_deep_research.advanced_search_system.strategies.browsecomp_entity_strategy import (
- BrowseCompEntityStrategy,
- )
-
- mock_search = Mock()
- mock_search.run.return_value = []
- mock_model = Mock()
- mock_model.invoke.return_value = Mock(content="Test")
-
- strategy = BrowseCompEntityStrategy(
- model=mock_model,
- search=mock_search,
- )
-
- callback = Mock()
-
- with patch.object(
- strategy.constraint_analyzer, "extract_constraints", return_value=[]
- ):
- with patch.object(
- strategy.question_generator,
- "generate_questions",
- return_value=[],
- ):
- await strategy.search("test query", progress_callback=callback)
-
- # Callback should be called at some point
- assert callback.call_count >= 0
-
-
-class TestEntityPatternMatching:
- """Tests for entity pattern matching."""
-
- def test_company_patterns(self):
- """Company patterns include expected terms."""
- from local_deep_research.advanced_search_system.strategies.browsecomp_entity_strategy import (
- BrowseCompEntityStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = BrowseCompEntityStrategy(
- model=mock_model,
- search=mock_search,
- )
-
- company_patterns = strategy.entity_patterns["company"]
-
- assert "company" in company_patterns
- assert "corporation" in company_patterns
- assert "firm" in company_patterns
-
- def test_person_patterns(self):
- """Person patterns include expected terms."""
- from local_deep_research.advanced_search_system.strategies.browsecomp_entity_strategy import (
- BrowseCompEntityStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = BrowseCompEntityStrategy(
- model=mock_model,
- search=mock_search,
- )
-
- person_patterns = strategy.entity_patterns["person"]
-
- assert "person" in person_patterns
- assert "individual" in person_patterns
-
- def test_location_patterns(self):
- """Location patterns include expected terms."""
- from local_deep_research.advanced_search_system.strategies.browsecomp_entity_strategy import (
- BrowseCompEntityStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = BrowseCompEntityStrategy(
- model=mock_model,
- search=mock_search,
- )
-
- location_patterns = strategy.entity_patterns["location"]
-
- assert "place" in location_patterns
- assert "city" in location_patterns
- assert "country" in location_patterns
-
-
-class TestComponentIntegration:
- """Tests for component integration."""
-
- def test_constraint_checker_integration(self):
- """Constraint checker uses correct settings."""
- from local_deep_research.advanced_search_system.strategies.browsecomp_entity_strategy import (
- BrowseCompEntityStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = BrowseCompEntityStrategy(
- model=mock_model,
- search=mock_search,
- )
-
- checker = strategy.constraint_checker
-
- # Should have lenient thresholds for entities
- assert checker.negative_threshold == 0.3
- assert checker.positive_threshold == 0.4
-
- def test_explorer_integration(self):
- """Explorer is created with search and model."""
- from local_deep_research.advanced_search_system.strategies.browsecomp_entity_strategy import (
- BrowseCompEntityStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = BrowseCompEntityStrategy(
- model=mock_model,
- search=mock_search,
- )
-
- assert strategy.explorer is not None
-
-
-class TestEvidenceGathering:
- """Tests for evidence gathering methods."""
-
- def test_gather_entity_evidence_method_exists(self):
- """Gather entity evidence method exists."""
- from local_deep_research.advanced_search_system.strategies.browsecomp_entity_strategy import (
- BrowseCompEntityStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = BrowseCompEntityStrategy(
- model=mock_model,
- search=mock_search,
- )
-
- assert hasattr(strategy, "_gather_entity_evidence")
- assert callable(strategy._gather_entity_evidence)
-
-
-class TestBaseStrategyInheritance:
- """Tests for base strategy inheritance."""
-
- def test_inherits_from_base_strategy(self):
- """Strategy inherits from BaseSearchStrategy."""
- from local_deep_research.advanced_search_system.strategies.browsecomp_entity_strategy import (
- BrowseCompEntityStrategy,
- )
- from local_deep_research.advanced_search_system.strategies.base_strategy import (
- BaseSearchStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = BrowseCompEntityStrategy(
- model=mock_model,
- search=mock_search,
- )
-
- assert isinstance(strategy, BaseSearchStrategy)
-
- def test_has_all_links_of_system(self):
- """Strategy has all_links_of_system attribute."""
- from local_deep_research.advanced_search_system.strategies.browsecomp_entity_strategy import (
- BrowseCompEntityStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
- links = [{"url": "http://test.com"}]
-
- strategy = BrowseCompEntityStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=links,
- )
-
- assert strategy.all_links_of_system is links
-
- def test_has_settings_snapshot(self):
- """Strategy has settings_snapshot attribute."""
- from local_deep_research.advanced_search_system.strategies.browsecomp_entity_strategy import (
- BrowseCompEntityStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
- settings = {"key": "value"}
-
- strategy = BrowseCompEntityStrategy(
- model=mock_model,
- search=mock_search,
- settings_snapshot=settings,
- )
-
- assert strategy.settings_snapshot is settings
-
-
-class TestErrorHandling:
- """Tests for error handling."""
-
- def test_init_without_model_logs_warning(self):
- """Initialize without model logs warning."""
- from local_deep_research.advanced_search_system.strategies.browsecomp_entity_strategy import (
- BrowseCompEntityStrategy,
- )
-
- mock_search = Mock()
-
- # Should not raise, but may log warning
- strategy = BrowseCompEntityStrategy(
- model=None,
- search=mock_search,
- )
-
- assert strategy.model is None
diff --git a/tests/advanced_search_system/strategies/test_browsecomp_optimized_high_value.py b/tests/advanced_search_system/strategies/test_browsecomp_optimized_high_value.py
deleted file mode 100644
index 08d699692e..0000000000
--- a/tests/advanced_search_system/strategies/test_browsecomp_optimized_high_value.py
+++ /dev/null
@@ -1,291 +0,0 @@
-"""High-value tests for BrowseCompOptimizedStrategy pure logic methods."""
-
-import pytest
-from unittest.mock import patch
-
-from local_deep_research.advanced_search_system.strategies.browsecomp_optimized_strategy import (
- BrowseCompOptimizedStrategy,
- QueryClues,
-)
-
-
-# --- QueryClues dataclass ---
-
-
-class TestQueryClues:
- def test_defaults(self):
- clues = QueryClues()
- assert clues.location_clues == []
- assert clues.temporal_clues == []
- assert clues.numerical_clues == []
- assert clues.name_clues == []
- assert clues.incident_clues == []
- assert clues.comparison_clues == []
- assert clues.all_clues == []
- assert clues.query_type == "unknown"
-
- def test_custom_values(self):
- clues = QueryClues(
- location_clues=["Colorado"],
- query_type="location",
- )
- assert clues.location_clues == ["Colorado"]
- assert clues.query_type == "location"
-
- def test_mutable_defaults_independent(self):
- c1 = QueryClues()
- c2 = QueryClues()
- c1.location_clues.append("test")
- assert c2.location_clues == []
-
-
-def strategy():
- """Create a BrowseCompOptimizedStrategy with mocked init."""
- with patch.object(
- BrowseCompOptimizedStrategy, "__init__", lambda self, *a, **kw: None
- ):
- s = BrowseCompOptimizedStrategy.__new__(BrowseCompOptimizedStrategy)
- s.query_clues = QueryClues(
- location_clues=["near Grand Canyon"],
- temporal_clues=["2014"],
- numerical_clues=["84.5x ratio"],
- name_clues=["contains body part"],
- incident_clues=["hiker fell to death"],
- comparison_clues=["84.5 times Grand Canyon 2022"],
- all_clues=[
- "near Grand Canyon",
- "2014",
- "hiker fell",
- "body part name",
- "84.5x ratio",
- ],
- )
- s.confirmed_info = {}
- s.candidates = []
- s.search_history = []
- s.iteration = 0
- s.confidence_threshold = 0.90
- s.max_browsecomp_iterations = 15
- s.progress_callback = None
- return s
-
-
-# --- _get_matched_clues ---
-
-
-class TestGetMatchedClues:
- def test_name_clue_word_match(self, strategy):
- strategy.query_clues.name_clues = ["contains arm"]
- matched = strategy._get_matched_clues("Arm Creek")
- assert any("name:" in m for m in matched)
-
- def test_name_clue_no_match(self, strategy):
- strategy.query_clues.name_clues = ["contains arm"]
- matched = strategy._get_matched_clues("Silver Creek")
- assert not any("name:" in m for m in matched)
-
- def test_location_in_confirmed_info(self, strategy):
- strategy.query_clues.location_clues = ["near Grand Canyon"]
- strategy.confirmed_info = {
- "near Grand Canyon": "arm creek is near the grand canyon"
- }
- matched = strategy._get_matched_clues("Arm Creek")
- assert any("location:" in m for m in matched)
-
- def test_fact_match(self, strategy):
- strategy.confirmed_info = {"arm creek hiking trail": "scenic viewpoint"}
- matched = strategy._get_matched_clues("Arm Creek")
- assert any("fact:" in m for m in matched)
-
- def test_temporal_year_match(self, strategy):
- strategy.query_clues.temporal_clues = ["in 2014"]
- strategy.confirmed_info = {"arm creek 2014 accident": "confirmed"}
- matched = strategy._get_matched_clues("Arm Creek")
- assert any("temporal:" in m for m in matched)
-
- def test_incident_word_match(self, strategy):
- strategy.query_clues.incident_clues = ["hiker fell to death"]
- strategy.confirmed_info = {"arm creek hiker fell": "confirmed"}
- matched = strategy._get_matched_clues("Arm Creek")
- assert any("incident:" in m for m in matched)
-
- def test_deduplication(self, strategy):
- strategy.query_clues.name_clues = ["arm", "arm"]
- matched = strategy._get_matched_clues("Arm Creek")
- # Duplicates removed via set
- assert len(matched) == len(set(matched))
-
-
-# --- _get_unverified_clues ---
-
-
-class TestGetUnverifiedClues:
- def test_all_unverified(self, strategy):
- candidate = {"name": "Test", "matched_clues": []}
- unverified = strategy._get_unverified_clues(candidate)
- assert len(unverified) > 0
-
- def test_some_verified(self, strategy):
- candidate = {
- "name": "Test",
- "matched_clues": ["name: contains body part"],
- }
- strategy.query_clues.name_clues = ["contains body part"]
- strategy.query_clues.location_clues = ["near Grand Canyon"]
- strategy.query_clues.temporal_clues = []
- strategy.query_clues.numerical_clues = []
- strategy.query_clues.incident_clues = []
- strategy.query_clues.comparison_clues = []
- unverified = strategy._get_unverified_clues(candidate)
- assert "near Grand Canyon" in unverified
-
- def test_type_prefix_extracted(self, strategy):
- """Matched clues with 'type: clue' format should extract the clue text."""
- candidate = {
- "name": "Test",
- "matched_clues": ["location: near Grand Canyon"],
- }
- strategy.query_clues.location_clues = ["near Grand Canyon"]
- strategy.query_clues.temporal_clues = []
- strategy.query_clues.numerical_clues = []
- strategy.query_clues.name_clues = []
- strategy.query_clues.incident_clues = []
- strategy.query_clues.comparison_clues = []
- unverified = strategy._get_unverified_clues(candidate)
- assert "near Grand Canyon" not in unverified
-
-
-# --- _evaluate_candidates ---
-
-
-class TestEvaluateCandidates:
- def test_no_candidates_returns_false(self, strategy):
- strategy.candidates = []
- assert strategy._evaluate_candidates() is False
-
- def test_high_confidence_high_ratio(self, strategy):
- strategy.candidates = [
- {
- "name": "Test",
- "confidence": 0.92,
- "matched_clues": ["a", "b", "c", "d"],
- },
- ]
- strategy.query_clues.all_clues = ["a", "b", "c", "d", "e"]
- # 4/5 = 0.8 >= 0.8 and 0.92 >= 0.90
- assert strategy._evaluate_candidates() is True
-
- def test_high_confidence_low_ratio(self, strategy):
- strategy.candidates = [
- {"name": "Test", "confidence": 0.92, "matched_clues": ["a"]},
- ]
- strategy.query_clues.all_clues = ["a", "b", "c", "d", "e"]
- # 1/5 = 0.2 < 0.8
- strategy.iteration = 1 # guard: iteration < 3 -> False
- assert strategy._evaluate_candidates() is False
-
- def test_very_high_confidence_90pct_ratio(self, strategy):
- strategy.candidates = [
- {
- "name": "Test",
- "confidence": 0.96,
- "matched_clues": list(range(9)),
- },
- ]
- strategy.query_clues.all_clues = list(range(10))
- # 9/10 = 0.9 >= 0.9 and 0.96 >= 0.95
- assert strategy._evaluate_candidates() is True
-
- def test_iteration_less_than_3_guard(self, strategy):
- strategy.iteration = 2
- strategy.candidates = [
- {"name": "Test", "confidence": 0.5, "matched_clues": []},
- ]
- assert strategy._evaluate_candidates() is False
-
- def test_iteration_8_with_gap(self, strategy):
- strategy.iteration = 8
- strategy.candidates = [
- {"name": "Leader", "confidence": 0.7, "matched_clues": []},
- {"name": "Second", "confidence": 0.3, "matched_clues": []},
- ]
- strategy.query_clues.all_clues = ["a"]
- # gap = 0.7 - 0.3 = 0.4 > 0.3
- assert strategy._evaluate_candidates() is True
-
- def test_iteration_8_no_gap(self, strategy):
- strategy.iteration = 8
- strategy.candidates = [
- {"name": "Leader", "confidence": 0.7, "matched_clues": []},
- {"name": "Second", "confidence": 0.6, "matched_clues": []},
- ]
- strategy.query_clues.all_clues = ["a"]
- # gap = 0.1 < 0.3
- assert strategy._evaluate_candidates() is False
-
-
-# --- _generate_targeted_search ---
-
-
-class TestGenerateTargetedSearch:
- def test_iteration_1_broad(self, strategy):
- strategy.iteration = 1
- result = strategy._generate_targeted_search()
- assert result is not None
- assert isinstance(result, str)
-
- def test_iteration_2_temporal(self, strategy):
- strategy.iteration = 2
- result = strategy._generate_targeted_search()
- assert result is not None
-
- def test_iteration_3_to_8_combinations(self, strategy):
- strategy.iteration = 4
- strategy.candidates = [] # No candidates to verify
- result = strategy._generate_targeted_search()
- assert result is not None
-
- def test_iteration_gt_8_stats(self, strategy):
- strategy.iteration = 9
- strategy.candidates = []
- result = strategy._generate_targeted_search()
- assert result is not None
- assert "statistics" in result or "data" in result or result is not None
-
- def test_iteration_gt_8_numerical(self, strategy):
- strategy.iteration = 9
- strategy.candidates = []
- strategy.query_clues.comparison_clues = []
- strategy.query_clues.numerical_clues = ["84.5x ratio"]
- result = strategy._generate_targeted_search()
- assert result is not None
-
- def test_with_candidates_iteration_gt_2(self, strategy):
- strategy.iteration = 3
- strategy.candidates = [
- {"name": "Arm Creek", "matched_clues": ["name: arm"]},
- ]
- # Set up unverified clues
- strategy.query_clues.incident_clues = ["hiker fell to death"]
- result = strategy._generate_targeted_search()
- assert result is not None
-
- def test_no_more_clues_returns_none(self, strategy):
- strategy.iteration = 20
- strategy.candidates = []
- strategy.query_clues = QueryClues()
- strategy.search_history = []
- result = strategy._generate_targeted_search()
- assert result is None
-
- def test_unused_clues_as_fallback(self, strategy):
- strategy.iteration = 20
- strategy.candidates = []
- strategy.query_clues = QueryClues(all_clues=["unique clue"])
- strategy.search_history = []
- # No comparison or numerical clues, so falls through to unused clues
- strategy.query_clues.comparison_clues = []
- strategy.query_clues.numerical_clues = []
- result = strategy._generate_targeted_search()
- assert result == "unique clue"
diff --git a/tests/advanced_search_system/strategies/test_browsecomp_optimized_strategy.py b/tests/advanced_search_system/strategies/test_browsecomp_optimized_strategy.py
deleted file mode 100644
index 8ae608e7bf..0000000000
--- a/tests/advanced_search_system/strategies/test_browsecomp_optimized_strategy.py
+++ /dev/null
@@ -1,458 +0,0 @@
-"""
-Tests for BrowseComp Optimized Strategy.
-
-Phase 35: Complex Strategies - Tests for browsecomp_optimized_strategy.py
-Tests puzzle query handling, clue extraction, and candidate verification.
-"""
-
-from unittest.mock import MagicMock
-
-from local_deep_research.advanced_search_system.strategies.browsecomp_optimized_strategy import (
- BrowseCompOptimizedStrategy,
- QueryClues,
-)
-
-
-class TestQueryCluesDataclass:
- """Tests for QueryClues dataclass."""
-
- def test_query_clues_initialization(self):
- """Test QueryClues initializes with empty lists."""
- clues = QueryClues()
- assert clues.location_clues == []
- assert clues.temporal_clues == []
- assert clues.numerical_clues == []
- assert clues.name_clues == []
- assert clues.incident_clues == []
- assert clues.comparison_clues == []
- assert clues.all_clues == []
- assert clues.query_type == "unknown"
-
- def test_query_clues_with_values(self):
- """Test QueryClues with provided values."""
- clues = QueryClues(
- location_clues=["Paris", "France"],
- temporal_clues=["2024"],
- numerical_clues=["100"],
- query_type="location",
- )
- assert "Paris" in clues.location_clues
- assert "2024" in clues.temporal_clues
- assert clues.query_type == "location"
-
- def test_query_clues_all_clues(self):
- """Test all_clues field."""
- clues = QueryClues(all_clues=["clue1", "clue2", "clue3"])
- assert len(clues.all_clues) == 3
-
-
-class TestBrowseCompOptimizedStrategyInit:
- """Tests for strategy initialization."""
-
- def test_initialization_basic(self):
- """Test basic initialization."""
- mock_model = MagicMock()
- mock_search = MagicMock()
-
- strategy = BrowseCompOptimizedStrategy(
- model=mock_model, search=mock_search, all_links_of_system=[]
- )
-
- assert strategy.model is mock_model
- assert strategy.search is mock_search
- assert strategy.max_browsecomp_iterations == 15
- assert strategy.confidence_threshold == 0.90
-
- def test_initialization_custom_params(self):
- """Test initialization with custom parameters."""
- mock_model = MagicMock()
- mock_search = MagicMock()
-
- strategy = BrowseCompOptimizedStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- max_browsecomp_iterations=20,
- confidence_threshold=0.85,
- )
-
- assert strategy.max_browsecomp_iterations == 20
- assert strategy.confidence_threshold == 0.85
-
- def test_initialization_state(self):
- """Test initial state is properly set."""
- mock_model = MagicMock()
- mock_search = MagicMock()
-
- strategy = BrowseCompOptimizedStrategy(
- model=mock_model, search=mock_search, all_links_of_system=[]
- )
-
- assert strategy.query_clues is None
- assert strategy.confirmed_info == {}
- assert strategy.candidates == []
- assert strategy.search_history == []
- assert strategy.iteration == 0
-
- def test_initialization_with_links(self):
- """Test initialization with existing links."""
- mock_model = MagicMock()
- mock_search = MagicMock()
- links = ["http://link1.com", "http://link2.com"]
-
- strategy = BrowseCompOptimizedStrategy(
- model=mock_model, search=mock_search, all_links_of_system=links
- )
-
- assert len(strategy.all_links_of_system) == 2
-
-
-class TestClueExtraction:
- """Tests for clue extraction functionality."""
-
- def test_extract_clues_location(self):
- """Test extraction of location clues."""
- mock_model = MagicMock()
- mock_search = MagicMock()
- mock_response = MagicMock()
- mock_response.content = """
- Location clues: Paris, France
- Temporal clues: 2024
- Query type: location
- """
- mock_model.invoke.return_value = mock_response
-
- strategy = BrowseCompOptimizedStrategy(
- model=mock_model, search=mock_search, all_links_of_system=[]
- )
-
- if hasattr(strategy, "_extract_clues"):
- clues = strategy._extract_clues("Where is the Eiffel Tower?")
- assert clues is not None
-
- def test_extract_clues_temporal(self):
- """Test extraction of temporal clues."""
- mock_model = MagicMock()
- mock_search = MagicMock()
- mock_response = MagicMock()
- mock_response.content = "Temporal clues: 1889, 19th century"
- mock_model.invoke.return_value = mock_response
-
- strategy = BrowseCompOptimizedStrategy(
- model=mock_model, search=mock_search, all_links_of_system=[]
- )
-
- if hasattr(strategy, "_extract_clues"):
- clues = strategy._extract_clues("When was the Eiffel Tower built?")
- assert clues is not None
-
- def test_extract_clues_numerical(self):
- """Test extraction of numerical clues."""
- mock_model = MagicMock()
- mock_search = MagicMock()
- mock_response = MagicMock()
- mock_response.content = (
- "Numerical clues: 300 meters, 7 million visitors"
- )
- mock_model.invoke.return_value = mock_response
-
- strategy = BrowseCompOptimizedStrategy(
- model=mock_model, search=mock_search, all_links_of_system=[]
- )
-
- if hasattr(strategy, "_extract_clues"):
- clues = strategy._extract_clues("How tall is the Eiffel Tower?")
- assert clues is not None
-
-
-class TestAnalyzeTopic:
- """Tests for analyze_topic method."""
-
- def test_analyze_topic_clears_state(self):
- """Test analyze_topic clears previous state."""
- mock_model = MagicMock()
- mock_search = MagicMock()
- mock_response = MagicMock()
- mock_response.content = "Clues: test"
- mock_model.invoke.return_value = mock_response
-
- strategy = BrowseCompOptimizedStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=["old_link"],
- )
-
- # Add some state
- strategy.candidates = [{"name": "old"}]
- strategy.iteration = 5
-
- try:
- _result = strategy.analyze_topic("New query") # noqa: F841
- # State should be cleared
- assert strategy.iteration >= 0
- except Exception:
- # May need additional mocking
- pass
-
- def test_analyze_topic_calls_progress_callback(self):
- """Test analyze_topic calls progress callback."""
- mock_model = MagicMock()
- mock_search = MagicMock()
- mock_response = MagicMock()
- mock_response.content = """
- All clues: test1, test2
- Query type: location
- """
- mock_model.invoke.return_value = mock_response
-
- callback = MagicMock()
- strategy = BrowseCompOptimizedStrategy(
- model=mock_model, search=mock_search, all_links_of_system=[]
- )
- strategy.progress_callback = callback
-
- try:
- strategy.analyze_topic("Test query")
- # Progress callback should be called
- assert callback.called or True
- except Exception:
- pass
-
- def test_analyze_topic_returns_dict(self):
- """Test analyze_topic returns dictionary."""
- mock_model = MagicMock()
- mock_search = MagicMock()
- mock_response = MagicMock()
- mock_response.content = "Test response"
- mock_model.invoke.return_value = mock_response
-
- strategy = BrowseCompOptimizedStrategy(
- model=mock_model, search=mock_search, all_links_of_system=[]
- )
-
- try:
- result = strategy.analyze_topic("Test query")
- assert isinstance(result, dict)
- except Exception:
- # Expected if not fully mocked
- pass
-
-
-class TestCandidateManagement:
- """Tests for candidate management."""
-
- def test_candidates_list_initialization(self):
- """Test candidates list is properly initialized."""
- mock_model = MagicMock()
- mock_search = MagicMock()
-
- strategy = BrowseCompOptimizedStrategy(
- model=mock_model, search=mock_search, all_links_of_system=[]
- )
-
- assert isinstance(strategy.candidates, list)
- assert len(strategy.candidates) == 0
-
- def test_add_candidate(self):
- """Test adding candidates."""
- mock_model = MagicMock()
- mock_search = MagicMock()
-
- strategy = BrowseCompOptimizedStrategy(
- model=mock_model, search=mock_search, all_links_of_system=[]
- )
-
- strategy.candidates.append({"name": "Candidate 1", "score": 0.8})
- assert len(strategy.candidates) == 1
-
-
-class TestConfidenceThreshold:
- """Tests for confidence threshold handling."""
-
- def test_default_confidence_threshold(self):
- """Test default confidence threshold."""
- mock_model = MagicMock()
- mock_search = MagicMock()
-
- strategy = BrowseCompOptimizedStrategy(
- model=mock_model, search=mock_search, all_links_of_system=[]
- )
-
- assert strategy.confidence_threshold == 0.90
-
- def test_custom_confidence_threshold(self):
- """Test custom confidence threshold."""
- mock_model = MagicMock()
- mock_search = MagicMock()
-
- strategy = BrowseCompOptimizedStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- confidence_threshold=0.75,
- )
-
- assert strategy.confidence_threshold == 0.75
-
-
-class TestIterationControl:
- """Tests for iteration control."""
-
- def test_max_iterations_default(self):
- """Test default max iterations."""
- mock_model = MagicMock()
- mock_search = MagicMock()
-
- strategy = BrowseCompOptimizedStrategy(
- model=mock_model, search=mock_search, all_links_of_system=[]
- )
-
- assert strategy.max_browsecomp_iterations == 15
-
- def test_max_iterations_custom(self):
- """Test custom max iterations."""
- mock_model = MagicMock()
- mock_search = MagicMock()
-
- strategy = BrowseCompOptimizedStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- max_browsecomp_iterations=30,
- )
-
- assert strategy.max_browsecomp_iterations == 30
-
- def test_iteration_tracking(self):
- """Test iteration counter."""
- mock_model = MagicMock()
- mock_search = MagicMock()
-
- strategy = BrowseCompOptimizedStrategy(
- model=mock_model, search=mock_search, all_links_of_system=[]
- )
-
- assert strategy.iteration == 0
- strategy.iteration += 1
- assert strategy.iteration == 1
-
-
-class TestSearchHistory:
- """Tests for search history tracking."""
-
- def test_search_history_initialization(self):
- """Test search history is initialized empty."""
- mock_model = MagicMock()
- mock_search = MagicMock()
-
- strategy = BrowseCompOptimizedStrategy(
- model=mock_model, search=mock_search, all_links_of_system=[]
- )
-
- assert strategy.search_history == []
-
- def test_search_history_append(self):
- """Test appending to search history."""
- mock_model = MagicMock()
- mock_search = MagicMock()
-
- strategy = BrowseCompOptimizedStrategy(
- model=mock_model, search=mock_search, all_links_of_system=[]
- )
-
- strategy.search_history.append("Search query 1")
- strategy.search_history.append("Search query 2")
-
- assert len(strategy.search_history) == 2
-
-
-class TestFindingsRepository:
- """Tests for findings repository integration."""
-
- def test_findings_repository_initialized(self):
- """Test findings repository is initialized."""
- mock_model = MagicMock()
- mock_search = MagicMock()
-
- strategy = BrowseCompOptimizedStrategy(
- model=mock_model, search=mock_search, all_links_of_system=[]
- )
-
- assert strategy.findings_repository is not None
-
-
-class TestProgressCallback:
- """Tests for progress callback functionality."""
-
- def test_progress_callback_assignment(self):
- """Test progress callback can be assigned."""
- mock_model = MagicMock()
- mock_search = MagicMock()
-
- strategy = BrowseCompOptimizedStrategy(
- model=mock_model, search=mock_search, all_links_of_system=[]
- )
-
- callback = MagicMock()
- strategy.progress_callback = callback
-
- assert strategy.progress_callback is callback
-
-
-class TestProcessSearchResultsConfidenceParsing:
- """Tests for confidence parsing in _process_search_results (PR #2020).
-
- PR #2020 changed bare `except:` to `except (ValueError, IndexError):`
- when parsing confidence from candidate strings like "name: 0.85".
- """
-
- def test_confidence_parsing_with_valid_float(self):
- """Test confidence parsing with valid float string."""
- # Simulates the parsing logic from _process_search_results
- confidence_str = "0.85 some extra text"
- try:
- confidence = float(confidence_str.split()[0])
- except (ValueError, IndexError):
- confidence = 0.5
-
- assert confidence == 0.85
-
- def test_confidence_parsing_with_invalid_string(self):
- """Test confidence falls back to 0.5 with invalid string (ValueError)."""
- confidence_str = "invalid_value"
- try:
- confidence = float(confidence_str.split()[0])
- except (ValueError, IndexError):
- confidence = 0.5
-
- assert confidence == 0.5
-
- def test_confidence_parsing_with_empty_string(self):
- """Test confidence falls back to 0.5 with empty string (IndexError)."""
- confidence_str = " " # Only whitespace, split() returns []
- try:
- confidence = float(confidence_str.split()[0])
- except (ValueError, IndexError):
- confidence = 0.5
-
- assert confidence == 0.5
-
- def test_confidence_parsing_with_integer(self):
- """Test confidence parsing with integer string."""
- confidence_str = "1"
- try:
- confidence = float(confidence_str.split()[0])
- except (ValueError, IndexError):
- confidence = 0.5
-
- assert confidence == 1.0
-
- def test_confidence_parsing_with_zero(self):
- """Test confidence parsing with zero."""
- confidence_str = "0.0 low confidence"
- try:
- confidence = float(confidence_str.split()[0])
- except (ValueError, IndexError):
- confidence = 0.5
-
- assert confidence == 0.0
diff --git a/tests/advanced_search_system/strategies/test_concurrent_dual_confidence_high_value.py b/tests/advanced_search_system/strategies/test_concurrent_dual_confidence_high_value.py
deleted file mode 100644
index b99a58979e..0000000000
--- a/tests/advanced_search_system/strategies/test_concurrent_dual_confidence_high_value.py
+++ /dev/null
@@ -1,460 +0,0 @@
-"""
-High-value tests for ConcurrentDualConfidenceStrategy.
-
-Covers pure logic paths:
-- SearchState dataclass defaults and field types
-- _classify_constraint_difficulty: constraint type adjustment, sorting
-- _build_combined_query: multi-word quoting, already-quoted passthrough, concatenation
-- _should_stop_search: all 7 stopping criteria
-- _is_candidate_evaluated: thread-safe duplicate check
-"""
-
-import threading
-import time
-from unittest.mock import MagicMock, Mock
-
-
-from local_deep_research.advanced_search_system.strategies.concurrent_dual_confidence_strategy import (
- ConcurrentDualConfidenceStrategy,
- SearchState,
-)
-
-
-# ---------------------------------------------------------------------------
-# Helpers
-# ---------------------------------------------------------------------------
-
-
-def _make_strategy(**kwargs):
- """Create a ConcurrentDualConfidenceStrategy with mocked dependencies."""
- model = MagicMock()
- search = MagicMock()
- defaults = dict(
- model=model,
- search=search,
- all_links_of_system=[],
- )
- defaults.update(kwargs)
- return ConcurrentDualConfidenceStrategy(**defaults)
-
-
-def _make_constraint(value="test", type_name="PROPERTY"):
- """Create a mock Constraint with a ConstraintType."""
- from local_deep_research.advanced_search_system.constraints.base_constraint import (
- ConstraintType,
- )
-
- constraint = Mock()
- constraint.value = value
- constraint.type = ConstraintType[type_name]
- return constraint
-
-
-def _make_candidate(name="Candidate"):
- """Create a mock Candidate."""
- c = Mock()
- c.name = name
- return c
-
-
-# ---------------------------------------------------------------------------
-# SearchState dataclass
-# ---------------------------------------------------------------------------
-
-
-class TestSearchState:
- """Tests for SearchState dataclass defaults."""
-
- def test_default_good_candidates_empty(self):
- state = SearchState()
- assert state.good_candidates == []
-
- def test_default_total_evaluated_zero(self):
- state = SearchState()
- assert state.total_evaluated == 0
-
- def test_start_time_is_float(self):
- state = SearchState()
- assert isinstance(state.start_time, float)
-
- def test_remaining_constraints_empty(self):
- state = SearchState()
- assert state.remaining_constraints == []
-
- def test_candidates_lock_is_lock(self):
- state = SearchState()
- assert isinstance(state.candidates_lock, type(threading.Lock()))
-
- def test_stop_search_is_event(self):
- state = SearchState()
- assert isinstance(state.stop_search, threading.Event)
- assert not state.stop_search.is_set()
-
- def test_evaluation_futures_empty(self):
- state = SearchState()
- assert state.evaluation_futures == []
-
- def test_each_instance_gets_unique_lock(self):
- s1 = SearchState()
- s2 = SearchState()
- assert s1.candidates_lock is not s2.candidates_lock
-
- def test_each_instance_gets_unique_event(self):
- s1 = SearchState()
- s2 = SearchState()
- assert s1.stop_search is not s2.stop_search
-
-
-# ---------------------------------------------------------------------------
-# _build_combined_query
-# ---------------------------------------------------------------------------
-
-
-class TestBuildCombinedQuery:
- """Tests for query construction from constraints."""
-
- def test_single_word_no_quotes(self):
- strategy = _make_strategy()
- c = _make_constraint(value="Netflix")
- result = strategy._build_combined_query([c])
- assert result == "Netflix"
-
- def test_multi_word_gets_quoted(self):
- strategy = _make_strategy()
- c = _make_constraint(value="TV series")
- result = strategy._build_combined_query([c])
- assert result == '"TV series"'
-
- def test_already_quoted_not_double_quoted(self):
- strategy = _make_strategy()
- c = _make_constraint(value='"Breaking Bad"')
- result = strategy._build_combined_query([c])
- assert result == '"Breaking Bad"'
-
- def test_multiple_constraints_joined_with_space(self):
- strategy = _make_strategy()
- c1 = _make_constraint(value="HBO")
- c2 = _make_constraint(value="TV show")
- c3 = _make_constraint(value="2019")
- result = strategy._build_combined_query([c1, c2, c3])
- assert result == 'HBO "TV show" 2019'
-
- def test_empty_constraints_list(self):
- strategy = _make_strategy()
- result = strategy._build_combined_query([])
- assert result == ""
-
- def test_constraint_with_existing_quotes_preserved(self):
- strategy = _make_strategy()
- c = _make_constraint(value='aired on "HBO Max"')
- result = strategy._build_combined_query([c])
- # Contains a quote already, so it should NOT be additionally quoted
- assert result == 'aired on "HBO Max"'
-
-
-# ---------------------------------------------------------------------------
-# _classify_constraint_difficulty
-# ---------------------------------------------------------------------------
-
-
-class TestClassifyConstraintDifficulty:
- """Tests for constraint difficulty rating and sorting."""
-
- def test_event_type_gets_0_7(self):
- """EVENT type raises difficulty to 0.7."""
- strategy = _make_strategy()
- c = _make_constraint(
- value="complex emotional narrative", type_name="EVENT"
- )
- strategy.state = SearchState(remaining_constraints=[c])
- strategy._classify_constraint_difficulty()
- assert c.search_difficulty == 0.7
-
- def test_default_difficulty_is_0_5(self):
- strategy = _make_strategy()
- c = _make_constraint(value="something generic xyz")
- strategy.state = SearchState(remaining_constraints=[c])
- strategy._classify_constraint_difficulty()
- assert c.search_difficulty == 0.5
-
- def test_property_type_gets_0_5(self):
- """PROPERTY type gets default difficulty 0.5 (no special handling)."""
- strategy = _make_strategy()
- c = _make_constraint(value="netflix original")
- strategy.state = SearchState(remaining_constraints=[c])
- strategy._classify_constraint_difficulty()
- assert c.search_difficulty == 0.5
-
- def test_event_type_raises_difficulty(self):
- """EVENT constraint type raises difficulty to at least 0.7."""
- strategy = _make_strategy()
- c = _make_constraint(value="something simple", type_name="EVENT")
- strategy.state = SearchState(remaining_constraints=[c])
- strategy._classify_constraint_difficulty()
- assert c.search_difficulty >= 0.7
-
- def test_sorted_by_difficulty_descending(self):
- """Constraints are sorted hardest-first after classification."""
- strategy = _make_strategy()
- prop = _make_constraint(value="some property", type_name="PROPERTY")
- event = _make_constraint(value="some event", type_name="EVENT")
- strategy.state = SearchState(remaining_constraints=[prop, event])
- strategy._classify_constraint_difficulty()
- assert strategy.state.remaining_constraints[0] is event
- assert strategy.state.remaining_constraints[1] is prop
-
- def test_statistic_gets_default_0_5(self):
- """STATISTIC type has no special handling, gets default 0.5."""
- strategy = _make_strategy()
- c = _make_constraint(value="84.5x ratio", type_name="STATISTIC")
- strategy.state = SearchState(remaining_constraints=[c])
- strategy._classify_constraint_difficulty()
- assert c.search_difficulty == 0.5
-
- def test_location_gets_default_0_5(self):
- """LOCATION type has no special handling, gets default 0.5."""
- strategy = _make_strategy()
- c = _make_constraint(value="New York City", type_name="LOCATION")
- strategy.state = SearchState(remaining_constraints=[c])
- strategy._classify_constraint_difficulty()
- assert c.search_difficulty == 0.5
-
-
-# ---------------------------------------------------------------------------
-# _should_stop_search
-# ---------------------------------------------------------------------------
-
-
-class TestShouldStopSearch:
- """Tests for the 7 stopping criteria."""
-
- def _setup_strategy(self, **overrides):
- defaults = dict(
- max_candidates=10,
- target_candidates=5,
- min_good_candidates=3,
- exceptional_score=0.95,
- max_search_time=30.0,
- max_evaluations=30,
- quality_plateau_threshold=0.1,
- )
- defaults.update(overrides)
- strategy = _make_strategy(**defaults)
- strategy.state = SearchState(start_time=time.time())
- return strategy
-
- def test_returns_false_when_no_criteria_met(self):
- strategy = self._setup_strategy()
- assert strategy._should_stop_search() is False
-
- def test_criterion_1_stop_flag_set(self):
- """Respects the stop_search Event."""
- strategy = self._setup_strategy()
- strategy.state.stop_search.set()
- assert strategy._should_stop_search() is True
-
- def test_criterion_2_max_candidates_reached(self):
- """Stops when good_candidates >= max_candidates."""
- strategy = self._setup_strategy(max_candidates=2)
- strategy.state.good_candidates = [
- (_make_candidate("A"), 0.8),
- (_make_candidate("B"), 0.7),
- ]
- assert strategy._should_stop_search() is True
-
- def test_criterion_3_target_with_high_quality(self):
- """Stops when target_candidates reached with avg score >= 0.8."""
- strategy = self._setup_strategy(target_candidates=2)
- strategy.state.good_candidates = [
- (_make_candidate("A"), 0.85),
- (_make_candidate("B"), 0.90),
- ]
- assert strategy._should_stop_search() is True
-
- def test_criterion_3_target_with_low_quality_continues(self):
- """Does not stop when target reached but avg score < 0.8."""
- strategy = self._setup_strategy(target_candidates=2)
- strategy.state.good_candidates = [
- (_make_candidate("A"), 0.6),
- (_make_candidate("B"), 0.7),
- ]
- assert strategy._should_stop_search() is False
-
- def test_criterion_4_exceptional_candidate(self):
- """Stops when min_good met and one candidate >= exceptional_score."""
- strategy = self._setup_strategy(
- min_good_candidates=2, exceptional_score=0.95
- )
- strategy.state.good_candidates = [
- (_make_candidate("A"), 0.7),
- (_make_candidate("B"), 0.96),
- ]
- assert strategy._should_stop_search() is True
-
- def test_criterion_4_no_exceptional(self):
- """Does not stop when min_good met but no candidate >= exceptional_score,
- and target not yet reached with high quality."""
- strategy = self._setup_strategy(
- min_good_candidates=2,
- exceptional_score=0.95,
- target_candidates=10, # High target so criterion 3 doesn't trigger
- )
- strategy.state.good_candidates = [
- (_make_candidate("A"), 0.7),
- (_make_candidate("B"), 0.7),
- ]
- strategy.state.remaining_constraints = [
- _make_constraint()
- ] # Prevent criterion 7
- assert strategy._should_stop_search() is False
-
- def test_criterion_5_time_limit(self):
- """Stops when elapsed time exceeds max_search_time."""
- strategy = self._setup_strategy(max_search_time=0.001)
- strategy.state.start_time = time.time() - 1.0 # 1 second ago
- assert strategy._should_stop_search() is True
-
- def test_criterion_6_evaluation_limit(self):
- """Stops when total_evaluated >= max_evaluations."""
- strategy = self._setup_strategy(max_evaluations=5)
- strategy.state.total_evaluated = 5
- assert strategy._should_stop_search() is True
-
- def test_criterion_7_no_remaining_constraints_with_min_candidates(self):
- """Stops when no constraints remain and min candidates found."""
- strategy = self._setup_strategy(min_good_candidates=1)
- strategy.state.remaining_constraints = []
- strategy.state.good_candidates = [(_make_candidate("A"), 0.7)]
- assert strategy._should_stop_search() is True
-
- def test_criterion_7_no_constraints_but_no_candidates(self):
- """Does not stop when no constraints but also no candidates."""
- strategy = self._setup_strategy(min_good_candidates=1)
- strategy.state.remaining_constraints = []
- strategy.state.good_candidates = []
- assert strategy._should_stop_search() is False
-
- def test_criterion_8_quality_plateau(self):
- """Stops when last 5 scores are within plateau threshold."""
- strategy = self._setup_strategy(quality_plateau_threshold=0.1)
- strategy.state.good_candidates = [
- (_make_candidate(f"C{i}"), score)
- for i, score in enumerate([0.80, 0.81, 0.82, 0.83, 0.84])
- ]
- assert strategy._should_stop_search() is True
-
- def test_no_plateau_with_wide_score_range(self):
- """Does not trigger plateau when score range is wide."""
- strategy = self._setup_strategy(
- quality_plateau_threshold=0.1,
- target_candidates=20, # Prevent criterion 3
- max_candidates=20, # Prevent criterion 2
- )
- strategy.state.good_candidates = [
- (_make_candidate(f"C{i}"), score)
- for i, score in enumerate([0.50, 0.60, 0.70, 0.80, 0.90])
- ]
- strategy.state.remaining_constraints = [
- _make_constraint()
- ] # Prevent criterion 7
- assert strategy._should_stop_search() is False
-
- def test_plateau_not_checked_under_5_candidates(self):
- """Plateau detection requires at least 5 candidates."""
- strategy = self._setup_strategy(
- quality_plateau_threshold=0.1,
- target_candidates=20, # Prevent criterion 3
- max_candidates=20, # Prevent criterion 2
- )
- strategy.state.good_candidates = [
- (_make_candidate(f"C{i}"), 0.8) for i in range(4)
- ]
- strategy.state.remaining_constraints = [
- _make_constraint()
- ] # Prevent criterion 7
- assert strategy._should_stop_search() is False
-
-
-# ---------------------------------------------------------------------------
-# _is_candidate_evaluated
-# ---------------------------------------------------------------------------
-
-
-class TestIsCandidateEvaluated:
- """Tests for thread-safe duplicate candidate check."""
-
- def test_not_evaluated_when_empty(self):
- strategy = _make_strategy()
- strategy.state = SearchState()
- candidate = _make_candidate("NewCandidate")
- assert strategy._is_candidate_evaluated(candidate) is False
-
- def test_evaluated_when_in_good_candidates(self):
- strategy = _make_strategy()
- existing = _make_candidate("ExistingCandidate")
- strategy.state = SearchState(good_candidates=[(existing, 0.8)])
- check = _make_candidate("ExistingCandidate")
- assert strategy._is_candidate_evaluated(check) is True
-
- def test_different_name_not_evaluated(self):
- strategy = _make_strategy()
- existing = _make_candidate("CandidateA")
- strategy.state = SearchState(good_candidates=[(existing, 0.8)])
- check = _make_candidate("CandidateB")
- assert strategy._is_candidate_evaluated(check) is False
-
- def test_thread_safe_check(self):
- """Multiple threads can safely check without race conditions."""
- strategy = _make_strategy()
- existing = _make_candidate("SharedCandidate")
- strategy.state = SearchState(good_candidates=[(existing, 0.8)])
-
- results = []
-
- def check():
- candidate = _make_candidate("SharedCandidate")
- results.append(strategy._is_candidate_evaluated(candidate))
-
- threads = [threading.Thread(target=check) for _ in range(10)]
- for t in threads:
- t.start()
- for t in threads:
- t.join()
-
- assert all(r is True for r in results)
-
-
-# ---------------------------------------------------------------------------
-# Initialization defaults
-# ---------------------------------------------------------------------------
-
-
-class TestInitializationDefaults:
- """Tests for constructor parameter storage."""
-
- def test_default_max_workers(self):
- strategy = _make_strategy()
- # Default from __init__ signature is 10
- assert strategy.evaluation_executor._max_workers == 10
-
- def test_custom_parameters_stored(self):
- strategy = _make_strategy(
- min_good_candidates=5,
- target_candidates=8,
- max_candidates=15,
- min_score_threshold=0.7,
- exceptional_score=0.98,
- max_search_time=60.0,
- max_evaluations=50,
- )
- assert strategy.min_good_candidates == 5
- assert strategy.target_candidates == 8
- assert strategy.max_candidates == 15
- assert strategy.min_score_threshold == 0.7
- assert strategy.exceptional_score == 0.98
- assert strategy.max_search_time == 60.0
- assert strategy.max_evaluations == 50
-
- def test_state_initially_none(self):
- strategy = _make_strategy()
- assert strategy.state is None
diff --git a/tests/advanced_search_system/strategies/test_constrained_search_high_value.py b/tests/advanced_search_system/strategies/test_constrained_search_high_value.py
deleted file mode 100644
index e59ef2e115..0000000000
--- a/tests/advanced_search_system/strategies/test_constrained_search_high_value.py
+++ /dev/null
@@ -1,637 +0,0 @@
-"""
-High-value pure logic tests for ConstrainedSearchStrategy.
-
-Tests focus on:
-- _calculate_restrictiveness_score and _rank_constraints_by_restrictiveness
-- Formatting methods (_format_constraint_analysis, _format_stage_results, etc.)
-- Filtering/deduplication logic
-- _quick_evidence_check scoring
-- _validate_search_results
-- _group_similar_candidates
-
-All tests bypass __init__ to avoid LLM/network dependencies.
-"""
-
-from unittest.mock import patch
-
-from local_deep_research.advanced_search_system.candidates.base_candidate import (
- Candidate,
-)
-from local_deep_research.advanced_search_system.constraints.base_constraint import (
- Constraint,
- ConstraintType,
-)
-from local_deep_research.advanced_search_system.evidence.base_evidence import (
- Evidence,
- EvidenceType,
-)
-from local_deep_research.advanced_search_system.strategies.constrained_search_strategy import (
- ConstrainedSearchStrategy,
-)
-
-
-# ---------------------------------------------------------------------------
-# Helpers
-# ---------------------------------------------------------------------------
-
-
-def _make_strategy(**overrides):
- """Create a ConstrainedSearchStrategy with __init__ bypassed."""
- with patch.object(
- ConstrainedSearchStrategy, "__init__", lambda self, *a, **kw: None
- ):
- strat = ConstrainedSearchStrategy.__new__(ConstrainedSearchStrategy)
-
- # Defaults that the real __init__ would set
- defaults = dict(
- constraints=[],
- constraint_ranking=[],
- stage_candidates={},
- candidates=[],
- evidence_threshold=0.6,
- candidate_limit=100,
- search_history=[],
- )
- defaults.update(overrides)
- for key, val in defaults.items():
- setattr(strat, key, val)
- return strat
-
-
-def _make_constraint(
- id_="c1",
- ctype=ConstraintType.PROPERTY,
- value="test value",
- description="Test constraint",
- weight=0.5,
-):
- """Create a Constraint with convenient defaults."""
- return Constraint(
- id=id_, type=ctype, value=value, description=description, weight=weight
- )
-
-
-# ---------------------------------------------------------------------------
-# Tests: _calculate_restrictiveness_score
-# ---------------------------------------------------------------------------
-
-
-class TestCalculateRestrictivenessScore:
- """Tests for the _calculate_restrictiveness_score method."""
-
- def test_statistic_type_gets_10(self):
- """STATISTIC constraint type adds +10 to score."""
- strat = _make_strategy()
- c = _make_constraint(ctype=ConstraintType.STATISTIC, value="abc")
- assert strat._calculate_restrictiveness_score(c) == 10
-
- def test_event_type_gets_8(self):
- """EVENT constraint type adds +8 to score."""
- strat = _make_strategy()
- c = _make_constraint(ctype=ConstraintType.EVENT, value="abc")
- assert strat._calculate_restrictiveness_score(c) == 8
-
- def test_location_type_gets_6(self):
- """LOCATION constraint type adds +6 to score."""
- strat = _make_strategy()
- c = _make_constraint(ctype=ConstraintType.LOCATION, value="abc")
- assert strat._calculate_restrictiveness_score(c) == 6
-
- def test_property_type_gets_4(self):
- """PROPERTY constraint type adds +4 to score."""
- strat = _make_strategy()
- c = _make_constraint(ctype=ConstraintType.PROPERTY, value="abc")
- assert strat._calculate_restrictiveness_score(c) == 4
-
- def test_value_with_digits_adds_5(self):
- """Presence of digits in value adds +5."""
- strat = _make_strategy()
- c = _make_constraint(ctype=ConstraintType.PROPERTY, value="year 2020")
- # PROPERTY=4, digits=5 => 9
- assert strat._calculate_restrictiveness_score(c) == 9
-
- def test_long_value_adds_3(self):
- """Value with >3 words adds +3."""
- strat = _make_strategy()
- c = _make_constraint(
- ctype=ConstraintType.PROPERTY,
- value="a very long descriptive phrase",
- )
- # PROPERTY=4, >3 words=3 => 7
- assert strat._calculate_restrictiveness_score(c) == 7
-
- def test_specific_keyword_adds_2(self):
- """Values containing 'specific', 'exact', 'only', or 'must' add +2."""
- strat = _make_strategy()
- for keyword in ["specific", "exact", "only", "must"]:
- c = _make_constraint(
- ctype=ConstraintType.PROPERTY, value=f"{keyword} item"
- )
- score = strat._calculate_restrictiveness_score(c)
- # PROPERTY=4, keyword=2 => 6
- assert score == 6, f"Keyword '{keyword}' should add +2"
-
- def test_combined_bonuses_stack(self):
- """All specificity bonuses stack correctly."""
- strat = _make_strategy()
- # STATISTIC(10) + digits(5) + >3 words(3) + keyword(2) = 20
- c = _make_constraint(
- ctype=ConstraintType.STATISTIC,
- value="must be exactly 42 units long",
- )
- assert strat._calculate_restrictiveness_score(c) == 20
-
- def test_none_value_skips_specificity(self):
- """Constraint with value=None gets only type-based score."""
- strat = _make_strategy()
- c = _make_constraint(ctype=ConstraintType.EVENT, value=None)
- assert strat._calculate_restrictiveness_score(c) == 8
-
- def test_empty_string_value_skips_specificity(self):
- """Constraint with empty string value gets only type-based score."""
- strat = _make_strategy()
- c = _make_constraint(ctype=ConstraintType.LOCATION, value="")
- assert strat._calculate_restrictiveness_score(c) == 6
-
-
-# ---------------------------------------------------------------------------
-# Tests: _rank_constraints_by_restrictiveness
-# ---------------------------------------------------------------------------
-
-
-class TestRankConstraintsByRestrictiveness:
- """Tests for _rank_constraints_by_restrictiveness method."""
-
- def test_sorts_by_score_descending(self):
- """Constraints are sorted from highest to lowest score."""
- strat = _make_strategy()
- strat.constraints = [
- _make_constraint(
- id_="p", ctype=ConstraintType.PROPERTY, value="abc"
- ),
- _make_constraint(
- id_="s", ctype=ConstraintType.STATISTIC, value="123"
- ),
- _make_constraint(id_="e", ctype=ConstraintType.EVENT, value="abc"),
- ]
- ranked = strat._rank_constraints_by_restrictiveness()
- # STATISTIC(10)+digits(5)=15, EVENT=8, PROPERTY=4
- assert ranked[0].id == "s"
- assert ranked[1].id == "e"
- assert ranked[2].id == "p"
-
- def test_empty_constraints_returns_empty(self):
- """Empty constraints list returns empty ranked list."""
- strat = _make_strategy()
- strat.constraints = []
- assert strat._rank_constraints_by_restrictiveness() == []
-
- def test_single_constraint(self):
- """Single constraint is returned as-is."""
- strat = _make_strategy()
- c = _make_constraint(id_="only")
- strat.constraints = [c]
- ranked = strat._rank_constraints_by_restrictiveness()
- assert len(ranked) == 1
- assert ranked[0].id == "only"
-
- def test_preserves_all_constraints(self):
- """All constraints appear in ranked output."""
- strat = _make_strategy()
- strat.constraints = [
- _make_constraint(
- id_=str(i), ctype=ConstraintType.PROPERTY, value="x"
- )
- for i in range(5)
- ]
- ranked = strat._rank_constraints_by_restrictiveness()
- assert len(ranked) == 5
-
-
-# ---------------------------------------------------------------------------
-# Tests: Format methods
-# ---------------------------------------------------------------------------
-
-
-class TestFormatMethods:
- """Tests for formatting helper methods."""
-
- def test_format_constraint_analysis_includes_header(self):
- """_format_constraint_analysis includes query constraint header."""
- strat = _make_strategy()
- c = _make_constraint(description="Height over 100m")
- strat.constraints = [c]
- strat.constraint_ranking = [c]
- result = strat._format_constraint_analysis()
- assert "Query Constraint Analysis" in result
-
- def test_format_constraint_analysis_includes_description(self):
- """_format_constraint_analysis includes each constraint description."""
- strat = _make_strategy()
- c = _make_constraint(description="Height over 100m")
- strat.constraints = [c]
- strat.constraint_ranking = [c]
- result = strat._format_constraint_analysis()
- assert "Height over 100m" in result
-
- def test_format_constraint_analysis_includes_score(self):
- """_format_constraint_analysis shows restrictiveness score."""
- strat = _make_strategy()
- c = _make_constraint(ctype=ConstraintType.STATISTIC, value="42")
- strat.constraints = [c]
- strat.constraint_ranking = [c]
- result = strat._format_constraint_analysis()
- assert "15" in result # STATISTIC(10) + digits(5)
-
- def test_format_stage_results_with_candidates(self):
- """_format_stage_results shows stage number and candidates."""
- strat = _make_strategy()
- c = _make_constraint(description="Located in Colorado")
- candidates = [
- Candidate(name="Pike's Peak"),
- Candidate(name="Mt Elbert"),
- ]
- result = strat._format_stage_results(0, c, candidates)
- assert "Stage 1" in result
- assert "Located in Colorado" in result
- assert "Pike's Peak" in result
- assert "Mt Elbert" in result
-
- def test_format_stage_results_empty_candidates(self):
- """_format_stage_results handles empty candidate list."""
- strat = _make_strategy()
- c = _make_constraint()
- result = strat._format_stage_results(0, c, [])
- assert "No candidates found" in result
-
- def test_format_search_summary_includes_final_count(self):
- """_format_search_summary includes final candidate count."""
- strat = _make_strategy()
- c = _make_constraint()
- strat.constraint_ranking = [c]
- strat.stage_candidates = {0: [Candidate(name="A")]}
- strat.candidates = [Candidate(name="A")]
- result = strat._format_search_summary()
- assert "1 candidates selected" in result
-
- def test_format_debug_summary_includes_debug_header(self):
- """_format_debug_summary includes Debug Summary header."""
- strat = _make_strategy()
- c = _make_constraint()
- strat.constraints = [c]
- strat.constraint_ranking = [c]
- strat.stage_candidates = {}
- strat.candidates = []
- result = strat._format_debug_summary()
- assert "Debug Summary" in result
-
- def test_format_evidence_summary_no_candidates(self):
- """_format_evidence_summary works with zero candidates."""
- strat = _make_strategy()
- strat.constraints = [_make_constraint()]
- strat.candidates = []
- result = strat._format_evidence_summary()
- assert "Evidence Gathering Summary" in result
-
-
-# ---------------------------------------------------------------------------
-# Tests: _deduplicate_candidates
-# ---------------------------------------------------------------------------
-
-
-class TestDeduplicateCandidates:
- """Tests for candidate deduplication."""
-
- def test_removes_case_insensitive_duplicates(self):
- """Candidates with same name (case-insensitive) are deduplicated."""
- strat = _make_strategy()
- candidates = [
- Candidate(name="Alpha"),
- Candidate(name="alpha"),
- Candidate(name="ALPHA"),
- ]
- result = strat._deduplicate_candidates(candidates)
- assert len(result) == 1
- assert result[0].name == "Alpha" # first seen wins
-
- def test_keeps_distinct_candidates(self):
- """Distinct candidates are all kept."""
- strat = _make_strategy()
- candidates = [
- Candidate(name="Alpha"),
- Candidate(name="Beta"),
- Candidate(name="Gamma"),
- ]
- result = strat._deduplicate_candidates(candidates)
- assert len(result) == 3
-
- def test_empty_list(self):
- """Empty input returns empty output."""
- strat = _make_strategy()
- assert strat._deduplicate_candidates([]) == []
-
-
-# ---------------------------------------------------------------------------
-# Tests: _group_similar_candidates
-# ---------------------------------------------------------------------------
-
-
-class TestGroupSimilarCandidates:
- """Tests for candidate grouping logic."""
-
- def test_ai_model_group(self):
- """Candidates with AI model keywords go to 'AI Models' group."""
- strat = _make_strategy()
- candidates = [Candidate(name="GPT-4"), Candidate(name="Claude 3")]
- grouped = strat._group_similar_candidates(candidates)
- assert "AI Models" in grouped
- assert len(grouped["AI Models"]) == 2
-
- def test_numeric_items_group(self):
- """Candidates with digits go to 'Numeric Items' group."""
- strat = _make_strategy()
- candidates = [Candidate(name="Highway 66")]
- grouped = strat._group_similar_candidates(candidates)
- assert "Numeric Items" in grouped
-
- def test_default_grouping_uses_first_word(self):
- """Candidates without keyword matches use first-word grouping."""
- strat = _make_strategy()
- candidates = [Candidate(name="Evergreen Forest")]
- grouped = strat._group_similar_candidates(candidates)
- assert "Evergreen Items" in grouped
-
- def test_empty_candidates(self):
- """Empty candidate list returns empty dict."""
- strat = _make_strategy()
- assert strat._group_similar_candidates([]) == {}
-
-
-# ---------------------------------------------------------------------------
-# Tests: _validate_search_results
-# ---------------------------------------------------------------------------
-
-
-class TestValidateSearchResults:
- """Tests for search result validation."""
-
- def test_rejects_none_results(self):
- """None results are rejected."""
- strat = _make_strategy()
- c = _make_constraint()
- assert strat._validate_search_results(None, c) is False
-
- def test_rejects_empty_content(self):
- """Empty content string is rejected."""
- strat = _make_strategy()
- c = _make_constraint()
- results = {"current_knowledge": "", "search_results": []}
- assert strat._validate_search_results(results, c) is False
-
- def test_rejects_short_content(self):
- """Content under 50 chars is rejected."""
- strat = _make_strategy()
- c = _make_constraint()
- results = {"current_knowledge": "Too short", "search_results": []}
- assert strat._validate_search_results(results, c) is False
-
- def test_rejects_no_results_found_message(self):
- """Content containing 'No results found' is rejected."""
- strat = _make_strategy()
- c = _make_constraint()
- results = {
- "current_knowledge": "No results found for this query. " * 5,
- "search_results": [],
- }
- assert strat._validate_search_results(results, c) is False
-
- def test_accepts_valid_property_content(self):
- """Valid content matching property constraint terms is accepted."""
- strat = _make_strategy()
- c = _make_constraint(
- ctype=ConstraintType.PROPERTY,
- value="mountain hiking trail overview",
- )
- results = {
- "current_knowledge": (
- "This mountain hiking trail overview covers several popular "
- "destinations. The trail system includes many routes for "
- "experienced hikers and beginners alike."
- ),
- "search_results": [{"title": "Trails", "snippet": "hiking info"}],
- }
- assert strat._validate_search_results(results, c) is True
-
- def test_accepts_statistic_with_matching_terms(self):
- """STATISTIC constraint with matching terms in content is accepted."""
- strat = _make_strategy()
- c = _make_constraint(
- ctype=ConstraintType.STATISTIC,
- value="population density growth",
- )
- results = {
- "current_knowledge": (
- "The population of the region saw significant density "
- "increases and growth over the past decade due to urban "
- "expansion and migration patterns."
- ),
- "search_results": [{"title": "Stats", "snippet": "data"}],
- }
- assert strat._validate_search_results(results, c) is True
-
- def test_rejects_statistic_with_no_matching_terms(self):
- """STATISTIC constraint rejected when content has no matching terms."""
- strat = _make_strategy()
- c = _make_constraint(
- ctype=ConstraintType.STATISTIC,
- value="revenue quarterly earnings",
- )
- results = {
- "current_knowledge": (
- "The weather forecast for tomorrow shows sunny skies "
- "with temperatures reaching thirty degrees in most areas."
- ),
- "search_results": [{"title": "Weather", "snippet": "sun"}],
- }
- assert strat._validate_search_results(results, c) is False
-
- def test_accepts_statistic_non_tv_domain(self):
- """STATISTIC constraint works for non-TV domains (no TV coupling)."""
- strat = _make_strategy()
- c = _make_constraint(
- ctype=ConstraintType.STATISTIC,
- value="4000 meter elevation",
- )
- results = {
- "current_knowledge": (
- "The mountain peak reaches an elevation of over four "
- "thousand meter above sea level, making it one of the "
- "tallest in the range."
- ),
- "search_results": [{"title": "Peak", "snippet": "altitude"}],
- }
- assert strat._validate_search_results(results, c) is True
-
- def test_statistic_none_value_skips_term_check(self):
- """STATISTIC with None value skips term check, falls to quality."""
- strat = _make_strategy()
- c = _make_constraint(
- ctype=ConstraintType.STATISTIC,
- value=None,
- )
- results = {
- "current_knowledge": (
- "Sufficient content that passes the length check easily "
- "and does not contain error or no results messages."
- ),
- "search_results": [{"title": "Info", "snippet": "data"}],
- }
- assert strat._validate_search_results(results, c) is True
-
- def test_statistic_numeric_value_no_crash(self):
- """STATISTIC with numeric value does not crash."""
- strat = _make_strategy()
- c = _make_constraint(
- ctype=ConstraintType.STATISTIC,
- value=42,
- )
- results = {
- "current_knowledge": (
- "This content is long enough and contains the number 42 "
- "somewhere in the text for validation purposes."
- ),
- "search_results": [],
- }
- # str(42) = "42", len == 2, filtered by len > 2,
- # so constraint_terms is empty and validation passes.
- assert strat._validate_search_results(results, c) is True
-
- def test_none_value_non_statistic_no_crash(self):
- """PROPERTY with None value does not crash."""
- strat = _make_strategy()
- c = _make_constraint(
- ctype=ConstraintType.PROPERTY,
- value=None,
- )
- results = {
- "current_knowledge": (
- "Sufficient content that passes the length check easily "
- "and does not contain error or no results messages."
- ),
- "search_results": [{"title": "Info", "snippet": "data"}],
- }
- assert strat._validate_search_results(results, c) is True
-
- def test_short_numeric_value_passes_validation(self):
- """PROPERTY with short numeric value '42' passes (no terms > 2 chars)."""
- strat = _make_strategy()
- c = _make_constraint(
- ctype=ConstraintType.PROPERTY,
- value="42",
- )
- results = {
- "current_knowledge": (
- "This content is long enough to pass the minimum length "
- "check and has valid search results attached to it."
- ),
- "search_results": [{"title": "Info", "snippet": "data"}],
- }
- assert strat._validate_search_results(results, c) is True
-
-
-# ---------------------------------------------------------------------------
-# Tests: _quick_evidence_check scoring
-# ---------------------------------------------------------------------------
-
-
-class TestQuickEvidenceCheck:
- """Tests for the _quick_evidence_check scoring logic."""
-
- def test_returns_evidence_object(self):
- """Returns an Evidence instance."""
- strat = _make_strategy()
- candidate = Candidate(name="Test Entity")
- constraint = _make_constraint()
- results = {"current_knowledge": "Some content", "search_results": []}
- evidence = strat._quick_evidence_check(results, candidate, constraint)
- assert isinstance(evidence, Evidence)
-
- def test_base_confidence_when_nothing_matches(self):
- """When no components match, confidence falls back to Evidence type base (INFERENCE=0.5).
-
- The _quick_evidence_check computes 0.0 but Evidence.__post_init__
- replaces 0.0 with the EvidenceType.INFERENCE base_confidence of 0.5.
- """
- strat = _make_strategy()
- candidate = Candidate(name="Nonexistent Entity")
- constraint = _make_constraint(value="irrelevant zzzz")
- results = {
- "current_knowledge": "Completely unrelated topic about weather patterns.",
- "search_results": [],
- }
- evidence = strat._quick_evidence_check(results, candidate, constraint)
- # All scoring components are zero
- assert evidence.metadata["name_presence"] == 0.0
- assert evidence.metadata["constraint_presence"] == 0.0
- assert evidence.metadata["co_occurrence"] == 0.0
- assert evidence.metadata["context_quality"] == 0.0
- # But Evidence post_init sets INFERENCE base_confidence
- assert evidence.confidence == EvidenceType.INFERENCE.base_confidence
-
- def test_higher_confidence_with_co_occurrence(self):
- """Confidence is higher when both candidate and constraint value co-occur."""
- strat = _make_strategy()
- candidate = Candidate(name="Mount Elbert")
- constraint = _make_constraint(value="14000 feet")
- # Both terms present and close together
- content = (
- "Mount Elbert rises to 14000 feet above sea level in Colorado."
- )
- results = {"current_knowledge": content, "search_results": []}
- evidence = strat._quick_evidence_check(results, candidate, constraint)
- assert evidence.confidence > 0.5
-
- def test_statistic_type_multiplier(self):
- """STATISTIC constraint type applies 1.1x multiplier to confidence."""
- strat = _make_strategy()
- candidate = Candidate(name="Entity A")
- content = (
- "Entity A has exactly the value abc as expected in this context."
- )
-
- c_stat = _make_constraint(ctype=ConstraintType.STATISTIC, value="abc")
- c_prop = _make_constraint(ctype=ConstraintType.PROPERTY, value="abc")
-
- results = {"current_knowledge": content, "search_results": []}
- ev_stat = strat._quick_evidence_check(results, candidate, c_stat)
- ev_prop = strat._quick_evidence_check(results, candidate, c_prop)
- # STATISTIC multiplier (1.1) > PROPERTY multiplier (0.95)
- assert ev_stat.confidence > ev_prop.confidence
-
- def test_confidence_capped_at_one(self):
- """Confidence never exceeds 1.0."""
- strat = _make_strategy()
- candidate = Candidate(name="x")
- constraint = _make_constraint(ctype=ConstraintType.STATISTIC, value="x")
- # Lots of repetition to push score up
- content = ("x " * 500).strip()
- results = {
- "current_knowledge": content,
- "search_results": [
- {"title": "x", "snippet": "x"} for _ in range(20)
- ],
- }
- evidence = strat._quick_evidence_check(results, candidate, constraint)
- assert evidence.confidence <= 1.0
-
- def test_none_constraint_value_no_crash(self):
- """None constraint value does not crash _quick_evidence_check."""
- strat = _make_strategy()
- candidate = Candidate(name="Test Entity")
- constraint = _make_constraint(value=None)
- results = {
- "current_knowledge": "Some content about various topics.",
- "search_results": [],
- }
- evidence = strat._quick_evidence_check(results, candidate, constraint)
- assert isinstance(evidence, Evidence)
diff --git a/tests/advanced_search_system/strategies/test_constrained_search_pure_logic.py b/tests/advanced_search_system/strategies/test_constrained_search_pure_logic.py
deleted file mode 100644
index 09c9b25538..0000000000
--- a/tests/advanced_search_system/strategies/test_constrained_search_pure_logic.py
+++ /dev/null
@@ -1,283 +0,0 @@
-"""
-Pure-logic tests for ConstrainedSearchStrategy.
-
-Tests restrictiveness scoring, constraint ranking, candidate deduplication,
-and query generation — no LLM or search calls.
-"""
-
-from unittest.mock import Mock
-
-from local_deep_research.advanced_search_system.candidates.base_candidate import (
- Candidate,
-)
-from local_deep_research.advanced_search_system.constraints.base_constraint import (
- Constraint,
- ConstraintType,
-)
-from local_deep_research.advanced_search_system.strategies.constrained_search_strategy import (
- ConstrainedSearchStrategy,
-)
-
-
-def _constraint(id, ctype=ConstraintType.PROPERTY, value="v", weight=1.0):
- return Constraint(
- id=id, type=ctype, description=f"desc {id}", value=value, weight=weight
- )
-
-
-def _make_strategy(constraints=None):
- """Build a minimal Mock with the attributes read by pure-logic methods."""
- s = Mock(spec=[])
- s.constraints = constraints or []
- return s
-
-
-# ---------------------------------------------------------------------------
-# _calculate_restrictiveness_score
-# ---------------------------------------------------------------------------
-
-
-class TestCalculateRestrictivenessScore:
- """Verify type-based and value-based scoring components."""
-
- def _score(self, ctype=ConstraintType.PROPERTY, value="v"):
- c = _constraint("c1", ctype, value)
- return ConstrainedSearchStrategy._calculate_restrictiveness_score(
- Mock(), c
- )
-
- def test_statistic_highest_type_score(self):
- """STATISTIC type gets 10 points."""
- assert self._score(ConstraintType.STATISTIC) >= 10
-
- def test_event_type_score(self):
- """EVENT type gets 8 points."""
- assert self._score(ConstraintType.EVENT, "something") == 8
-
- def test_location_type_score(self):
- """LOCATION type gets 6 points."""
- assert self._score(ConstraintType.LOCATION, "something") == 6
-
- def test_property_type_score(self):
- """PROPERTY type gets 4 points."""
- assert self._score(ConstraintType.PROPERTY, "something") == 4
-
- def test_digits_bonus(self):
- """Values containing digits get +5."""
- base = self._score(ConstraintType.PROPERTY, "abc")
- with_digit = self._score(ConstraintType.PROPERTY, "abc 42")
- assert with_digit - base == 5
-
- def test_long_value_bonus(self):
- """Values with > 3 words get +3."""
- short = self._score(ConstraintType.PROPERTY, "one two three")
- long = self._score(ConstraintType.PROPERTY, "one two three four")
- assert long - short == 3
-
- def test_specificity_keywords_bonus(self):
- """Values with 'specific', 'exact', 'only', or 'must' get +2."""
- base = self._score(ConstraintType.PROPERTY, "something")
- with_kw = self._score(ConstraintType.PROPERTY, "exact something")
- assert with_kw - base == 2
-
- def test_combined_bonuses(self):
- """Digits + long value + keyword = +10 total bonus."""
- # PROPERTY(4) + digits(5) + long(3) + keyword(2) = 14
- score = self._score(
- ConstraintType.PROPERTY,
- "must have exactly 100 specific items",
- )
- assert score == 14
-
- def test_empty_value(self):
- """Empty string value adds no bonus (falsy guard)."""
- score = self._score(ConstraintType.PROPERTY, "")
- assert score == 4 # Type score only
-
-
-# ---------------------------------------------------------------------------
-# _rank_constraints_by_restrictiveness
-# ---------------------------------------------------------------------------
-
-
-class TestRankConstraintsByRestrictiveness:
- """Verify that constraints are sorted most-restrictive-first."""
-
- def test_type_ordering(self):
- """STATISTIC > EVENT > LOCATION > PROPERTY."""
- s = _make_strategy(
- constraints=[
- _constraint("prop", ConstraintType.PROPERTY, "alpha"),
- _constraint("stat", ConstraintType.STATISTIC, "alpha"),
- _constraint("evt", ConstraintType.EVENT, "alpha"),
- _constraint("loc", ConstraintType.LOCATION, "alpha"),
- ]
- )
- ranked = ConstrainedSearchStrategy._rank_constraints_by_restrictiveness(
- s
- )
- ids = [c.id for c in ranked]
- assert ids == ["stat", "evt", "loc", "prop"]
-
- def test_bonus_can_reorder(self):
- """A PROPERTY with many bonuses can outrank a plain EVENT."""
- s = _make_strategy(
- constraints=[
- _constraint("evt", ConstraintType.EVENT, "plain"), # 8
- _constraint(
- "prop",
- ConstraintType.PROPERTY,
- "must have exact 500 specific items", # 4+5+3+2 = 14
- ),
- ]
- )
- ranked = ConstrainedSearchStrategy._rank_constraints_by_restrictiveness(
- s
- )
- assert ranked[0].id == "prop"
-
- def test_empty_constraints(self):
- """Empty list returns empty."""
- s = _make_strategy(constraints=[])
- assert (
- ConstrainedSearchStrategy._rank_constraints_by_restrictiveness(s)
- == []
- )
-
-
-# ---------------------------------------------------------------------------
-# _deduplicate_candidates
-# ---------------------------------------------------------------------------
-
-
-class TestDeduplicateCandidates:
- """Verify case-insensitive, strip-based deduplication."""
-
- def _dedup(self, names):
- candidates = [Candidate(name=n) for n in names]
- return ConstrainedSearchStrategy._deduplicate_candidates(
- Mock(), candidates
- )
-
- def test_no_duplicates(self):
- """Distinct names all kept."""
- result = self._dedup(["Alice", "Bob"])
- assert len(result) == 2
-
- def test_case_insensitive(self):
- """'alice' and 'Alice' are duplicates."""
- result = self._dedup(["Alice", "alice"])
- assert len(result) == 1
-
- def test_strips_whitespace(self):
- """Leading/trailing whitespace is ignored."""
- result = self._dedup(["Alice", " Alice "])
- assert len(result) == 1
-
- def test_preserves_first(self):
- """First occurrence is kept."""
- result = self._dedup(["Alice", "ALICE"])
- assert result[0].name == "Alice"
-
- def test_empty_list(self):
- """Empty input returns empty."""
- assert self._dedup([]) == []
-
-
-# ---------------------------------------------------------------------------
-# _generate_additional_queries
-# ---------------------------------------------------------------------------
-
-
-class TestGenerateAdditionalQueries:
- """Verify type-branched query template generation."""
-
- def _call(self, ctype, value="test data"):
- c = _constraint("c1", ctype, value)
- return ConstrainedSearchStrategy._generate_additional_queries(Mock(), c)
-
- def test_always_has_reference_queries(self):
- """All types get reference/authoritative/official queries."""
- result = self._call(ConstraintType.PROPERTY)
- assert any("reference" in q for q in result)
- assert any("authoritative" in q for q in result)
- assert any("official" in q for q in result)
-
- def test_statistic_gets_dataset_queries(self):
- """STATISTIC type gets spreadsheet/dataset/statistical analysis."""
- result = self._call(ConstraintType.STATISTIC)
- assert any("spreadsheet" in q or "dataset" in q for q in result)
-
- def test_property_gets_characterized_queries(self):
- """PROPERTY type gets 'characterized by' etc."""
- result = self._call(ConstraintType.PROPERTY)
- assert any("characterized by" in q for q in result)
-
- def test_other_gets_generic(self):
- """Other types get exhaustive/thorough/detailed."""
- result = self._call(ConstraintType.LOCATION)
- assert any("exhaustive" in q or "thorough" in q for q in result)
-
- def test_value_in_queries(self):
- """All queries contain the constraint value."""
- result = self._call(ConstraintType.PROPERTY, "blue eyes")
- assert all("blue eyes" in q for q in result)
-
-
-# ---------------------------------------------------------------------------
-# _generate_constraint_specific_queries
-# ---------------------------------------------------------------------------
-
-
-class TestGenerateConstraintSpecificQueries:
- """Verify type-specific query expansion with context from other constraints."""
-
- def _call(self, ctype, value="test data", other_constraints=None):
- c = _constraint("c1", ctype, value)
- s = _make_strategy(constraints=[c] + (other_constraints or []))
- return ConstrainedSearchStrategy._generate_constraint_specific_queries(
- s, c
- )
-
- def test_statistic_queries(self):
- """STATISTIC produces list/complete/database style queries."""
- result = self._call(ConstraintType.STATISTIC)
- assert any("database" in q for q in result)
- assert any("statistics" in q for q in result)
-
- def test_event_queries(self):
- """EVENT produces during/timeline style queries."""
- result = self._call(ConstraintType.EVENT)
- assert any("timeline" in q for q in result)
-
- def test_property_queries(self):
- """PROPERTY produces with/having/characterized by style queries."""
- result = self._call(ConstraintType.PROPERTY)
- assert any("characterized by" in q for q in result)
-
- def test_generic_queries(self):
- """Other types get generic list/examples queries."""
- result = self._call(ConstraintType.TEMPORAL)
- assert any("list" in q for q in result)
-
- def test_includes_description(self):
- """Constraint description is included as a query."""
- c = Constraint(
- id="c1",
- type=ConstraintType.PROPERTY,
- description="has blue eyes",
- value="blue eyes",
- )
- s = _make_strategy(constraints=[c])
- result = (
- ConstrainedSearchStrategy._generate_constraint_specific_queries(
- s, c
- )
- )
- assert "has blue eyes" in result
-
- def test_context_from_other_constraints(self):
- """Context from other constraints is appended in combined queries."""
- other = _constraint("c2", ConstraintType.PROPERTY, "red hair")
- result = self._call(ConstraintType.PROPERTY, "blue eyes", [other])
- assert any("red hair" in q for q in result)
diff --git a/tests/advanced_search_system/strategies/test_constrained_search_strategy.py b/tests/advanced_search_system/strategies/test_constrained_search_strategy.py
deleted file mode 100644
index acf7b9aeb2..0000000000
--- a/tests/advanced_search_system/strategies/test_constrained_search_strategy.py
+++ /dev/null
@@ -1,926 +0,0 @@
-"""
-Tests for ConstrainedSearchStrategy.
-
-Tests cover:
-- Initialization and inheritance
-- Constraint ranking by restrictiveness
-- Progressive constraint search
-- Candidate filtering
-- Evidence gathering
-- Error handling
-"""
-
-from unittest.mock import Mock, patch
-
-
-class TestConstrainedSearchStrategyInit:
- """Tests for ConstrainedSearchStrategy initialization."""
-
- def test_init_with_required_params(self):
- """Initialize with required parameters."""
- from local_deep_research.advanced_search_system.strategies.constrained_search_strategy import (
- ConstrainedSearchStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = ConstrainedSearchStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- assert strategy.model is mock_model
- assert strategy.search is mock_search
- assert strategy.use_direct_search is True
-
- def test_init_with_custom_params(self):
- """Initialize with custom parameters."""
- from local_deep_research.advanced_search_system.strategies.constrained_search_strategy import (
- ConstrainedSearchStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = ConstrainedSearchStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- max_iterations=15,
- candidate_limit=50,
- min_candidates_per_stage=10,
- )
-
- assert strategy.max_iterations == 15
- assert strategy.candidate_limit == 50
- assert strategy.min_candidates_per_stage == 10
-
- def test_init_inherits_from_evidence_based(self):
- """Initialize inherits from EvidenceBasedStrategy."""
- from local_deep_research.advanced_search_system.strategies.constrained_search_strategy import (
- ConstrainedSearchStrategy,
- )
- from local_deep_research.advanced_search_system.strategies.evidence_based_strategy import (
- EvidenceBasedStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = ConstrainedSearchStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- assert isinstance(strategy, EvidenceBasedStrategy)
-
- def test_init_state_tracking(self):
- """Initialize state tracking attributes."""
- from local_deep_research.advanced_search_system.strategies.constrained_search_strategy import (
- ConstrainedSearchStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = ConstrainedSearchStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- assert strategy.constraint_ranking == []
- assert strategy.stage_candidates == {}
-
-
-class TestConstraintRanking:
- """Tests for constraint ranking methods."""
-
- def test_rank_constraints_by_restrictiveness(self):
- """Rank constraints by restrictiveness score."""
- from local_deep_research.advanced_search_system.strategies.constrained_search_strategy import (
- ConstrainedSearchStrategy,
- )
- from local_deep_research.advanced_search_system.constraints.base_constraint import (
- Constraint,
- ConstraintType,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = ConstrainedSearchStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- # Create constraints with different types
- constraints = [
- Constraint(
- id="1",
- type=ConstraintType.PROPERTY,
- value="property value",
- description="Property",
- weight=0.5,
- ),
- Constraint(
- id="2",
- type=ConstraintType.STATISTIC,
- value="123 specific number",
- description="Statistic",
- weight=0.8,
- ),
- Constraint(
- id="3",
- type=ConstraintType.EVENT,
- value="event 2020",
- description="Event",
- weight=0.7,
- ),
- ]
- strategy.constraints = constraints
-
- ranked = strategy._rank_constraints_by_restrictiveness()
-
- # Statistics should be ranked higher
- assert len(ranked) == 3
- assert ranked[0].type == ConstraintType.STATISTIC
-
- def test_calculate_restrictiveness_score_statistic(self):
- """Calculate restrictiveness score for statistic constraint."""
- from local_deep_research.advanced_search_system.strategies.constrained_search_strategy import (
- ConstrainedSearchStrategy,
- )
- from local_deep_research.advanced_search_system.constraints.base_constraint import (
- Constraint,
- ConstraintType,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = ConstrainedSearchStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- constraint = Constraint(
- id="1",
- type=ConstraintType.STATISTIC,
- value="123",
- description="Test statistic",
- weight=0.8,
- )
-
- score = strategy._calculate_restrictiveness_score(constraint)
-
- # Statistic type gives +10, digits give +5
- assert score >= 15
-
- def test_calculate_restrictiveness_score_property(self):
- """Calculate restrictiveness score for property constraint."""
- from local_deep_research.advanced_search_system.strategies.constrained_search_strategy import (
- ConstrainedSearchStrategy,
- )
- from local_deep_research.advanced_search_system.constraints.base_constraint import (
- Constraint,
- ConstraintType,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = ConstrainedSearchStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- constraint = Constraint(
- id="1",
- type=ConstraintType.PROPERTY,
- value="simple",
- description="Test property",
- weight=0.5,
- )
-
- score = strategy._calculate_restrictiveness_score(constraint)
-
- # Property type gives +4
- assert score >= 4
-
-
-class TestProgressiveSearch:
- """Tests for progressive constraint search methods."""
-
- def test_progressive_constraint_search(self):
- """Progressive constraint search processes stages."""
- from local_deep_research.advanced_search_system.strategies.constrained_search_strategy import (
- ConstrainedSearchStrategy,
- )
- from local_deep_research.advanced_search_system.constraints.base_constraint import (
- Constraint,
- ConstraintType,
- )
-
- mock_search = Mock()
- mock_search.run.return_value = []
- mock_model = Mock()
- mock_model.invoke.return_value = Mock(content="CANDIDATE_1: Test")
-
- strategy = ConstrainedSearchStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- constraint = Constraint(
- id="1",
- type=ConstraintType.PROPERTY,
- value="test",
- description="Test constraint",
- weight=0.5,
- )
- strategy.constraint_ranking = [constraint]
- strategy.findings = [] # Initialize findings list
-
- strategy._progressive_constraint_search()
-
- assert len(strategy.stage_candidates) >= 0
-
- def test_generate_constraint_specific_queries(self):
- """Generate constraint-specific queries."""
- from local_deep_research.advanced_search_system.strategies.constrained_search_strategy import (
- ConstrainedSearchStrategy,
- )
- from local_deep_research.advanced_search_system.constraints.base_constraint import (
- Constraint,
- ConstraintType,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = ConstrainedSearchStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- constraint = Constraint(
- id="1",
- type=ConstraintType.STATISTIC,
- value="100 meters",
- description="Height constraint",
- weight=0.8,
- )
- strategy.constraints = [constraint]
-
- queries = strategy._generate_constraint_specific_queries(constraint)
-
- assert isinstance(queries, list)
- assert len(queries) > 0
- # Should contain common patterns for statistics
- assert any("100 meters" in q for q in queries)
-
- def test_generate_additional_queries(self):
- """Generate additional diverse queries."""
- from local_deep_research.advanced_search_system.strategies.constrained_search_strategy import (
- ConstrainedSearchStrategy,
- )
- from local_deep_research.advanced_search_system.constraints.base_constraint import (
- Constraint,
- ConstraintType,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = ConstrainedSearchStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- constraint = Constraint(
- id="1",
- type=ConstraintType.STATISTIC,
- value="test value",
- description="Test",
- weight=0.5,
- )
-
- queries = strategy._generate_additional_queries(constraint)
-
- assert isinstance(queries, list)
- # Should include reference source queries
- assert any(
- "reference" in q.lower() or "authoritative" in q.lower()
- for q in queries
- )
-
-
-class TestCandidateExtraction:
- """Tests for candidate extraction methods."""
-
- def test_extract_relevant_candidates(self):
- """Extract relevant candidates from search results."""
- from local_deep_research.advanced_search_system.strategies.constrained_search_strategy import (
- ConstrainedSearchStrategy,
- )
- from local_deep_research.advanced_search_system.constraints.base_constraint import (
- Constraint,
- ConstraintType,
- )
-
- mock_search = Mock()
- mock_model = Mock()
- mock_model.invoke.return_value = Mock(
- content="Candidate A\nCandidate B\nCandidate C"
- )
-
- strategy = ConstrainedSearchStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- constraint = Constraint(
- id="1",
- type=ConstraintType.PROPERTY,
- value="test",
- description="Test constraint",
- weight=0.5,
- )
-
- results = {"current_knowledge": "Information about candidates"}
-
- candidates = strategy._extract_relevant_candidates(results, constraint)
-
- assert isinstance(candidates, list)
-
- def test_extract_relevant_candidates_empty_content(self):
- """Extract candidates returns empty list for empty content."""
- from local_deep_research.advanced_search_system.strategies.constrained_search_strategy import (
- ConstrainedSearchStrategy,
- )
- from local_deep_research.advanced_search_system.constraints.base_constraint import (
- Constraint,
- ConstraintType,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = ConstrainedSearchStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- constraint = Constraint(
- id="1",
- type=ConstraintType.PROPERTY,
- value="test",
- description="Test constraint",
- weight=0.5,
- )
-
- results = {"current_knowledge": ""}
-
- candidates = strategy._extract_relevant_candidates(results, constraint)
-
- assert candidates == []
-
- def test_deduplicate_candidates(self):
- """Deduplicate candidates by name."""
- from local_deep_research.advanced_search_system.strategies.constrained_search_strategy import (
- ConstrainedSearchStrategy,
- )
- from local_deep_research.advanced_search_system.candidates.base_candidate import (
- Candidate,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = ConstrainedSearchStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- candidates = [
- Candidate(name="Test A"),
- Candidate(name="Test B"),
- Candidate(name="test a"), # Duplicate with different case
- Candidate(name="Test C"),
- ]
-
- unique = strategy._deduplicate_candidates(candidates)
-
- # Should have 3 unique candidates
- assert len(unique) == 3
-
-
-class TestCandidateFiltering:
- """Tests for candidate filtering methods."""
-
- def test_filter_candidates_with_constraint(self):
- """Filter candidates with constraint check."""
- from local_deep_research.advanced_search_system.strategies.constrained_search_strategy import (
- ConstrainedSearchStrategy,
- )
- from local_deep_research.advanced_search_system.candidates.base_candidate import (
- Candidate,
- )
- from local_deep_research.advanced_search_system.constraints.base_constraint import (
- Constraint,
- ConstraintType,
- )
-
- mock_search = Mock()
- mock_search.run.return_value = [
- {"snippet": "Test candidate matches constraint"}
- ]
- mock_model = Mock()
-
- strategy = ConstrainedSearchStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- candidates = [
- Candidate(name="Candidate A"),
- Candidate(name="Candidate B"),
- ]
-
- constraint = Constraint(
- id="1",
- type=ConstraintType.PROPERTY,
- value="test property",
- description="Test constraint",
- weight=0.5,
- )
-
- # Mock quick evidence check
- with patch.object(
- strategy,
- "_quick_evidence_check",
- return_value=Mock(confidence=0.8),
- ):
- filtered = strategy._filter_candidates_with_constraint(
- candidates, constraint
- )
-
- assert isinstance(filtered, list)
-
- def test_quick_evidence_check(self):
- """Quick evidence check calculates confidence."""
- from local_deep_research.advanced_search_system.strategies.constrained_search_strategy import (
- ConstrainedSearchStrategy,
- )
- from local_deep_research.advanced_search_system.candidates.base_candidate import (
- Candidate,
- )
- from local_deep_research.advanced_search_system.constraints.base_constraint import (
- Constraint,
- ConstraintType,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = ConstrainedSearchStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- candidate = Candidate(name="Test Entity")
- constraint = Constraint(
- id="1",
- type=ConstraintType.PROPERTY,
- value="has feature",
- description="Feature constraint",
- weight=0.5,
- )
-
- results = {
- "current_knowledge": "Test Entity has feature and is well known.",
- "search_results": [],
- }
-
- evidence = strategy._quick_evidence_check(
- results, candidate, constraint
- )
-
- assert hasattr(evidence, "confidence")
- assert 0 <= evidence.confidence <= 1
-
-
-class TestEvidenceGathering:
- """Tests for evidence gathering methods."""
-
- def test_focused_evidence_gathering(self):
- """Focused evidence gathering verifies candidates."""
- from local_deep_research.advanced_search_system.strategies.constrained_search_strategy import (
- ConstrainedSearchStrategy,
- )
- from local_deep_research.advanced_search_system.candidates.base_candidate import (
- Candidate,
- )
- from local_deep_research.advanced_search_system.constraints.base_constraint import (
- Constraint,
- ConstraintType,
- )
-
- mock_search = Mock()
- mock_search.run.return_value = []
- mock_model = Mock()
-
- strategy = ConstrainedSearchStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- candidate = Candidate(name="Test")
- strategy.candidates = [candidate]
-
- constraint = Constraint(
- id="1",
- type=ConstraintType.PROPERTY,
- value="test",
- description="Test",
- weight=0.5,
- )
- strategy.constraints = [constraint]
-
- # Mock evidence evaluator
- with patch.object(
- strategy.evidence_evaluator,
- "extract_evidence",
- return_value=Mock(confidence=0.8, type=Mock(value="inference")),
- ):
- strategy._focused_evidence_gathering()
-
- # Candidates should be scored and sorted
- assert len(strategy.candidates) > 0
-
-
-class TestResultValidation:
- """Tests for search result validation."""
-
- def test_validate_search_results_valid(self):
- """Validate search results accepts valid content."""
- from local_deep_research.advanced_search_system.strategies.constrained_search_strategy import (
- ConstrainedSearchStrategy,
- )
- from local_deep_research.advanced_search_system.constraints.base_constraint import (
- Constraint,
- ConstraintType,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = ConstrainedSearchStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- constraint = Constraint(
- id="1",
- type=ConstraintType.PROPERTY,
- value="test value",
- description="Test constraint",
- weight=0.5,
- )
-
- results = {
- "current_knowledge": "This is a valid test value content with enough information.",
- "search_results": [{"title": "Test", "snippet": "Content"}],
- }
-
- is_valid = strategy._validate_search_results(results, constraint)
-
- assert is_valid is True
-
- def test_validate_search_results_empty(self):
- """Validate search results rejects empty content."""
- from local_deep_research.advanced_search_system.strategies.constrained_search_strategy import (
- ConstrainedSearchStrategy,
- )
- from local_deep_research.advanced_search_system.constraints.base_constraint import (
- Constraint,
- ConstraintType,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = ConstrainedSearchStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- constraint = Constraint(
- id="1",
- type=ConstraintType.PROPERTY,
- value="test",
- description="Test",
- weight=0.5,
- )
-
- results = {
- "current_knowledge": "",
- "search_results": [],
- }
-
- is_valid = strategy._validate_search_results(results, constraint)
-
- assert is_valid is False
-
- def test_validate_search_results_no_results(self):
- """Validate search results rejects no results message."""
- from local_deep_research.advanced_search_system.strategies.constrained_search_strategy import (
- ConstrainedSearchStrategy,
- )
- from local_deep_research.advanced_search_system.constraints.base_constraint import (
- Constraint,
- ConstraintType,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = ConstrainedSearchStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- constraint = Constraint(
- id="1",
- type=ConstraintType.PROPERTY,
- value="test",
- description="Test",
- weight=0.5,
- )
-
- results = {
- "current_knowledge": "No results found for this query.",
- "search_results": [],
- }
-
- is_valid = strategy._validate_search_results(results, constraint)
-
- assert is_valid is False
-
-
-class TestFormattingMethods:
- """Tests for formatting helper methods."""
-
- def test_format_constraint_analysis(self):
- """Format constraint analysis output."""
- from local_deep_research.advanced_search_system.strategies.constrained_search_strategy import (
- ConstrainedSearchStrategy,
- )
- from local_deep_research.advanced_search_system.constraints.base_constraint import (
- Constraint,
- ConstraintType,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = ConstrainedSearchStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- constraint = Constraint(
- id="1",
- type=ConstraintType.PROPERTY,
- value="test",
- description="Test constraint",
- weight=0.5,
- )
- strategy.constraints = [constraint]
- strategy.constraint_ranking = [constraint]
-
- analysis = strategy._format_constraint_analysis()
-
- assert "Constraint" in analysis
- assert "Test constraint" in analysis
-
- def test_format_stage_results(self):
- """Format stage results output."""
- from local_deep_research.advanced_search_system.strategies.constrained_search_strategy import (
- ConstrainedSearchStrategy,
- )
- from local_deep_research.advanced_search_system.candidates.base_candidate import (
- Candidate,
- )
- from local_deep_research.advanced_search_system.constraints.base_constraint import (
- Constraint,
- ConstraintType,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = ConstrainedSearchStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- constraint = Constraint(
- id="1",
- type=ConstraintType.PROPERTY,
- value="test",
- description="Test constraint",
- weight=0.5,
- )
-
- candidates = [
- Candidate(name="Test A"),
- Candidate(name="Test B"),
- ]
-
- result = strategy._format_stage_results(0, constraint, candidates)
-
- assert "Stage 1" in result
- assert "Test A" in result or "Test B" in result
-
- def test_format_search_summary(self):
- """Format search summary output."""
- from local_deep_research.advanced_search_system.strategies.constrained_search_strategy import (
- ConstrainedSearchStrategy,
- )
- from local_deep_research.advanced_search_system.candidates.base_candidate import (
- Candidate,
- )
- from local_deep_research.advanced_search_system.constraints.base_constraint import (
- Constraint,
- ConstraintType,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = ConstrainedSearchStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- constraint = Constraint(
- id="1",
- type=ConstraintType.PROPERTY,
- value="test",
- description="Test constraint",
- weight=0.5,
- )
- strategy.constraint_ranking = [constraint]
- strategy.stage_candidates = {0: [Candidate(name="Test")]}
- strategy.candidates = [Candidate(name="Test")]
-
- summary = strategy._format_search_summary()
-
- assert "Summary" in summary
-
- def test_format_debug_summary(self):
- """Format debug summary output."""
- from local_deep_research.advanced_search_system.strategies.constrained_search_strategy import (
- ConstrainedSearchStrategy,
- )
- from local_deep_research.advanced_search_system.candidates.base_candidate import (
- Candidate,
- )
- from local_deep_research.advanced_search_system.constraints.base_constraint import (
- Constraint,
- ConstraintType,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = ConstrainedSearchStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- constraint = Constraint(
- id="1",
- type=ConstraintType.PROPERTY,
- value="test",
- description="Test constraint",
- weight=0.5,
- )
- strategy.constraints = [constraint]
- strategy.constraint_ranking = [constraint]
- strategy.stage_candidates = {0: [Candidate(name="Test")]}
- strategy.candidates = [Candidate(name="Test")]
-
- summary = strategy._format_debug_summary()
-
- assert "Debug" in summary
-
-
-class TestCandidateGrouping:
- """Tests for candidate grouping methods."""
-
- def test_group_similar_candidates(self):
- """Group similar candidates by characteristics."""
- from local_deep_research.advanced_search_system.strategies.constrained_search_strategy import (
- ConstrainedSearchStrategy,
- )
- from local_deep_research.advanced_search_system.candidates.base_candidate import (
- Candidate,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = ConstrainedSearchStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- candidates = [
- Candidate(name="AI Model GPT"),
- Candidate(name="AI Model Claude"),
- Candidate(name="City New York"),
- Candidate(name="Year 2020"),
- ]
-
- grouped = strategy._group_similar_candidates(candidates)
-
- assert isinstance(grouped, dict)
- assert len(grouped) > 0
-
-
-class TestSimpleSearch:
- """Tests for simple search fallback."""
-
- def test_simple_search(self):
- """Simple search returns formatted results."""
- from local_deep_research.advanced_search_system.strategies.constrained_search_strategy import (
- ConstrainedSearchStrategy,
- )
-
- mock_search = Mock()
- mock_search.run.return_value = [
- {
- "title": "Result 1",
- "snippet": "Content 1",
- "link": "http://test.com",
- },
- ]
- mock_model = Mock()
-
- strategy = ConstrainedSearchStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- result = strategy._simple_search("test query")
-
- assert "current_knowledge" in result
- assert "search_results" in result
- assert "Result 1" in result["current_knowledge"]
-
- def test_simple_search_no_results(self):
- """Simple search handles no results."""
- from local_deep_research.advanced_search_system.strategies.constrained_search_strategy import (
- ConstrainedSearchStrategy,
- )
-
- mock_search = Mock()
- mock_search.run.return_value = []
- mock_model = Mock()
-
- strategy = ConstrainedSearchStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- result = strategy._simple_search("test query")
-
- assert "No results found" in result["current_knowledge"]
diff --git a/tests/advanced_search_system/strategies/test_constraint_parallel_high_value.py b/tests/advanced_search_system/strategies/test_constraint_parallel_high_value.py
deleted file mode 100644
index 2a3b0bc46f..0000000000
--- a/tests/advanced_search_system/strategies/test_constraint_parallel_high_value.py
+++ /dev/null
@@ -1,297 +0,0 @@
-"""
-High-value pure logic tests for ConstraintParallelStrategy and ConstraintSearchState.
-
-Tests focus on dataclass defaults, constructor parameter storage, threading primitives,
-and the _should_stop_search decision logic -- all without LLM or network calls.
-"""
-
-import threading
-import time
-from unittest.mock import patch
-
-
-from local_deep_research.advanced_search_system.candidates.base_candidate import (
- Candidate,
-)
-from local_deep_research.advanced_search_system.strategies.constraint_parallel_strategy import (
- ConstraintParallelStrategy,
- ConstraintSearchState,
-)
-
-
-# ---------------------------------------------------------------------------
-# Helpers
-# ---------------------------------------------------------------------------
-
-
-def _make_strategy(**overrides):
- """Create a ConstraintParallelStrategy with __init__ bypassed."""
- with patch.object(
- ConstraintParallelStrategy, "__init__", lambda self, *a, **kw: None
- ):
- strat = ConstraintParallelStrategy.__new__(ConstraintParallelStrategy)
-
- # Apply defaults that the real __init__ would set
- defaults = dict(
- min_good_candidates=3,
- target_candidates=5,
- max_candidates=10,
- min_score_threshold=0.65,
- exceptional_score=0.95,
- quality_plateau_threshold=0.1,
- max_search_time=30.0,
- max_evaluations=30,
- initial_search_timeout=5.0,
- state=None,
- )
- defaults.update(overrides)
- for key, val in defaults.items():
- setattr(strat, key, val)
- return strat
-
-
-def _make_state(**overrides):
- """Create a ConstraintSearchState with optional overrides."""
- return ConstraintSearchState(**overrides)
-
-
-# ---------------------------------------------------------------------------
-# Tests: ConstraintSearchState dataclass
-# ---------------------------------------------------------------------------
-
-
-class TestConstraintSearchStateDefaults:
- """Verify default values of ConstraintSearchState fields."""
-
- def test_all_candidates_defaults_to_empty_list(self):
- state = _make_state()
- assert state.all_candidates == []
-
- def test_evaluated_candidates_defaults_to_empty_list(self):
- state = _make_state()
- assert state.evaluated_candidates == []
-
- def test_total_evaluated_defaults_to_zero(self):
- state = _make_state()
- assert state.total_evaluated == 0
-
- def test_entity_type_defaults_to_unknown(self):
- state = _make_state()
- assert state.entity_type == "unknown entity"
-
- def test_constraint_searches_defaults_to_empty_dict(self):
- state = _make_state()
- assert state.constraint_searches == {}
-
- def test_evaluation_futures_defaults_to_empty_list(self):
- state = _make_state()
- assert state.evaluation_futures == []
-
- def test_start_time_is_recent(self):
- before = time.time()
- state = _make_state()
- after = time.time()
- assert before <= state.start_time <= after
-
-
-class TestConstraintSearchStateThreadingPrimitives:
- """Verify threading fields are properly initialised."""
-
- def test_candidates_lock_is_a_lock(self):
- state = _make_state()
- assert isinstance(state.candidates_lock, type(threading.Lock()))
-
- def test_lock_can_acquire_and_release(self):
- state = _make_state()
- acquired = state.candidates_lock.acquire(blocking=False)
- assert acquired is True
- state.candidates_lock.release()
-
- def test_stop_search_is_an_event(self):
- state = _make_state()
- assert isinstance(state.stop_search, threading.Event)
-
- def test_stop_search_not_set_by_default(self):
- state = _make_state()
- assert not state.stop_search.is_set()
-
- def test_stop_search_can_be_set(self):
- state = _make_state()
- state.stop_search.set()
- assert state.stop_search.is_set()
-
-
-class TestConstraintSearchStateMutability:
- """Verify that list/dict fields are mutable as expected."""
-
- def test_append_to_all_candidates(self):
- state = _make_state()
- cand = Candidate(name="Alice")
- state.all_candidates.append(cand)
- assert len(state.all_candidates) == 1
- assert state.all_candidates[0].name == "Alice"
-
- def test_append_to_evaluated_candidates(self):
- state = _make_state()
- cand = Candidate(name="Bob")
- state.evaluated_candidates.append((cand, 0.85))
- assert len(state.evaluated_candidates) == 1
- assert state.evaluated_candidates[0][1] == 0.85
-
- def test_add_to_constraint_searches(self):
- state = _make_state()
- state.constraint_searches["c1"] = [Candidate(name="X")]
- assert "c1" in state.constraint_searches
-
- def test_independent_instances_have_separate_lists(self):
- state_a = _make_state()
- state_b = _make_state()
- state_a.all_candidates.append(Candidate(name="only_a"))
- assert len(state_b.all_candidates) == 0
-
-
-# ---------------------------------------------------------------------------
-# Tests: ConstraintParallelStrategy constructor defaults
-# ---------------------------------------------------------------------------
-
-
-class TestStrategyConstructorDefaults:
- """Verify that default parameter values match the signature."""
-
- def test_min_good_candidates_default(self):
- strat = _make_strategy()
- assert strat.min_good_candidates == 3
-
- def test_target_candidates_default(self):
- strat = _make_strategy()
- assert strat.target_candidates == 5
-
- def test_max_candidates_default(self):
- strat = _make_strategy()
- assert strat.max_candidates == 10
-
- def test_min_score_threshold_default(self):
- strat = _make_strategy()
- assert strat.min_score_threshold == 0.65
-
- def test_exceptional_score_default(self):
- strat = _make_strategy()
- assert strat.exceptional_score == 0.95
-
- def test_quality_plateau_threshold_default(self):
- strat = _make_strategy()
- assert strat.quality_plateau_threshold == 0.1
-
- def test_max_search_time_default(self):
- strat = _make_strategy()
- assert strat.max_search_time == 30.0
-
- def test_max_evaluations_default(self):
- strat = _make_strategy()
- assert strat.max_evaluations == 30
-
- def test_initial_search_timeout_default(self):
- strat = _make_strategy()
- assert strat.initial_search_timeout == 5.0
-
- def test_state_defaults_to_none(self):
- strat = _make_strategy()
- assert strat.state is None
-
-
-# ---------------------------------------------------------------------------
-# Tests: _should_stop_search logic
-# ---------------------------------------------------------------------------
-
-
-class TestShouldStopSearch:
- """Pure logic tests for the _should_stop_search method."""
-
- def _strategy_with_state(self, evaluated_candidates=None, **state_kw):
- strat = _make_strategy()
- strat.state = _make_state(**state_kw)
- if evaluated_candidates is not None:
- strat.state.evaluated_candidates = evaluated_candidates
- return strat
-
- def test_returns_false_when_no_criteria_met(self):
- strat = self._strategy_with_state(evaluated_candidates=[])
- assert strat._should_stop_search() is False
-
- def test_returns_true_when_stop_event_set(self):
- strat = self._strategy_with_state(evaluated_candidates=[])
- strat.state.stop_search.set()
- assert strat._should_stop_search() is True
-
- def test_returns_true_when_max_candidates_reached(self):
- cands = [(Candidate(name=f"c{i}"), 0.7) for i in range(10)]
- strat = self._strategy_with_state(evaluated_candidates=cands)
- assert strat._should_stop_search() is True
-
- def test_returns_true_target_reached_high_quality(self):
- # 5 candidates with avg score >= 0.8
- cands = [(Candidate(name=f"c{i}"), 0.85) for i in range(5)]
- strat = self._strategy_with_state(evaluated_candidates=cands)
- assert strat._should_stop_search() is True
-
- def test_returns_false_target_reached_low_quality(self):
- # 5 candidates but avg score < 0.8
- cands = [(Candidate(name=f"c{i}"), 0.7) for i in range(5)]
- strat = self._strategy_with_state(evaluated_candidates=cands)
- # Also need score range > plateau threshold to avoid plateau stop
- # Make scores varied enough
- cands[0] = (Candidate(name="c0"), 0.5)
- cands[4] = (Candidate(name="c4"), 0.9)
- strat.state.evaluated_candidates = cands
- assert strat._should_stop_search() is False
-
- def test_returns_true_min_good_with_exceptional_candidate(self):
- cands = [
- (Candidate(name="c0"), 0.7),
- (Candidate(name="c1"), 0.7),
- (Candidate(name="c2"), 0.96),
- ]
- strat = self._strategy_with_state(evaluated_candidates=cands)
- assert strat._should_stop_search() is True
-
- def test_returns_false_min_good_without_exceptional(self):
- cands = [
- (Candidate(name="c0"), 0.7),
- (Candidate(name="c1"), 0.7),
- (Candidate(name="c2"), 0.8),
- ]
- strat = self._strategy_with_state(evaluated_candidates=cands)
- assert strat._should_stop_search() is False
-
- def test_returns_true_time_limit_exceeded(self):
- strat = self._strategy_with_state(
- evaluated_candidates=[],
- start_time=time.time() - 60.0,
- )
- assert strat._should_stop_search() is True
-
- def test_returns_true_evaluation_limit_reached(self):
- strat = self._strategy_with_state(evaluated_candidates=[])
- strat.state.total_evaluated = 30
- assert strat._should_stop_search() is True
-
- def test_returns_true_quality_plateau_detected(self):
- # 5+ candidates with very close recent scores (range < 0.1)
- cands = [(Candidate(name=f"c{i}"), 0.75 + 0.01 * i) for i in range(6)]
- strat = self._strategy_with_state(evaluated_candidates=cands)
- # last 5 scores: 0.76, 0.77, 0.78, 0.79, 0.80 => range=0.04 < 0.1
- assert strat._should_stop_search() is True
-
- def test_returns_false_no_plateau_with_varied_scores(self):
- cands = [
- (Candidate(name="c0"), 0.5),
- (Candidate(name="c1"), 0.6),
- (Candidate(name="c2"), 0.7),
- (Candidate(name="c3"), 0.4),
- (Candidate(name="c4"), 0.9),
- (Candidate(name="c5"), 0.7),
- ]
- strat = self._strategy_with_state(evaluated_candidates=cands)
- # last 5: 0.6, 0.7, 0.4, 0.9, 0.7 => range=0.5 >= 0.1, no plateau
- # Also avg of 6 = ~0.633 < 0.8 so target not met; no exceptional
- assert strat._should_stop_search() is False
diff --git a/tests/advanced_search_system/strategies/test_constraint_parallel_pure_logic.py b/tests/advanced_search_system/strategies/test_constraint_parallel_pure_logic.py
deleted file mode 100644
index 6ec0106b96..0000000000
--- a/tests/advanced_search_system/strategies/test_constraint_parallel_pure_logic.py
+++ /dev/null
@@ -1,128 +0,0 @@
-"""
-Pure-logic tests for ConstraintParallelStrategy._build_constraint_query.
-
-Tests entity-type quoting, constraint-value quoting, search-terms
-appending, and edge cases — no LLM or search calls.
-"""
-
-from unittest.mock import Mock
-
-from local_deep_research.advanced_search_system.constraints.base_constraint import (
- Constraint,
- ConstraintType,
-)
-from local_deep_research.advanced_search_system.strategies.constraint_parallel_strategy import (
- ConstraintParallelStrategy,
-)
-
-
-def _make_strategy(entity_type="unknown entity"):
- """Build a minimal Mock with state attributes."""
- s = Mock(spec=[])
- s.state = Mock(spec=[])
- s.state.entity_type = entity_type
- return s
-
-
-def _constraint(value, ctype=ConstraintType.PROPERTY):
- return Constraint(
- id="c1", type=ctype, description=value, value=value, weight=1.0
- )
-
-
-# ---------------------------------------------------------------------------
-# _build_constraint_query
-# ---------------------------------------------------------------------------
-
-
-class TestBuildConstraintQuery:
- """Verify query construction with quoting logic."""
-
- def test_unknown_entity_type_excluded(self):
- """Unknown entity type is not included in query."""
- s = _make_strategy("unknown entity")
- c = _constraint("tall")
- result = ConstraintParallelStrategy._build_constraint_query(s, c)
- assert "unknown entity" not in result
- assert "tall" in result
-
- def test_none_entity_type_excluded(self):
- """None entity type is not included in query."""
- s = _make_strategy(None)
- c = _constraint("red")
- result = ConstraintParallelStrategy._build_constraint_query(s, c)
- assert result.startswith("red")
-
- def test_empty_entity_type_excluded(self):
- """Empty entity type is not included."""
- s = _make_strategy("")
- c = _constraint("blue")
- result = ConstraintParallelStrategy._build_constraint_query(s, c)
- assert result.startswith("blue")
-
- def test_single_word_entity_not_quoted(self):
- """Single-word entity type is not quoted."""
- s = _make_strategy("mountain")
- c = _constraint("tall")
- result = ConstraintParallelStrategy._build_constraint_query(s, c)
- assert result.startswith("mountain")
- assert '"mountain"' not in result
-
- def test_multi_word_entity_quoted(self):
- """Multi-word entity type gets quoted."""
- s = _make_strategy("national park")
- c = _constraint("large")
- result = ConstraintParallelStrategy._build_constraint_query(s, c)
- assert '"national park"' in result
-
- def test_already_quoted_entity_not_double_quoted(self):
- """Entity already in quotes is not double-quoted."""
- s = _make_strategy('"national park"')
- c = _constraint("large")
- result = ConstraintParallelStrategy._build_constraint_query(s, c)
- assert '""national park""' not in result
- assert '"national park"' in result
-
- def test_single_word_value_not_quoted(self):
- """Single-word constraint value is not quoted."""
- s = _make_strategy("mountain")
- c = _constraint("tall")
- result = ConstraintParallelStrategy._build_constraint_query(s, c)
- assert '"tall"' not in result
-
- def test_multi_word_value_quoted(self):
- """Multi-word constraint value gets quoted."""
- s = _make_strategy("mountain")
- c = _constraint("very tall peak")
- result = ConstraintParallelStrategy._build_constraint_query(s, c)
- assert '"very tall peak"' in result
-
- def test_search_terms_appended_when_different(self):
- """Search terms from constraint are appended when they differ from value."""
- s = _make_strategy()
- c = _constraint("Mount Rainier", ConstraintType.NAME_PATTERN)
- # NAME_PATTERN.to_search_terms() produces a different string
- search_terms = c.to_search_terms()
- result = ConstraintParallelStrategy._build_constraint_query(s, c)
- if search_terms and search_terms != "Mount Rainier":
- assert search_terms in result
-
- def test_search_terms_not_duplicated_when_same(self):
- """Search terms equal to value are not appended twice."""
- s = _make_strategy()
- c = _constraint("simple")
- # For simple values, to_search_terms() often returns the value itself
- result = ConstraintParallelStrategy._build_constraint_query(s, c)
- # Should not have "simple" duplicated
- parts = result.strip().split()
- assert (
- parts.count("simple") <= 2
- ) # entity_type excluded, so at most 1 or 2
-
- def test_all_parts_joined_with_space(self):
- """All query parts are joined with spaces."""
- s = _make_strategy("river")
- c = _constraint("long")
- result = ConstraintParallelStrategy._build_constraint_query(s, c)
- assert "river" in result
- assert "long" in result
diff --git a/tests/advanced_search_system/strategies/test_constraint_parallel_strategy.py b/tests/advanced_search_system/strategies/test_constraint_parallel_strategy.py
deleted file mode 100644
index 4ccfccdc25..0000000000
--- a/tests/advanced_search_system/strategies/test_constraint_parallel_strategy.py
+++ /dev/null
@@ -1,410 +0,0 @@
-"""
-Tests for Constraint Parallel Strategy.
-
-Phase 35: Complex Strategies - Tests for constraint_parallel_strategy.py
-Tests parallel search dispatch, constraint handling, and result merging.
-"""
-
-from unittest.mock import MagicMock
-
-
-class TestConstraintParallelStrategyInit:
- """Tests for constraint parallel strategy initialization."""
-
- def test_initialization_imports(self):
- """Test that required modules can be imported."""
- try:
- from local_deep_research.advanced_search_system.strategies.constraint_parallel_strategy import (
- ConstraintParallelStrategy,
- )
-
- assert ConstraintParallelStrategy is not None
- except ImportError:
- # Module might not exist, test the concept
- pass
-
- def test_initialization_basic(self):
- """Test basic initialization concepts."""
- mock_model = MagicMock()
- mock_search = MagicMock()
-
- # Basic constraint parallel strategy should have:
- strategy_config = {
- "model": mock_model,
- "search": mock_search,
- "max_parallel": 5,
- "timeout": 30,
- }
-
- assert strategy_config["max_parallel"] == 5
-
-
-class TestConstraintParsing:
- """Tests for constraint parsing functionality."""
-
- def test_parse_simple_constraint(self):
- """Test parsing simple constraints."""
- constraint = "date:2024"
- parts = constraint.split(":")
- assert parts[0] == "date"
- assert parts[1] == "2024"
-
- def test_parse_multiple_constraints(self):
- """Test parsing multiple constraints."""
- constraints = [
- "date:2024",
- "source:arxiv",
- "type:research",
- ]
- parsed = {}
- for c in constraints:
- key, value = c.split(":")
- parsed[key] = value
-
- assert len(parsed) == 3
- assert parsed["source"] == "arxiv"
-
- def test_parse_constraint_with_special_chars(self):
- """Test parsing constraints with special characters."""
- constraint = "query:machine learning AND deep learning"
- parts = constraint.split(":", 1)
- assert parts[0] == "query"
- assert "AND" in parts[1]
-
-
-class TestParallelSearchDispatch:
- """Tests for parallel search dispatch."""
-
- def test_dispatch_single_search(self):
- """Test dispatching single search."""
- mock_search = MagicMock()
- mock_search.search.return_value = [{"title": "Result 1"}]
-
- results = mock_search.search("test query")
- assert len(results) == 1
-
- def test_dispatch_multiple_searches(self):
- """Test dispatching multiple parallel searches."""
- mock_search = MagicMock()
- queries = ["query1", "query2", "query3"]
-
- results = []
- for q in queries:
- mock_search.search.return_value = [{"title": f"Result for {q}"}]
- results.append(mock_search.search(q))
-
- assert len(results) == 3
-
- def test_dispatch_with_timeout(self):
- """Test dispatch respects timeout."""
- timeout = 30 # seconds
- assert timeout > 0
-
-
-class TestResultMerging:
- """Tests for result merging from parallel searches."""
-
- def test_merge_results_basic(self):
- """Test basic result merging."""
- results1 = [{"url": "url1", "title": "Title 1"}]
- results2 = [{"url": "url2", "title": "Title 2"}]
-
- merged = results1 + results2
- assert len(merged) == 2
-
- def test_merge_results_deduplication(self):
- """Test deduplication during merge."""
- results1 = [{"url": "url1"}, {"url": "url2"}]
- results2 = [{"url": "url2"}, {"url": "url3"}] # url2 is duplicate
-
- all_results = results1 + results2
- unique = {r["url"]: r for r in all_results}
-
- assert len(unique) == 3
-
- def test_merge_results_ranking(self):
- """Test ranking merged results."""
- merged = [
- {"url": "url1", "score": 0.9},
- {"url": "url2", "score": 0.7},
- {"url": "url3", "score": 0.8},
- ]
- sorted_results = sorted(merged, key=lambda x: x["score"], reverse=True)
-
- assert sorted_results[0]["score"] == 0.9
- assert sorted_results[-1]["score"] == 0.7
-
-
-class TestConstraintValidation:
- """Tests for constraint validation."""
-
- def test_validate_date_constraint(self):
- """Test validation of date constraints."""
- valid_dates = ["2024", "2024-01", "2024-01-15"]
- for date in valid_dates:
- # Simple validation - check format
- is_valid = date.replace("-", "").isdigit()
- assert is_valid
-
- def test_validate_source_constraint(self):
- """Test validation of source constraints."""
- valid_sources = ["arxiv", "wikipedia", "google", "pubmed"]
- source = "arxiv"
- assert source in valid_sources
-
- def test_validate_invalid_constraint(self):
- """Test handling of invalid constraints."""
- invalid = "invalid_format_no_colon"
- has_separator = ":" in invalid
- assert not has_separator
-
-
-class TestConstraintRelaxation:
- """Tests for constraint relaxation when no results found."""
-
- def test_relax_date_constraint(self):
- """Test relaxing date constraint."""
- original = "2024-01-15"
- # Relax to month level
- relaxed1 = original[:7] # "2024-01"
- # Relax to year level
- relaxed2 = original[:4] # "2024"
-
- assert len(relaxed1) < len(original)
- assert len(relaxed2) < len(relaxed1)
-
- def test_relax_multiple_constraints(self):
- """Test relaxing multiple constraints."""
- constraints = {
- "date": "2024-01-15",
- "source": "arxiv",
- "type": "paper",
- }
- # Remove one constraint at a time
- relaxation_order = ["type", "date", "source"]
-
- for key in relaxation_order:
- constraints.pop(key, None)
- assert len(constraints) < 3
-
-
-class TestConflictResolution:
- """Tests for resolving conflicts between parallel results."""
-
- def test_resolve_conflicting_scores(self):
- """Test resolving results with conflicting scores."""
- result1 = {"url": "same_url", "score": 0.8, "source": "search1"}
- result2 = {"url": "same_url", "score": 0.9, "source": "search2"}
-
- # Take higher score
- final_score = max(result1["score"], result2["score"])
- assert final_score == 0.9
-
- def test_resolve_conflicting_metadata(self):
- """Test resolving results with conflicting metadata."""
- result1 = {"url": "url", "title": "Title A", "date": "2024"}
- result2 = {"url": "url", "title": "Title B", "date": "2024"}
-
- # Could merge metadata or prefer one source
- merged = result1.copy()
- merged["alternative_titles"] = [result2["title"]]
-
- assert "alternative_titles" in merged
-
-
-class TestPriorityHandling:
- """Tests for constraint priority handling."""
-
- def test_priority_ordering(self):
- """Test constraints are handled in priority order."""
- constraints = [
- {"type": "required", "value": "constraint1", "priority": 1},
- {"type": "optional", "value": "constraint2", "priority": 3},
- {"type": "preferred", "value": "constraint3", "priority": 2},
- ]
- sorted_constraints = sorted(constraints, key=lambda x: x["priority"])
-
- assert sorted_constraints[0]["priority"] == 1
-
-
-class TestResourceAllocation:
- """Tests for resource allocation in parallel execution."""
-
- def test_limit_parallel_requests(self):
- """Test limiting parallel requests."""
- max_parallel = 5
- requests = list(range(10))
-
- # Should batch into groups
- batches = [
- requests[i : i + max_parallel]
- for i in range(0, len(requests), max_parallel)
- ]
- assert len(batches) == 2
-
- def test_resource_distribution(self):
- """Test distributing resources across searches."""
- total_budget = 100
- num_searches = 4
- per_search = total_budget // num_searches
-
- assert per_search == 25
-
-
-class TestTimeoutHandling:
- """Tests for timeout handling in parallel searches."""
-
- def test_individual_search_timeout(self):
- """Test individual search respects timeout."""
- timeout_seconds = 10
- assert timeout_seconds > 0
-
- def test_overall_timeout(self):
- """Test overall operation timeout."""
- total_timeout = 60
- individual_timeout = 10
-
- # Total should be larger than individual
- assert total_timeout >= individual_timeout
-
-
-class TestPartialResults:
- """Tests for handling partial results."""
-
- def test_return_partial_on_timeout(self):
- """Test returning partial results when some searches timeout."""
- completed_results = [
- {"url": "url1", "completed": True},
- {"url": "url2", "completed": True},
- ]
- timed_out = ["search3", "search4"]
-
- # Should still return completed results
- assert len(completed_results) == 2
- assert len(timed_out) == 2
-
- def test_mark_incomplete_results(self):
- """Test marking results from incomplete searches."""
- result = {"url": "url1", "complete": False, "reason": "timeout"}
- assert not result["complete"]
-
-
-class TestErrorRecovery:
- """Tests for error recovery in parallel execution."""
-
- def test_recover_from_single_search_error(self):
- """Test recovery when one parallel search fails."""
- search_results = [
- {"status": "success", "results": [{"url": "url1"}]},
- {"status": "error", "error": "Connection failed"},
- {"status": "success", "results": [{"url": "url2"}]},
- ]
- successful = [
- r["results"] for r in search_results if r["status"] == "success"
- ]
-
- assert len(successful) == 2
-
- def test_recover_from_multiple_errors(self):
- """Test recovery when multiple searches fail."""
- num_searches = 5
- num_failed = 3
- num_successful = num_searches - num_failed
-
- assert num_successful > 0 # Should still have some results
-
-
-class TestProgressTracking:
- """Tests for progress tracking in parallel execution."""
-
- def test_track_completion_percentage(self):
- """Test tracking completion percentage."""
- total = 10
- completed = 6
- percentage = (completed / total) * 100
-
- assert percentage == 60.0
-
- def test_report_progress_updates(self):
- """Test progress updates are reported."""
- updates = []
-
- def progress_callback(message, percent, data):
- updates.append({"message": message, "percent": percent})
-
- # Simulate progress
- progress_callback("Starting", 0, {})
- progress_callback("In progress", 50, {})
- progress_callback("Complete", 100, {})
-
- assert len(updates) == 3
- assert updates[-1]["percent"] == 100
-
-
-class TestStateManagement:
- """Tests for strategy state management."""
-
- def test_initialize_state(self):
- """Test state initialization."""
- state = {
- "constraints": [],
- "results": [],
- "iteration": 0,
- "status": "ready",
- }
- assert state["status"] == "ready"
-
- def test_update_state(self):
- """Test state updates during execution."""
- state = {"iteration": 0, "results": []}
-
- state["iteration"] += 1
- state["results"].append({"url": "url1"})
-
- assert state["iteration"] == 1
- assert len(state["results"]) == 1
-
-
-class TestCheckpointSupport:
- """Tests for checkpoint support."""
-
- def test_save_checkpoint(self):
- """Test saving checkpoint."""
- checkpoint = {
- "iteration": 5,
- "constraints_processed": 3,
- "results_so_far": [{"url": "url1"}],
- }
- # Checkpoint should be serializable
- import json
-
- serialized = json.dumps(checkpoint)
- assert len(serialized) > 0
-
- def test_restore_from_checkpoint(self):
- """Test restoring from checkpoint."""
- import json
-
- checkpoint_str = '{"iteration": 5, "results": []}'
- checkpoint = json.loads(checkpoint_str)
-
- assert checkpoint["iteration"] == 5
-
-
-class TestMetrics:
- """Tests for strategy metrics tracking."""
-
- def test_track_search_metrics(self):
- """Test tracking search metrics."""
- metrics = {
- "total_searches": 10,
- "successful_searches": 8,
- "failed_searches": 2,
- "total_results": 150,
- "unique_results": 120,
- }
-
- success_rate = (
- metrics["successful_searches"] / metrics["total_searches"]
- )
- assert success_rate == 0.8
diff --git a/tests/advanced_search_system/strategies/test_decomposition_strategies.py b/tests/advanced_search_system/strategies/test_decomposition_strategies.py
deleted file mode 100644
index bf2e363e22..0000000000
--- a/tests/advanced_search_system/strategies/test_decomposition_strategies.py
+++ /dev/null
@@ -1,646 +0,0 @@
-"""
-Tests for decomposition search strategies.
-
-Combined tests for:
-- RecursiveDecompositionStrategy
-- AdaptiveDecompositionStrategy
-- IterativeRefinementStrategy
-- IterativeReasoningStrategy
-- FocusedIterationStrategy
-
-Tests cover:
-- Initialization and configuration
-- Query decomposition
-- Sub-query handling
-- Result synthesis
-- Iteration control
-- Error handling
-"""
-
-from unittest.mock import Mock, patch
-
-
-class TestRecursiveDecompositionStrategyInit:
- """Tests for RecursiveDecompositionStrategy initialization."""
-
- def test_init_with_required_params(self):
- """Initialize with required parameters."""
- from local_deep_research.advanced_search_system.strategies.recursive_decomposition_strategy import (
- RecursiveDecompositionStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = RecursiveDecompositionStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- assert strategy.model is mock_model
- assert strategy.search is mock_search
-
- def test_init_with_max_depth(self):
- """Initialize with max recursion depth parameter."""
- from local_deep_research.advanced_search_system.strategies.recursive_decomposition_strategy import (
- RecursiveDecompositionStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = RecursiveDecompositionStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- max_recursion_depth=5, # Correct parameter name
- )
-
- assert strategy.max_recursion_depth == 5
-
-
-class TestAdaptiveDecompositionStrategyInit:
- """Tests for AdaptiveDecompositionStrategy initialization."""
-
- def test_init_with_required_params(self):
- """Initialize with required parameters."""
- from local_deep_research.advanced_search_system.strategies.adaptive_decomposition_strategy import (
- AdaptiveDecompositionStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = AdaptiveDecompositionStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- assert strategy.model is mock_model
- assert strategy.search is mock_search
-
- def test_init_with_adaptation_params(self):
- """Initialize with adaptation parameters."""
- from local_deep_research.advanced_search_system.strategies.adaptive_decomposition_strategy import (
- AdaptiveDecompositionStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = AdaptiveDecompositionStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- # Should have adaptive components
- assert hasattr(strategy, "model")
-
-
-class TestIterativeRefinementStrategyInit:
- """Tests for IterativeRefinementStrategy initialization."""
-
- def test_init_with_required_params(self):
- """Initialize with required parameters."""
- from local_deep_research.advanced_search_system.strategies.iterative_refinement_strategy import (
- IterativeRefinementStrategy,
- )
- from local_deep_research.advanced_search_system.strategies.base_strategy import (
- BaseSearchStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
- mock_initial_strategy = Mock(spec=BaseSearchStrategy)
-
- strategy = IterativeRefinementStrategy(
- model=mock_model,
- search=mock_search,
- initial_strategy=mock_initial_strategy, # Required parameter
- all_links_of_system=[],
- )
-
- assert strategy.model is mock_model
- assert strategy.search is mock_search
-
- def test_init_with_iteration_params(self):
- """Initialize with iteration parameters."""
- from local_deep_research.advanced_search_system.strategies.iterative_refinement_strategy import (
- IterativeRefinementStrategy,
- )
- from local_deep_research.advanced_search_system.strategies.base_strategy import (
- BaseSearchStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
- mock_initial_strategy = Mock(spec=BaseSearchStrategy)
-
- strategy = IterativeRefinementStrategy(
- model=mock_model,
- search=mock_search,
- initial_strategy=mock_initial_strategy,
- all_links_of_system=[],
- max_refinements=10, # Correct parameter name
- )
-
- assert strategy.max_refinements == 10
-
-
-class TestIterativeReasoningStrategyInit:
- """Tests for IterativeReasoningStrategy initialization."""
-
- def test_init_with_required_params(self):
- """Initialize with required parameters."""
- from local_deep_research.advanced_search_system.strategies.iterative_reasoning_strategy import (
- IterativeReasoningStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = IterativeReasoningStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- assert strategy.model is mock_model
- assert strategy.search is mock_search
-
-
-class TestFocusedIterationStrategyInit:
- """Tests for FocusedIterationStrategy initialization."""
-
- def test_init_with_required_params(self):
- """Initialize with required parameters."""
- from local_deep_research.advanced_search_system.strategies.focused_iteration_strategy import (
- FocusedIterationStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
- mock_citation_handler = Mock()
-
- strategy = FocusedIterationStrategy(
- search=mock_search,
- model=mock_model,
- citation_handler=mock_citation_handler,
- )
-
- assert strategy.model is mock_model
- assert strategy.search is mock_search
-
- def test_init_with_custom_iterations(self):
- """Initialize with custom iteration parameters."""
- from local_deep_research.advanced_search_system.strategies.focused_iteration_strategy import (
- FocusedIterationStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
- mock_citation_handler = Mock()
-
- strategy = FocusedIterationStrategy(
- search=mock_search,
- model=mock_model,
- citation_handler=mock_citation_handler,
- max_iterations=15,
- questions_per_iteration=3,
- )
-
- assert strategy.max_iterations == 15
- assert strategy.questions_per_iteration == 3
-
-
-class TestRecursiveDecompositionAnalyze:
- """Tests for RecursiveDecompositionStrategy analyze_topic method."""
-
- def test_analyze_topic_returns_dict(self):
- """Analyze topic returns result dictionary."""
- from local_deep_research.advanced_search_system.strategies.recursive_decomposition_strategy import (
- RecursiveDecompositionStrategy,
- )
-
- mock_search = Mock()
- mock_search.run.return_value = []
- mock_model = Mock()
- # Return should_decompose = False to use direct search
- mock_model.invoke.return_value = Mock(
- content='{"should_decompose": false, "reason": "Simple query"}'
- )
-
- strategy = RecursiveDecompositionStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- # Mock the _use_source_based_strategy to avoid complex setup
- with patch.object(
- strategy,
- "_use_source_based_strategy",
- return_value={
- "current_knowledge": "Test",
- "findings": [],
- "all_links_of_system": [],
- },
- ):
- result = strategy.analyze_topic("test query")
-
- assert isinstance(result, dict)
-
-
-class TestAdaptiveDecompositionAnalyze:
- """Tests for AdaptiveDecompositionStrategy analyze_topic method."""
-
- def test_analyze_topic_adaptive(self):
- """Analyze topic adapts to query complexity."""
- from local_deep_research.advanced_search_system.strategies.adaptive_decomposition_strategy import (
- AdaptiveDecompositionStrategy,
- )
-
- mock_search = Mock()
- mock_search.run.return_value = []
- mock_model = Mock()
- mock_model.invoke.return_value = Mock(
- content='{"complexity": "low", "confidence": 0.9}'
- )
-
- strategy = AdaptiveDecompositionStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- # Just verify strategy can be instantiated and has analyze_topic
- assert hasattr(strategy, "analyze_topic")
- assert callable(strategy.analyze_topic)
-
-
-class TestIterativeRefinementAnalyze:
- """Tests for IterativeRefinementStrategy analyze_topic method."""
-
- def test_analyze_topic_iterates(self):
- """Analyze topic performs iterative refinement."""
- from local_deep_research.advanced_search_system.strategies.iterative_refinement_strategy import (
- IterativeRefinementStrategy,
- )
- from local_deep_research.advanced_search_system.strategies.base_strategy import (
- BaseSearchStrategy,
- )
-
- mock_search = Mock()
- mock_search.run.return_value = []
- mock_model = Mock()
- # Return high confidence to stop early
- mock_model.invoke.return_value = Mock(
- content='{"confidence": 0.95, "gaps": [], "should_continue": false}'
- )
-
- # Create a mock initial strategy
- mock_initial_strategy = Mock(spec=BaseSearchStrategy)
- mock_initial_strategy.analyze_topic.return_value = {
- "current_knowledge": "Test knowledge",
- "findings": [],
- "all_links_of_system": [],
- }
-
- strategy = IterativeRefinementStrategy(
- model=mock_model,
- search=mock_search,
- initial_strategy=mock_initial_strategy,
- all_links_of_system=[],
- max_refinements=2,
- )
-
- result = strategy.analyze_topic("test query")
-
- assert isinstance(result, dict)
-
-
-class TestIterativeReasoningAnalyze:
- """Tests for IterativeReasoningStrategy analyze_topic method."""
-
- def test_analyze_topic_reasons(self):
- """Analyze topic performs iterative reasoning."""
- from local_deep_research.advanced_search_system.strategies.iterative_reasoning_strategy import (
- IterativeReasoningStrategy,
- )
-
- mock_search = Mock()
- mock_search.run.return_value = []
- mock_model = Mock()
- # Return content indicating completion
- mock_model.invoke.return_value = Mock(
- content='{"reasoning_complete": true, "confidence": 0.9}'
- )
-
- strategy = IterativeReasoningStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- # Mock internal methods if needed
- try:
- result = strategy.analyze_topic("test query")
- assert isinstance(result, dict)
- except Exception:
- # If complex setup needed, verify strategy can be instantiated
- assert hasattr(strategy, "analyze_topic")
-
-
-class TestFocusedIterationAnalyze:
- """Tests for FocusedIterationStrategy analyze_topic method."""
-
- def test_analyze_topic_focused(self):
- """Analyze topic performs focused iteration."""
- from local_deep_research.advanced_search_system.strategies.focused_iteration_strategy import (
- FocusedIterationStrategy,
- )
-
- mock_search = Mock()
- mock_search.run.return_value = []
- mock_model = Mock()
- mock_model.invoke.return_value = Mock(content="Response")
- mock_citation_handler = Mock()
- mock_citation_handler.analyze_followup.return_value = {
- "content": "Analysis",
- "documents": [],
- }
-
- strategy = FocusedIterationStrategy(
- search=mock_search,
- model=mock_model,
- citation_handler=mock_citation_handler,
- max_iterations=1,
- )
-
- result = strategy.analyze_topic("test query")
-
- assert isinstance(result, dict)
-
-
-class TestQueryDecomposition:
- """Tests for query decomposition methods."""
-
- def test_decompose_query_creates_subqueries(self):
- """Decompose query creates sub-queries."""
- from local_deep_research.advanced_search_system.strategies.recursive_decomposition_strategy import (
- RecursiveDecompositionStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
- mock_model.invoke.return_value = Mock(
- content="1. Sub-query 1\n2. Sub-query 2\n3. Sub-query 3"
- )
-
- strategy = RecursiveDecompositionStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- # The decompose method should exist and work
- if hasattr(strategy, "_decompose_query"):
- subqueries = strategy._decompose_query("complex query")
- assert isinstance(subqueries, (list, tuple))
-
-
-class TestResultSynthesis:
- """Tests for result synthesis methods."""
-
- def test_synthesize_results(self):
- """Synthesize results combines sub-results."""
- from local_deep_research.advanced_search_system.strategies.recursive_decomposition_strategy import (
- RecursiveDecompositionStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
- mock_model.invoke.return_value = Mock(content="Synthesized response")
-
- strategy = RecursiveDecompositionStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- # Test synthesis if method exists
- if hasattr(strategy, "_synthesize_results"):
- results = [{"content": "Result 1"}, {"content": "Result 2"}]
- synthesized = strategy._synthesize_results(results)
- assert synthesized is not None
-
-
-class TestIterationControl:
- """Tests for iteration control."""
-
- def test_max_iterations_respected(self):
- """Max refinements parameter is respected."""
- from local_deep_research.advanced_search_system.strategies.iterative_refinement_strategy import (
- IterativeRefinementStrategy,
- )
- from local_deep_research.advanced_search_system.strategies.base_strategy import (
- BaseSearchStrategy,
- )
-
- mock_search = Mock()
- mock_search.run.return_value = []
- mock_model = Mock()
- # Return low confidence to trigger more iterations
- mock_model.invoke.return_value = Mock(
- content='{"confidence": 0.3, "gaps": ["gap1"], "should_continue": true}'
- )
-
- mock_initial_strategy = Mock(spec=BaseSearchStrategy)
- mock_initial_strategy.analyze_topic.return_value = {
- "current_knowledge": "Test",
- "findings": [],
- "all_links_of_system": [],
- }
-
- strategy = IterativeRefinementStrategy(
- model=mock_model,
- search=mock_search,
- initial_strategy=mock_initial_strategy,
- all_links_of_system=[],
- max_refinements=2,
- )
-
- result = strategy.analyze_topic("test query")
-
- # Should have stopped within max refinements
- assert isinstance(result, dict)
-
- def test_early_stopping_on_confidence(self):
- """Early stopping when confidence threshold reached."""
- from local_deep_research.advanced_search_system.strategies.iterative_reasoning_strategy import (
- IterativeReasoningStrategy,
- )
-
- mock_search = Mock()
- mock_search.run.return_value = []
- mock_model = Mock()
- mock_model.invoke.return_value = Mock(
- content='{"reasoning_complete": true, "confidence": 0.95}'
- )
-
- strategy = IterativeReasoningStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- try:
- result = strategy.analyze_topic("test query")
- assert isinstance(result, dict)
- except Exception:
- # If complex setup needed, verify strategy exists
- assert hasattr(strategy, "analyze_topic")
-
-
-class TestProgressCallbacks:
- """Tests for progress callback support."""
-
- def test_focused_iteration_progress(self):
- """FocusedIterationStrategy calls progress callback."""
- from local_deep_research.advanced_search_system.strategies.focused_iteration_strategy import (
- FocusedIterationStrategy,
- )
-
- mock_search = Mock()
- mock_search.run.return_value = []
- mock_model = Mock()
- mock_model.invoke.return_value = Mock(content="Response")
- mock_citation_handler = Mock()
- mock_citation_handler.analyze_followup.return_value = {
- "content": "Analysis",
- "documents": [],
- }
-
- strategy = FocusedIterationStrategy(
- search=mock_search,
- model=mock_model,
- citation_handler=mock_citation_handler,
- max_iterations=1,
- )
-
- callback = Mock()
- strategy.set_progress_callback(callback)
-
- strategy.analyze_topic("test query")
-
- # Should call progress callback at least once
- assert callback.call_count >= 0
-
-
-class TestErrorHandling:
- """Tests for error handling in decomposition strategies."""
-
- def test_recursive_handles_decomposition_error(self):
- """Recursive strategy handles decomposition errors."""
- from local_deep_research.advanced_search_system.strategies.recursive_decomposition_strategy import (
- RecursiveDecompositionStrategy,
- )
-
- mock_search = Mock()
- mock_search.run.return_value = []
- mock_model = Mock()
- mock_model.invoke.side_effect = Exception("LLM Error")
-
- strategy = RecursiveDecompositionStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- # Should handle error gracefully
- try:
- result = strategy.analyze_topic("test query")
- # If it returns, should be a dict
- assert isinstance(result, dict)
- except Exception:
- # Some implementations may raise
- pass
-
- def test_focused_iteration_handles_search_error(self):
- """FocusedIterationStrategy handles search errors."""
- from local_deep_research.advanced_search_system.strategies.focused_iteration_strategy import (
- FocusedIterationStrategy,
- )
-
- mock_search = Mock()
- mock_search.run.side_effect = Exception("Search error")
- mock_model = Mock()
- mock_model.invoke.return_value = Mock(content="Response")
- mock_citation_handler = Mock()
- mock_citation_handler.analyze_followup.return_value = {
- "content": "Analysis",
- "documents": [],
- }
-
- strategy = FocusedIterationStrategy(
- search=mock_search,
- model=mock_model,
- citation_handler=mock_citation_handler,
- max_iterations=1,
- )
-
- # Should handle error gracefully
- try:
- result = strategy.analyze_topic("test query")
- assert isinstance(result, dict)
- except Exception:
- # Some implementations may raise
- pass
-
-
-class TestInheritance:
- """Tests for inheritance relationships."""
-
- def test_recursive_inherits_base(self):
- """RecursiveDecompositionStrategy inherits from base."""
- from local_deep_research.advanced_search_system.strategies.recursive_decomposition_strategy import (
- RecursiveDecompositionStrategy,
- )
- from local_deep_research.advanced_search_system.strategies.base_strategy import (
- BaseSearchStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = RecursiveDecompositionStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- assert isinstance(strategy, BaseSearchStrategy)
-
- def test_focused_iteration_inherits_base(self):
- """FocusedIterationStrategy inherits from base."""
- from local_deep_research.advanced_search_system.strategies.focused_iteration_strategy import (
- FocusedIterationStrategy,
- )
- from local_deep_research.advanced_search_system.strategies.base_strategy import (
- BaseSearchStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
- mock_citation_handler = Mock()
-
- strategy = FocusedIterationStrategy(
- search=mock_search,
- model=mock_model,
- citation_handler=mock_citation_handler,
- )
-
- assert isinstance(strategy, BaseSearchStrategy)
diff --git a/tests/advanced_search_system/strategies/test_dual_confidence_rejection_high_value.py b/tests/advanced_search_system/strategies/test_dual_confidence_rejection_high_value.py
deleted file mode 100644
index c303c83d4a..0000000000
--- a/tests/advanced_search_system/strategies/test_dual_confidence_rejection_high_value.py
+++ /dev/null
@@ -1,320 +0,0 @@
-"""High-value tests for DualConfidenceWithRejectionStrategy pure logic."""
-
-import pytest
-import threading
-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.strategies.dual_confidence_with_rejection import (
- DualConfidenceWithRejectionStrategy,
-)
-
-
-def make_constraint(ctype, value, weight=1.0, cid=None):
- return Constraint(
- id=cid or f"c_{value[:8]}",
- type=ctype,
- description=value,
- value=value,
- weight=weight,
- )
-
-
-def make_mock_evidence(positive=0.5, negative=0.1, uncertainty=0.4):
- """Create a mock dual evidence result."""
- ev = MagicMock()
- ev.positive_confidence = positive
- ev.negative_confidence = negative
- ev.uncertainty = uncertainty
- return ev
-
-
-def strategy():
- """Create strategy with mocked parent init."""
- with patch.object(
- DualConfidenceWithRejectionStrategy,
- "__init__",
- lambda self, *a, **kw: None,
- ):
- s = DualConfidenceWithRejectionStrategy.__new__(
- DualConfidenceWithRejectionStrategy
- )
- s.rejection_threshold = 0.3
- s.positive_threshold = 0.2
- s.critical_constraint_rejection = 0.2
- s.uncertainty_penalty = 0.1
- s.negative_weight = 1.0
- s.constraint_ranking = []
- s.evaluated_candidates = {}
- s.best_score = 0.0
- s.best_candidate = None
- s.early_stop_threshold = 0.95
- s.found_answer = threading.Event()
- s.evaluation_lock = threading.Lock()
- return s
-
-
-# --- Constructor defaults ---
-
-
-class TestConstructorDefaults:
- def test_rejection_threshold(self, strategy):
- assert strategy.rejection_threshold == 0.3
-
- def test_positive_threshold(self, strategy):
- assert strategy.positive_threshold == 0.2
-
- def test_critical_constraint_rejection(self, strategy):
- assert strategy.critical_constraint_rejection == 0.2
-
-
-# --- Symbol mapping logic ---
-
-
-class TestSymbolMapping:
- """Test the symbol assignment logic: >= 0.8 -> checkmark, >= 0.5 -> circle, else cross."""
-
- def test_checkmark_at_0_8(self):
- score = 0.8
- symbol = "✓" if score >= 0.8 else "○" if score >= 0.5 else "✗"
- assert symbol == "✓"
-
- def test_checkmark_above_0_8(self):
- score = 0.95
- symbol = "✓" if score >= 0.8 else "○" if score >= 0.5 else "✗"
- assert symbol == "✓"
-
- def test_circle_at_0_5(self):
- score = 0.5
- symbol = "✓" if score >= 0.8 else "○" if score >= 0.5 else "✗"
- assert symbol == "○"
-
- def test_circle_at_0_79(self):
- score = 0.79
- symbol = "✓" if score >= 0.8 else "○" if score >= 0.5 else "✗"
- assert symbol == "○"
-
- def test_cross_below_0_5(self):
- score = 0.49
- symbol = "✓" if score >= 0.8 else "○" if score >= 0.5 else "✗"
- assert symbol == "✗"
-
- def test_cross_at_zero(self):
- score = 0.0
- symbol = "✓" if score >= 0.8 else "○" if score >= 0.5 else "✗"
- assert symbol == "✗"
-
-
-# --- Early rejection logic ---
-
-
-class TestEarlyRejection:
- def test_high_negative_rejects(self, strategy):
- """avg_negative > 0.25 should return 0.0."""
- candidate = MagicMock()
- candidate.name = "Test"
-
- constraint = make_constraint(
- ConstraintType.PROPERTY, "test", weight=1.0
- )
- strategy.constraint_ranking = [constraint]
-
- evidence = [MagicMock()]
- strategy._gather_evidence_for_constraint = MagicMock(
- return_value=evidence
- )
-
- dual_ev = make_mock_evidence(
- positive=0.1, negative=0.3, uncertainty=0.6
- )
- strategy._analyze_evidence_dual_confidence = MagicMock(
- return_value=dual_ev
- )
-
- result = strategy._evaluate_candidate_immediately(candidate)
- assert result == 0.0
-
- def test_low_negative_continues(self, strategy):
- """avg_negative <= 0.25 should not trigger early rejection."""
- candidate = MagicMock()
- candidate.name = "Test"
-
- constraint = make_constraint(
- ConstraintType.PROPERTY, "test", weight=1.0
- )
- strategy.constraint_ranking = [constraint]
-
- evidence = [MagicMock()]
- strategy._gather_evidence_for_constraint = MagicMock(
- return_value=evidence
- )
-
- dual_ev = make_mock_evidence(
- positive=0.6, negative=0.2, uncertainty=0.2
- )
- strategy._analyze_evidence_dual_confidence = MagicMock(
- return_value=dual_ev
- )
- strategy._evaluate_evidence = MagicMock(return_value=0.7)
-
- result = strategy._evaluate_candidate_immediately(candidate)
- assert result > 0.0
-
-
-# --- Skip remaining logic ---
-
-
-class TestSkipRemaining:
- def test_poor_score_important_constraint_skips(self, strategy):
- """score < 0.2 and weight > 0.5 should skip remaining constraints."""
- candidate = MagicMock()
- candidate.name = "Test"
-
- c1 = make_constraint(ConstraintType.PROPERTY, "important", weight=0.8)
- c2 = make_constraint(ConstraintType.PROPERTY, "secondary", weight=0.3)
- strategy.constraint_ranking = [c1, c2]
-
- evidence = [MagicMock()]
- strategy._gather_evidence_for_constraint = MagicMock(
- return_value=evidence
- )
-
- dual_ev = make_mock_evidence(
- positive=0.1, negative=0.1, uncertainty=0.8
- )
- strategy._analyze_evidence_dual_confidence = MagicMock(
- return_value=dual_ev
- )
- strategy._evaluate_evidence = MagicMock(return_value=0.1)
-
- strategy._evaluate_candidate_immediately(candidate)
- # Only one constraint evaluated due to skip
- assert strategy._evaluate_evidence.call_count == 1
-
-
-# --- Weighted average ---
-
-
-class TestWeightedAverage:
- def test_single_constraint(self, strategy):
- candidate = MagicMock()
- candidate.name = "Test"
-
- c1 = make_constraint(ConstraintType.PROPERTY, "test", weight=2.0)
- strategy.constraint_ranking = [c1]
-
- evidence = [MagicMock()]
- strategy._gather_evidence_for_constraint = MagicMock(
- return_value=evidence
- )
-
- dual_ev = make_mock_evidence(
- positive=0.7, negative=0.1, uncertainty=0.2
- )
- strategy._analyze_evidence_dual_confidence = MagicMock(
- return_value=dual_ev
- )
- strategy._evaluate_evidence = MagicMock(return_value=0.8)
-
- result = strategy._evaluate_candidate_immediately(candidate)
- # Weighted avg: (0.8 * 2.0) / 2.0 = 0.8
- assert abs(result - 0.8) < 0.01
-
- def test_two_constraints_weighted(self, strategy):
- candidate = MagicMock()
- candidate.name = "Test"
-
- c1 = make_constraint(ConstraintType.PROPERTY, "c1", weight=1.0)
- c2 = make_constraint(ConstraintType.PROPERTY, "c2", weight=3.0)
- strategy.constraint_ranking = [c1, c2]
-
- evidence = [MagicMock()]
- strategy._gather_evidence_for_constraint = MagicMock(
- return_value=evidence
- )
-
- dual_ev = make_mock_evidence(
- positive=0.7, negative=0.1, uncertainty=0.2
- )
- strategy._analyze_evidence_dual_confidence = MagicMock(
- return_value=dual_ev
- )
- strategy._evaluate_evidence = MagicMock(side_effect=[0.6, 0.8])
-
- result = strategy._evaluate_candidate_immediately(candidate)
- # (0.6*1.0 + 0.8*3.0) / (1.0+3.0) = 3.0/4.0 = 0.75
- assert abs(result - 0.75) < 0.01
-
-
-# --- No evidence ---
-
-
-class TestNoEvidence:
- def test_no_evidence_uses_uncertainty_penalty(self, strategy):
- candidate = MagicMock()
- candidate.name = "Test"
-
- c1 = make_constraint(ConstraintType.PROPERTY, "test", weight=1.0)
- strategy.constraint_ranking = [c1]
-
- strategy._gather_evidence_for_constraint = MagicMock(return_value=[])
-
- result = strategy._evaluate_candidate_immediately(candidate)
- expected = 0.5 - strategy.uncertainty_penalty
- assert abs(result - expected) < 0.01
-
-
-# --- Early stop ---
-
-
-class TestEarlyStop:
- def test_high_score_triggers_early_stop(self, strategy):
- candidate = MagicMock()
- candidate.name = "Champion"
- strategy.early_stop_threshold = 0.9
-
- c1 = make_constraint(ConstraintType.PROPERTY, "test", weight=1.0)
- strategy.constraint_ranking = [c1]
-
- evidence = [MagicMock()]
- strategy._gather_evidence_for_constraint = MagicMock(
- return_value=evidence
- )
-
- dual_ev = make_mock_evidence(
- positive=0.9, negative=0.05, uncertainty=0.05
- )
- strategy._analyze_evidence_dual_confidence = MagicMock(
- return_value=dual_ev
- )
- strategy._evaluate_evidence = MagicMock(return_value=0.95)
-
- strategy._evaluate_candidate_immediately(candidate)
- assert strategy.found_answer.is_set()
-
- def test_low_score_no_early_stop(self, strategy):
- candidate = MagicMock()
- candidate.name = "Mediocre"
-
- c1 = make_constraint(ConstraintType.PROPERTY, "test", weight=1.0)
- strategy.constraint_ranking = [c1]
-
- evidence = [MagicMock()]
- strategy._gather_evidence_for_constraint = MagicMock(
- return_value=evidence
- )
-
- dual_ev = make_mock_evidence(
- positive=0.5, negative=0.1, uncertainty=0.4
- )
- strategy._analyze_evidence_dual_confidence = MagicMock(
- return_value=dual_ev
- )
- strategy._evaluate_evidence = MagicMock(return_value=0.5)
-
- strategy._evaluate_candidate_immediately(candidate)
- assert not strategy.found_answer.is_set()
diff --git a/tests/advanced_search_system/strategies/test_dual_confidence_strategy.py b/tests/advanced_search_system/strategies/test_dual_confidence_strategy.py
deleted file mode 100644
index 9e311152e1..0000000000
--- a/tests/advanced_search_system/strategies/test_dual_confidence_strategy.py
+++ /dev/null
@@ -1,662 +0,0 @@
-"""
-Tests for DualConfidenceStrategy.
-
-Tests cover:
-- Initialization and inheritance
-- Dual confidence scoring
-- Evidence analysis
-- Score extraction
-- Error handling
-"""
-
-from unittest.mock import Mock, patch
-
-
-class TestConstraintEvidence:
- """Tests for ConstraintEvidence dataclass."""
-
- def test_create_constraint_evidence(self):
- """Create constraint evidence with all fields."""
- from local_deep_research.advanced_search_system.strategies.dual_confidence_strategy import (
- ConstraintEvidence,
- )
-
- evidence = ConstraintEvidence(
- positive_confidence=0.8,
- negative_confidence=0.1,
- uncertainty=0.1,
- evidence_text="Test evidence text",
- source="test_source",
- )
-
- assert evidence.positive_confidence == 0.8
- assert evidence.negative_confidence == 0.1
- assert evidence.uncertainty == 0.1
- assert evidence.evidence_text == "Test evidence text"
- assert evidence.source == "test_source"
-
-
-class TestDualConfidenceStrategyInit:
- """Tests for DualConfidenceStrategy initialization."""
-
- def test_init_inherits_from_smart_query(self):
- """Initialize inherits from SmartQueryStrategy."""
- from local_deep_research.advanced_search_system.strategies.dual_confidence_strategy import (
- DualConfidenceStrategy,
- )
- from local_deep_research.advanced_search_system.strategies.smart_query_strategy import (
- SmartQueryStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = DualConfidenceStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- assert isinstance(strategy, SmartQueryStrategy)
-
- def test_init_default_params(self):
- """Initialize with default parameters."""
- from local_deep_research.advanced_search_system.strategies.dual_confidence_strategy import (
- DualConfidenceStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = DualConfidenceStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- assert strategy.uncertainty_penalty == 0.2
- assert strategy.negative_weight == 0.5
-
- def test_init_custom_params(self):
- """Initialize with custom parameters."""
- from local_deep_research.advanced_search_system.strategies.dual_confidence_strategy import (
- DualConfidenceStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = DualConfidenceStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- uncertainty_penalty=0.3,
- negative_weight=0.7,
- )
-
- assert strategy.uncertainty_penalty == 0.3
- assert strategy.negative_weight == 0.7
-
-
-class TestEvaluateEvidence:
- """Tests for _evaluate_evidence method."""
-
- def test_evaluate_evidence_empty_list(self):
- """Evaluate evidence handles empty evidence list."""
- from local_deep_research.advanced_search_system.strategies.dual_confidence_strategy import (
- DualConfidenceStrategy,
- )
- from local_deep_research.advanced_search_system.constraints.base_constraint import (
- Constraint,
- ConstraintType,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = DualConfidenceStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- constraint = Constraint(
- id="1",
- type=ConstraintType.PROPERTY,
- value="test",
- description="Test",
- weight=0.5,
- )
-
- score = strategy._evaluate_evidence([], constraint)
-
- # No evidence means high uncertainty
- assert score == 0.5 - strategy.uncertainty_penalty
-
- def test_evaluate_evidence_with_list(self):
- """Evaluate evidence calculates score from evidence list."""
- from local_deep_research.advanced_search_system.strategies.dual_confidence_strategy import (
- DualConfidenceStrategy,
- )
- from local_deep_research.advanced_search_system.constraints.base_constraint import (
- Constraint,
- ConstraintType,
- )
-
- mock_search = Mock()
- mock_model = Mock()
- mock_model.invoke.return_value = Mock(
- content="POSITIVE: 0.8\nNEGATIVE: 0.1\nUNCERTAINTY: 0.1"
- )
-
- strategy = DualConfidenceStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- constraint = Constraint(
- id="1",
- type=ConstraintType.PROPERTY,
- value="test",
- description="Test",
- weight=0.5,
- )
-
- evidence_list = [{"text": "Test evidence text", "source": "search"}]
-
- score = strategy._evaluate_evidence(evidence_list, constraint)
-
- assert 0 <= score <= 1
-
-
-class TestAnalyzeEvidenceDualConfidence:
- """Tests for _analyze_evidence_dual_confidence method."""
-
- def test_analyze_evidence_parses_scores(self):
- """Analyze evidence parses LLM response scores."""
- from local_deep_research.advanced_search_system.strategies.dual_confidence_strategy import (
- DualConfidenceStrategy,
- )
- from local_deep_research.advanced_search_system.constraints.base_constraint import (
- Constraint,
- ConstraintType,
- )
-
- mock_search = Mock()
- mock_model = Mock()
- mock_model.invoke.return_value = Mock(
- content="POSITIVE: 0.7\nNEGATIVE: 0.2\nUNCERTAINTY: 0.1"
- )
-
- strategy = DualConfidenceStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- constraint = Constraint(
- id="1",
- type=ConstraintType.PROPERTY,
- value="test",
- description="Test",
- weight=0.5,
- )
-
- evidence = {"text": "Evidence text", "source": "search"}
-
- result = strategy._analyze_evidence_dual_confidence(
- evidence, constraint
- )
-
- assert hasattr(result, "positive_confidence")
- assert hasattr(result, "negative_confidence")
- assert hasattr(result, "uncertainty")
-
- def test_analyze_evidence_normalizes_scores(self):
- """Analyze evidence normalizes scores to sum to 1."""
- from local_deep_research.advanced_search_system.strategies.dual_confidence_strategy import (
- DualConfidenceStrategy,
- )
- from local_deep_research.advanced_search_system.constraints.base_constraint import (
- Constraint,
- ConstraintType,
- )
-
- mock_search = Mock()
- mock_model = Mock()
- mock_model.invoke.return_value = Mock(
- content="POSITIVE: 0.5\nNEGATIVE: 0.5\nUNCERTAINTY: 0.5"
- )
-
- strategy = DualConfidenceStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- constraint = Constraint(
- id="1",
- type=ConstraintType.PROPERTY,
- value="test",
- description="Test",
- weight=0.5,
- )
-
- evidence = {"text": "Evidence text", "source": "search"}
-
- result = strategy._analyze_evidence_dual_confidence(
- evidence, constraint
- )
-
- # Scores should be normalized to sum to approximately 1
- total = (
- result.positive_confidence
- + result.negative_confidence
- + result.uncertainty
- )
- assert 0.99 <= total <= 1.01
-
- def test_analyze_evidence_handles_error(self):
- """Analyze evidence handles LLM errors gracefully."""
- from local_deep_research.advanced_search_system.strategies.dual_confidence_strategy import (
- DualConfidenceStrategy,
- )
- from local_deep_research.advanced_search_system.constraints.base_constraint import (
- Constraint,
- ConstraintType,
- )
-
- mock_search = Mock()
- mock_model = Mock()
- mock_model.invoke.side_effect = Exception("LLM Error")
-
- strategy = DualConfidenceStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- constraint = Constraint(
- id="1",
- type=ConstraintType.PROPERTY,
- value="test",
- description="Test",
- weight=0.5,
- )
-
- evidence = {"text": "Evidence text", "source": "search"}
-
- result = strategy._analyze_evidence_dual_confidence(
- evidence, constraint
- )
-
- # Should default to high uncertainty
- assert result.uncertainty == 0.8
-
-
-class TestExtractScore:
- """Tests for _extract_score method."""
-
- def test_extract_score_finds_score(self):
- """Extract score finds score in text."""
- from local_deep_research.advanced_search_system.strategies.dual_confidence_strategy import (
- DualConfidenceStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = DualConfidenceStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- text = "POSITIVE: 0.85"
- score = strategy._extract_score(text, "POSITIVE")
-
- assert score == 0.85
-
- def test_extract_score_finds_bracketed(self):
- """Extract score finds bracketed score."""
- from local_deep_research.advanced_search_system.strategies.dual_confidence_strategy import (
- DualConfidenceStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = DualConfidenceStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- text = "POSITIVE: [0.75]"
- score = strategy._extract_score(text, "POSITIVE")
-
- assert score == 0.75
-
- def test_extract_score_not_found(self):
- """Extract score returns default when not found."""
- from local_deep_research.advanced_search_system.strategies.dual_confidence_strategy import (
- DualConfidenceStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = DualConfidenceStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- text = "No score here"
- score = strategy._extract_score(text, "POSITIVE")
-
- assert score == 0.1 # Default low score
-
- def test_extract_score_case_insensitive(self):
- """Extract score is case insensitive."""
- from local_deep_research.advanced_search_system.strategies.dual_confidence_strategy import (
- DualConfidenceStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = DualConfidenceStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- text = "positive: 0.65"
- score = strategy._extract_score(text, "POSITIVE")
-
- assert score == 0.65
-
- def test_extract_score_returns_default_for_non_numeric_match(self):
- """Extract score returns default when regex matches but float() fails (PR #2020).
-
- PR #2020 changed bare `except:` to `except ValueError:` for float
- conversion errors in _extract_score.
- """
- from local_deep_research.advanced_search_system.strategies.dual_confidence_strategy import (
- DualConfidenceStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = DualConfidenceStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- # No numeric match for POSITIVE label
- text = "POSITIVE: invalid"
- score = strategy._extract_score(text, "POSITIVE")
-
- assert score == 0.1 # Default low score
-
- def test_extract_score_returns_default_for_empty_input(self):
- """Extract score returns default for empty input."""
- from local_deep_research.advanced_search_system.strategies.dual_confidence_strategy import (
- DualConfidenceStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = DualConfidenceStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- score = strategy._extract_score("", "POSITIVE")
- assert score == 0.1
-
-
-class TestGatherEvidenceForConstraint:
- """Tests for _gather_evidence_for_constraint method."""
-
- def test_gather_evidence_creates_queries(self):
- """Gather evidence creates targeted queries."""
- from local_deep_research.advanced_search_system.strategies.dual_confidence_strategy import (
- DualConfidenceStrategy,
- )
- from local_deep_research.advanced_search_system.candidates.base_candidate import (
- Candidate,
- )
- from local_deep_research.advanced_search_system.constraints.base_constraint import (
- Constraint,
- ConstraintType,
- )
-
- mock_search = Mock()
- mock_search.run.return_value = [{"snippet": "Test result"}]
- mock_model = Mock()
- mock_model.invoke.return_value = Mock(content="Test response")
-
- strategy = DualConfidenceStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
- strategy.searched_queries = set()
- strategy.use_direct_search = True
-
- candidate = Candidate(name="Test Entity")
- constraint = Constraint(
- id="1",
- type=ConstraintType.PROPERTY,
- value="has feature",
- description="Test constraint",
- weight=0.5,
- )
-
- # Mock _execute_search
- with patch.object(
- strategy,
- "_execute_search",
- return_value={"current_knowledge": "Test content"},
- ):
- evidence = strategy._gather_evidence_for_constraint(
- candidate, constraint
- )
-
- assert isinstance(evidence, list)
-
- def test_gather_evidence_includes_negative_queries(self):
- """Gather evidence includes negative queries for properties."""
- from local_deep_research.advanced_search_system.strategies.dual_confidence_strategy import (
- DualConfidenceStrategy,
- )
- from local_deep_research.advanced_search_system.candidates.base_candidate import (
- Candidate,
- )
- from local_deep_research.advanced_search_system.constraints.base_constraint import (
- Constraint,
- ConstraintType,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = DualConfidenceStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
- strategy.searched_queries = set()
-
- candidate = Candidate(name="Test Entity")
- constraint = Constraint(
- id="1",
- type=ConstraintType.PROPERTY,
- value="feature",
- description="Test property",
- weight=0.5,
- )
-
- # The method should build queries including negative ones
- # We can check this by looking at what queries would be built
- # For property constraints, it should include NOT queries
- # Just verify the method exists and runs without error
- with patch.object(
- strategy,
- "_execute_search",
- return_value={"current_knowledge": ""},
- ):
- evidence = strategy._gather_evidence_for_constraint(
- candidate, constraint
- )
-
- assert isinstance(evidence, list)
-
-
-class TestScoreCalculation:
- """Tests for score calculation logic."""
-
- def test_score_high_positive_low_negative(self):
- """High positive and low negative gives high score."""
- from local_deep_research.advanced_search_system.strategies.dual_confidence_strategy import (
- DualConfidenceStrategy,
- ConstraintEvidence,
- )
- from local_deep_research.advanced_search_system.constraints.base_constraint import (
- Constraint,
- ConstraintType,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = DualConfidenceStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- # Manually calculate expected score
- # score = avg_positive - (avg_negative * negative_weight) - (avg_uncertainty * uncertainty_penalty)
- # With positive=0.8, negative=0.1, uncertainty=0.1
- # score = 0.8 - (0.1 * 0.5) - (0.1 * 0.2) = 0.8 - 0.05 - 0.02 = 0.73
-
- constraint = Constraint(
- id="1",
- type=ConstraintType.PROPERTY,
- value="test",
- description="Test",
- weight=0.5,
- )
-
- with patch.object(
- strategy,
- "_analyze_evidence_dual_confidence",
- return_value=ConstraintEvidence(
- positive_confidence=0.8,
- negative_confidence=0.1,
- uncertainty=0.1,
- evidence_text="test",
- source="test",
- ),
- ):
- evidence_list = [{"text": "test", "source": "test"}]
- score = strategy._evaluate_evidence(evidence_list, constraint)
-
- assert score > 0.5 # Should be relatively high
-
- def test_score_low_positive_high_negative(self):
- """Low positive and high negative gives low score."""
- from local_deep_research.advanced_search_system.strategies.dual_confidence_strategy import (
- DualConfidenceStrategy,
- ConstraintEvidence,
- )
- from local_deep_research.advanced_search_system.constraints.base_constraint import (
- Constraint,
- ConstraintType,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = DualConfidenceStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- constraint = Constraint(
- id="1",
- type=ConstraintType.PROPERTY,
- value="test",
- description="Test",
- weight=0.5,
- )
-
- with patch.object(
- strategy,
- "_analyze_evidence_dual_confidence",
- return_value=ConstraintEvidence(
- positive_confidence=0.1,
- negative_confidence=0.8,
- uncertainty=0.1,
- evidence_text="test",
- source="test",
- ),
- ):
- evidence_list = [{"text": "test", "source": "test"}]
- score = strategy._evaluate_evidence(evidence_list, constraint)
-
- assert score < 0.5 # Should be relatively low
-
-
-class TestErrorHandling:
- """Tests for error handling."""
-
- def test_analyze_evidence_invalid_response(self):
- """Analyze evidence handles invalid LLM response."""
- from local_deep_research.advanced_search_system.strategies.dual_confidence_strategy import (
- DualConfidenceStrategy,
- )
- from local_deep_research.advanced_search_system.constraints.base_constraint import (
- Constraint,
- ConstraintType,
- )
-
- mock_search = Mock()
- mock_model = Mock()
- mock_model.invoke.return_value = Mock(
- content="Invalid response with no scores"
- )
-
- strategy = DualConfidenceStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- constraint = Constraint(
- id="1",
- type=ConstraintType.PROPERTY,
- value="test",
- description="Test",
- weight=0.5,
- )
-
- evidence = {"text": "Evidence text", "source": "search"}
-
- result = strategy._analyze_evidence_dual_confidence(
- evidence, constraint
- )
-
- # Should still return valid ConstraintEvidence
- assert hasattr(result, "positive_confidence")
- assert hasattr(result, "negative_confidence")
- assert hasattr(result, "uncertainty")
diff --git a/tests/advanced_search_system/strategies/test_early_stop_high_value.py b/tests/advanced_search_system/strategies/test_early_stop_high_value.py
deleted file mode 100644
index fb01c7a32e..0000000000
--- a/tests/advanced_search_system/strategies/test_early_stop_high_value.py
+++ /dev/null
@@ -1,513 +0,0 @@
-"""
-High-value tests for EarlyStopConstrainedStrategy.
-
-Covers pure logic paths:
-- _extract_confidence_from_response: regex parsing, keyword fallback, edge cases
-- _evaluate_evidence: averaging, empty evidence, missing confidence keys
-- Thread-safe tracking: evaluation_lock, found_answer Event, best_candidate updates
-- _evaluate_candidate_immediately: score accumulation, early critical failure, early stop trigger
-"""
-
-import threading
-from unittest.mock import MagicMock, Mock, patch
-
-
-from local_deep_research.advanced_search_system.strategies.early_stop_constrained_strategy import (
- EarlyStopConstrainedStrategy,
-)
-
-
-# ---------------------------------------------------------------------------
-# Helpers
-# ---------------------------------------------------------------------------
-
-
-def _make_strategy(early_stop_threshold=0.99, concurrent_evaluation=True):
- """Create an EarlyStopConstrainedStrategy with mocked dependencies."""
- model = MagicMock()
- search = MagicMock()
- strategy = EarlyStopConstrainedStrategy(
- model=model,
- search=search,
- all_links_of_system=[],
- early_stop_threshold=early_stop_threshold,
- concurrent_evaluation=concurrent_evaluation,
- )
- return strategy
-
-
-def _make_constraint(
- value="test constraint", weight=1.0, type_value="property"
-):
- """Create a mock Constraint object."""
- constraint = Mock()
- constraint.value = value
- constraint.weight = weight
- constraint.type = Mock()
- constraint.type.value = type_value
- return constraint
-
-
-def _make_candidate(name="TestCandidate"):
- """Create a mock Candidate object."""
- candidate = Mock()
- candidate.name = name
- return candidate
-
-
-# ---------------------------------------------------------------------------
-# _extract_confidence_from_response
-# ---------------------------------------------------------------------------
-
-
-class TestExtractConfidenceFromResponse:
- """Tests for regex-based confidence extraction with keyword fallback."""
-
- def test_extracts_decimal_number(self):
- strategy = _make_strategy()
- assert (
- strategy._extract_confidence_from_response("Confidence: 0.85")
- == 0.85
- )
-
- def test_extracts_last_number_when_multiple(self):
- """Uses the last numeric match found."""
- strategy = _make_strategy()
- result = strategy._extract_confidence_from_response(
- "Score is 0.3 but revised to 0.9"
- )
- assert result == 0.9
-
- def test_extracts_1_0(self):
- strategy = _make_strategy()
- assert (
- strategy._extract_confidence_from_response("Perfect match: 1.0")
- == 1.0
- )
-
- def test_extracts_bare_1(self):
- strategy = _make_strategy()
- assert strategy._extract_confidence_from_response("Score: 1") == 1.0
-
- def test_extracts_number_without_leading_zero(self):
- """Regex requires word boundary so bare '.75' does not match; falls back to keyword/default."""
- strategy = _make_strategy()
- # The regex \b0?\.\d+ requires word boundary before the optional 0
- # '.75' alone doesn't match, but '0.75' does
- assert (
- strategy._extract_confidence_from_response("Confidence 0.75")
- == 0.75
- )
-
- def test_keyword_definitely_returns_0_9(self):
- strategy = _make_strategy()
- assert (
- strategy._extract_confidence_from_response(
- "This is definitely the answer"
- )
- == 0.9
- )
-
- def test_keyword_certainly_returns_0_9(self):
- strategy = _make_strategy()
- assert (
- strategy._extract_confidence_from_response("I certainly believe so")
- == 0.9
- )
-
- def test_keyword_absolutely_returns_0_9(self):
- strategy = _make_strategy()
- assert (
- strategy._extract_confidence_from_response("Absolutely correct")
- == 0.9
- )
-
- def test_keyword_likely_returns_0_7(self):
- strategy = _make_strategy()
- assert (
- strategy._extract_confidence_from_response("This is likely correct")
- == 0.7
- )
-
- def test_keyword_probably_returns_0_7(self):
- strategy = _make_strategy()
- assert (
- strategy._extract_confidence_from_response(
- "Probably the right answer"
- )
- == 0.7
- )
-
- def test_keyword_appears_returns_0_7(self):
- strategy = _make_strategy()
- assert (
- strategy._extract_confidence_from_response(
- "It appears to be correct"
- )
- == 0.7
- )
-
- def test_keyword_possibly_returns_0_5(self):
- strategy = _make_strategy()
- assert (
- strategy._extract_confidence_from_response("Possibly the answer")
- == 0.5
- )
-
- def test_keyword_maybe_returns_0_5(self):
- strategy = _make_strategy()
- assert (
- strategy._extract_confidence_from_response("Maybe it could be this")
- == 0.5
- )
-
- def test_keyword_might_returns_0_5(self):
- strategy = _make_strategy()
- assert (
- strategy._extract_confidence_from_response("It might be correct")
- == 0.5
- )
-
- def test_keyword_unlikely_matches_likely_first(self):
- """'unlikely' contains 'likely' substring, so 'likely' keyword matches first (0.7)."""
- strategy = _make_strategy()
- assert (
- strategy._extract_confidence_from_response("This is unlikely")
- == 0.7
- )
-
- def test_keyword_doubtful_returns_0_3(self):
- strategy = _make_strategy()
- assert (
- strategy._extract_confidence_from_response("It is doubtful") == 0.3
- )
-
- def test_keyword_not_returns_0_3(self):
- strategy = _make_strategy()
- assert (
- strategy._extract_confidence_from_response("This is not the answer")
- == 0.3
- )
-
- def test_no_number_no_keyword_returns_0_5(self):
- strategy = _make_strategy()
- assert (
- strategy._extract_confidence_from_response(
- "Some generic response with no indicators"
- )
- == 0.5
- )
-
- def test_empty_string_returns_0_5(self):
- strategy = _make_strategy()
- assert strategy._extract_confidence_from_response("") == 0.5
-
- def test_keyword_priority_high_confidence_first(self):
- """'definitely' keyword is checked before 'likely'."""
- strategy = _make_strategy()
- # The function checks keywords in order; 'definitely' matches first
- assert (
- strategy._extract_confidence_from_response(
- "This is definitely and likely correct"
- )
- == 0.9
- )
-
- def test_number_takes_priority_over_keywords(self):
- """When a number is present, it wins over keyword matching."""
- strategy = _make_strategy()
- result = strategy._extract_confidence_from_response(
- "Definitely the answer with confidence 0.42"
- )
- assert result == 0.42
-
- def test_case_insensitive_keywords(self):
- strategy = _make_strategy()
- assert (
- strategy._extract_confidence_from_response("DEFINITELY yes") == 0.9
- )
-
-
-# ---------------------------------------------------------------------------
-# _evaluate_evidence
-# ---------------------------------------------------------------------------
-
-
-class TestEvaluateEvidence:
- """Tests for evidence evaluation scoring."""
-
- def test_empty_evidence_returns_zero(self):
- strategy = _make_strategy()
- constraint = _make_constraint()
- assert strategy._evaluate_evidence([], constraint) == 0.0
-
- def test_single_evidence_returns_its_confidence(self):
- strategy = _make_strategy()
- constraint = _make_constraint()
- evidence = [{"confidence": 0.8, "text": "supports"}]
- assert strategy._evaluate_evidence(evidence, constraint) == 0.8
-
- def test_averages_multiple_evidence_confidences(self):
- strategy = _make_strategy()
- constraint = _make_constraint()
- evidence = [
- {"confidence": 0.6},
- {"confidence": 0.8},
- {"confidence": 1.0},
- ]
- result = strategy._evaluate_evidence(evidence, constraint)
- assert abs(result - 0.8) < 0.001
-
- def test_missing_confidence_defaults_to_0_5(self):
- strategy = _make_strategy()
- constraint = _make_constraint()
- evidence = [
- {"text": "no confidence key"},
- {"confidence": 0.9},
- ]
- result = strategy._evaluate_evidence(evidence, constraint)
- assert abs(result - 0.7) < 0.001 # (0.5 + 0.9) / 2
-
- def test_all_missing_confidence_returns_0_5(self):
- strategy = _make_strategy()
- constraint = _make_constraint()
- evidence = [{"text": "a"}, {"text": "b"}]
- result = strategy._evaluate_evidence(evidence, constraint)
- assert result == 0.5
-
-
-# ---------------------------------------------------------------------------
-# Thread-safe tracking
-# ---------------------------------------------------------------------------
-
-
-class TestThreadSafeTracking:
- """Tests for thread-safe best_candidate and found_answer tracking."""
-
- def test_initial_state(self):
- strategy = _make_strategy()
- assert strategy.best_candidate is None
- assert strategy.best_score == 0.0
- assert not strategy.found_answer.is_set()
- assert strategy.evaluated_candidates == {}
- assert strategy.evaluating_candidates == set()
-
- def test_evaluation_lock_is_threading_lock(self):
- strategy = _make_strategy()
- assert isinstance(strategy.evaluation_lock, type(threading.Lock()))
-
- def test_found_answer_is_threading_event(self):
- strategy = _make_strategy()
- assert isinstance(strategy.found_answer, threading.Event)
-
- def test_early_stop_threshold_stored(self):
- strategy = _make_strategy(early_stop_threshold=0.95)
- assert strategy.early_stop_threshold == 0.95
-
- def test_concurrent_evaluation_flag(self):
- strategy = _make_strategy(concurrent_evaluation=False)
- assert strategy.concurrent_evaluation is False
-
-
-# ---------------------------------------------------------------------------
-# _evaluate_candidate_immediately
-# ---------------------------------------------------------------------------
-
-
-class TestEvaluateCandidateImmediately:
- """Tests for immediate candidate evaluation against constraints."""
-
- def test_returns_zero_on_exception(self):
- """If evaluation throws, returns 0.0."""
- strategy = _make_strategy()
- strategy.constraint_ranking = [_make_constraint()]
- strategy._gather_evidence_for_constraint = Mock(
- side_effect=Exception("fail")
- )
- candidate = _make_candidate("FailCandidate")
-
- score = strategy._evaluate_candidate_immediately(candidate)
- assert score == 0.0
-
- def test_updates_best_candidate_on_higher_score(self):
- """Candidate with higher score replaces best_candidate."""
- strategy = _make_strategy()
- strategy.constraint_ranking = [_make_constraint(weight=0.5)]
- strategy._gather_evidence_for_constraint = Mock(
- return_value=[{"confidence": 0.85}]
- )
- strategy._evaluate_evidence = Mock(return_value=0.85)
-
- candidate = _make_candidate("GoodCandidate")
- score = strategy._evaluate_candidate_immediately(candidate)
-
- assert score == 0.85
- assert strategy.best_candidate == "GoodCandidate"
- assert strategy.best_score == 0.85
- assert strategy.evaluated_candidates["GoodCandidate"] == 0.85
-
- def test_does_not_replace_higher_score_candidate(self):
- """Lower score candidate does not replace existing best."""
- strategy = _make_strategy()
- strategy.best_score = 0.9
- strategy.best_candidate = "BetterCandidate"
- strategy.constraint_ranking = [_make_constraint(weight=0.5)]
- strategy._gather_evidence_for_constraint = Mock(
- return_value=[{"confidence": 0.5}]
- )
- strategy._evaluate_evidence = Mock(return_value=0.5)
-
- candidate = _make_candidate("WeakCandidate")
- score = strategy._evaluate_candidate_immediately(candidate)
-
- assert score == 0.5
- assert strategy.best_candidate == "BetterCandidate"
- assert strategy.best_score == 0.9
-
- def test_triggers_early_stop_at_threshold(self):
- """Score >= early_stop_threshold sets the found_answer Event."""
- strategy = _make_strategy(early_stop_threshold=0.8)
- strategy.constraint_ranking = [_make_constraint(weight=0.5)]
- strategy._gather_evidence_for_constraint = Mock(
- return_value=[{"confidence": 0.95}]
- )
- strategy._evaluate_evidence = Mock(return_value=0.95)
-
- candidate = _make_candidate("PerfectCandidate")
- strategy._evaluate_candidate_immediately(candidate)
-
- assert strategy.found_answer.is_set()
- assert strategy.best_candidate == "PerfectCandidate"
-
- def test_does_not_trigger_early_stop_below_threshold(self):
- strategy = _make_strategy(early_stop_threshold=0.99)
- strategy.constraint_ranking = [_make_constraint(weight=0.5)]
- strategy._gather_evidence_for_constraint = Mock(
- return_value=[{"confidence": 0.8}]
- )
- strategy._evaluate_evidence = Mock(return_value=0.8)
-
- candidate = _make_candidate("OkCandidate")
- strategy._evaluate_candidate_immediately(candidate)
-
- assert not strategy.found_answer.is_set()
-
- def test_early_critical_failure_skips_remaining_constraints(self):
- """Score < 0.3 on high-weight constraint skips remaining checks."""
- strategy = _make_strategy()
- c1 = _make_constraint(value="critical", weight=0.9)
- c2 = _make_constraint(value="secondary", weight=0.5)
- strategy.constraint_ranking = [c1, c2]
-
- call_count = 0
-
- def mock_gather(candidate, constraint):
- nonlocal call_count
- call_count += 1
- return [{"confidence": 0.1}]
-
- strategy._gather_evidence_for_constraint = mock_gather
- strategy._evaluate_evidence = Mock(return_value=0.1)
-
- candidate = _make_candidate("BadCandidate")
- score = strategy._evaluate_candidate_immediately(candidate)
-
- # Only the first constraint should have been checked (early break)
- assert call_count == 1
- # Score should be based on only the first constraint
- assert score == 0.1
-
- def test_averages_across_all_constraints_when_no_early_break(self):
- """When no early failure, averages scores across all constraints."""
- strategy = _make_strategy()
- c1 = _make_constraint(value="first", weight=0.5)
- c2 = _make_constraint(value="second", weight=0.5)
- strategy.constraint_ranking = [c1, c2]
-
- scores = iter([0.6, 0.8])
- strategy._gather_evidence_for_constraint = Mock(
- return_value=[{"confidence": 0.7}]
- )
- strategy._evaluate_evidence = Mock(
- side_effect=lambda e, c: next(scores)
- )
-
- candidate = _make_candidate("MediumCandidate")
- score = strategy._evaluate_candidate_immediately(candidate)
-
- assert abs(score - 0.7) < 0.001 # (0.6 + 0.8) / 2
-
- def test_no_constraints_returns_zero(self):
- """With no constraints, score is 0.0."""
- strategy = _make_strategy()
- strategy.constraint_ranking = []
-
- candidate = _make_candidate("NoConstraints")
- score = strategy._evaluate_candidate_immediately(candidate)
- assert score == 0.0
-
- def test_progress_callback_called_per_constraint(self):
- """Progress callback is called for each constraint evaluation."""
- strategy = _make_strategy()
- callback = Mock()
- strategy.progress_callback = callback
- strategy.constraint_ranking = [
- _make_constraint(value="c1", weight=0.5),
- _make_constraint(value="c2", weight=0.5),
- ]
- strategy._gather_evidence_for_constraint = Mock(
- return_value=[{"confidence": 0.7}]
- )
- strategy._evaluate_evidence = Mock(return_value=0.7)
-
- candidate = _make_candidate("CallbackTest")
- strategy._evaluate_candidate_immediately(candidate)
-
- assert callback.call_count == 2
-
-
-# ---------------------------------------------------------------------------
-# analyze_topic additions
-# ---------------------------------------------------------------------------
-
-
-class TestAnalyzeTopicEarlyStop:
- """Tests that analyze_topic adds early stopping metadata."""
-
- def test_analyze_topic_adds_early_stop_fields(self):
- """Result dict includes early_stopped, evaluated_candidates, best_candidate, best_score."""
- strategy = _make_strategy()
- # Mock parent's analyze_topic to return a base result
- with patch(
- "local_deep_research.advanced_search_system.strategies.early_stop_constrained_strategy.ParallelConstrainedStrategy.analyze_topic",
- return_value={"findings": [], "current_knowledge": "test"},
- ):
- result = strategy.analyze_topic("test query")
-
- assert "early_stopped" in result
- assert "evaluated_candidates" in result
- assert "best_candidate" in result
- assert "best_score" in result
-
- def test_early_stopped_reflects_found_answer(self):
- strategy = _make_strategy()
- strategy.found_answer.set()
-
- with patch(
- "local_deep_research.advanced_search_system.strategies.early_stop_constrained_strategy.ParallelConstrainedStrategy.analyze_topic",
- return_value={},
- ):
- result = strategy.analyze_topic("test")
-
- assert result["early_stopped"] is True
-
- def test_not_early_stopped_when_answer_not_found(self):
- strategy = _make_strategy()
-
- with patch(
- "local_deep_research.advanced_search_system.strategies.early_stop_constrained_strategy.ParallelConstrainedStrategy.analyze_topic",
- return_value={},
- ):
- result = strategy.analyze_topic("test")
-
- assert result["early_stopped"] is False
diff --git a/tests/advanced_search_system/strategies/test_evidence_based_pure_logic.py b/tests/advanced_search_system/strategies/test_evidence_based_pure_logic.py
deleted file mode 100644
index 9a235c92dc..0000000000
--- a/tests/advanced_search_system/strategies/test_evidence_based_pure_logic.py
+++ /dev/null
@@ -1,210 +0,0 @@
-"""
-Pure-logic tests for EvidenceBasedStrategy.
-
-Tests _has_sufficient_answer (threshold + critical constraint checks) and
-_get_distinctive_constraints (priority-indexed sort with naming guarantee)
-— no LLM or search calls.
-"""
-
-from unittest.mock import Mock
-
-from local_deep_research.advanced_search_system.candidates.base_candidate import (
- Candidate,
-)
-from local_deep_research.advanced_search_system.constraints.base_constraint import (
- Constraint,
- ConstraintType,
-)
-from local_deep_research.advanced_search_system.evidence.base_evidence import (
- Evidence,
- EvidenceType,
-)
-from local_deep_research.advanced_search_system.strategies.evidence_based_strategy import (
- EvidenceBasedStrategy,
-)
-
-
-def _constraint(id, ctype=ConstraintType.PROPERTY, weight=1.0, value="v"):
- return Constraint(
- id=id,
- type=ctype,
- description="",
- value=value,
- weight=weight,
- )
-
-
-def _evidence(confidence=0.8):
- return Evidence(
- claim="test",
- type=EvidenceType.DIRECT_STATEMENT,
- source="test",
- confidence=confidence,
- )
-
-
-def _make_strategy(
- candidates=None,
- constraints=None,
- confidence_threshold=0.85,
- evidence_threshold=0.6,
-):
- """Build a minimal Mock with the attributes used by pure-logic methods."""
- s = Mock(spec=[])
- s.candidates = candidates or []
- s.constraints = constraints or []
- s.confidence_threshold = confidence_threshold
- s.evidence_threshold = evidence_threshold
- return s
-
-
-# ---------------------------------------------------------------------------
-# _has_sufficient_answer
-# ---------------------------------------------------------------------------
-
-
-class TestHasSufficientAnswer:
- """Verify sufficient-answer determination: score threshold + critical evidence."""
-
- def test_no_candidates(self):
- """No candidates -> False."""
- s = _make_strategy(candidates=[])
- assert EvidenceBasedStrategy._has_sufficient_answer(s) is False
-
- def test_top_candidate_below_threshold(self):
- """Top candidate score below confidence_threshold -> False."""
- c = Candidate(name="X", score=0.5)
- s = _make_strategy(candidates=[c])
- assert EvidenceBasedStrategy._has_sufficient_answer(s) is False
-
- def test_passes_with_all_critical_evidence(self):
- """High score + all critical constraints have strong evidence -> True."""
- c = Candidate(name="X", score=0.9)
- con = _constraint("c1", weight=0.9)
- c.add_evidence("c1", _evidence(confidence=0.7))
- s = _make_strategy(
- candidates=[c],
- constraints=[con],
- confidence_threshold=0.85,
- evidence_threshold=0.6,
- )
- assert EvidenceBasedStrategy._has_sufficient_answer(s) is True
-
- def test_fails_with_weak_critical_evidence(self):
- """High score but critical constraint evidence below threshold -> False."""
- c = Candidate(name="X", score=0.9)
- con = _constraint("c1", weight=0.9)
- c.add_evidence("c1", _evidence(confidence=0.3)) # Below 0.6
- s = _make_strategy(
- candidates=[c],
- constraints=[con],
- confidence_threshold=0.85,
- evidence_threshold=0.6,
- )
- assert EvidenceBasedStrategy._has_sufficient_answer(s) is False
-
- def test_fails_with_missing_critical_evidence(self):
- """High score but critical constraint has no evidence -> False."""
- c = Candidate(name="X", score=0.9)
- con = _constraint("c1", weight=0.9)
- s = _make_strategy(
- candidates=[c],
- constraints=[con],
- confidence_threshold=0.85,
- evidence_threshold=0.6,
- )
- assert EvidenceBasedStrategy._has_sufficient_answer(s) is False
-
- def test_non_critical_constraints_ignored(self):
- """Constraints with weight < 0.8 don't block sufficiency."""
- c = Candidate(name="X", score=0.9)
- critical = _constraint("c1", weight=0.9)
- non_critical = _constraint("c2", weight=0.5)
- c.add_evidence("c1", _evidence(confidence=0.8))
- # c2 has no evidence but weight < 0.8
- s = _make_strategy(
- candidates=[c],
- constraints=[critical, non_critical],
- )
- assert EvidenceBasedStrategy._has_sufficient_answer(s) is True
-
- def test_multiple_critical_all_needed(self):
- """All critical constraints must have sufficient evidence."""
- c = Candidate(name="X", score=0.9)
- c1 = _constraint("c1", weight=0.9)
- c2 = _constraint("c2", weight=0.85)
- c.add_evidence("c1", _evidence(confidence=0.8))
- # c2 missing evidence
- s = _make_strategy(candidates=[c], constraints=[c1, c2])
- assert EvidenceBasedStrategy._has_sufficient_answer(s) is False
-
-
-# ---------------------------------------------------------------------------
-# _get_distinctive_constraints
-# ---------------------------------------------------------------------------
-
-
-class TestGetDistinctiveConstraints:
- """Verify priority-sorted constraint selection with naming guarantee."""
-
- def test_priority_order(self):
- """NAME_PATTERN > LOCATION > EVENT > STATISTIC > PROPERTY > TEMPORAL."""
- constraints = [
- _constraint("prop", ConstraintType.PROPERTY),
- _constraint("name", ConstraintType.NAME_PATTERN),
- _constraint("loc", ConstraintType.LOCATION),
- _constraint("evt", ConstraintType.EVENT),
- ]
- s = _make_strategy(constraints=constraints)
- result = EvidenceBasedStrategy._get_distinctive_constraints(s)
- ids = [c.id for c in result]
- # Top 3 by priority: NAME_PATTERN, LOCATION, EVENT
- assert ids == ["name", "loc", "evt"]
-
- def test_returns_max_three(self):
- """At most 3 constraints returned."""
- constraints = [
- _constraint(f"c{i}", ConstraintType.PROPERTY) for i in range(5)
- ]
- s = _make_strategy(constraints=constraints)
- result = EvidenceBasedStrategy._get_distinctive_constraints(s)
- assert len(result) == 3
-
- def test_naming_guarantee(self):
- """If top 3 lack NAME_PATTERN/LOCATION, one is swapped in."""
- constraints = [
- _constraint("stat", ConstraintType.STATISTIC),
- _constraint("evt", ConstraintType.EVENT),
- _constraint("prop", ConstraintType.PROPERTY),
- _constraint("loc", ConstraintType.LOCATION), # 4th by priority
- ]
- s = _make_strategy(constraints=constraints)
- result = EvidenceBasedStrategy._get_distinctive_constraints(s)
- # Location should be swapped in for the least important (property)
- ids = [c.id for c in result]
- assert "loc" in ids
-
- def test_naming_already_present(self):
- """No swap needed if NAME_PATTERN already in top 3."""
- constraints = [
- _constraint("name", ConstraintType.NAME_PATTERN),
- _constraint("stat", ConstraintType.STATISTIC),
- _constraint("evt", ConstraintType.EVENT),
- _constraint("prop", ConstraintType.PROPERTY),
- ]
- s = _make_strategy(constraints=constraints)
- result = EvidenceBasedStrategy._get_distinctive_constraints(s)
- ids = [c.id for c in result]
- assert ids == ["name", "evt", "stat"]
-
- def test_weight_tiebreaker(self):
- """Within same type, higher weight comes first."""
- constraints = [
- _constraint("p1", ConstraintType.PROPERTY, weight=0.5),
- _constraint("p2", ConstraintType.PROPERTY, weight=0.9),
- _constraint("p3", ConstraintType.PROPERTY, weight=0.7),
- ]
- s = _make_strategy(constraints=constraints)
- result = EvidenceBasedStrategy._get_distinctive_constraints(s)
- ids = [c.id for c in result]
- assert ids == ["p2", "p3", "p1"]
diff --git a/tests/advanced_search_system/strategies/test_evidence_based_strategy.py b/tests/advanced_search_system/strategies/test_evidence_based_strategy.py
deleted file mode 100644
index 8597c5a8f8..0000000000
--- a/tests/advanced_search_system/strategies/test_evidence_based_strategy.py
+++ /dev/null
@@ -1,718 +0,0 @@
-"""
-Tests for EvidenceBasedStrategy.
-
-Tests cover:
-- Initialization with dependencies
-- Constraint extraction
-- Candidate finding and scoring
-- Evidence gathering
-- Progress callbacks
-- Error handling
-"""
-
-from unittest.mock import Mock, patch
-
-
-class TestEvidenceBasedStrategyInit:
- """Tests for EvidenceBasedStrategy initialization."""
-
- def test_init_with_required_params(self):
- """Initialize with required parameters."""
- from local_deep_research.advanced_search_system.strategies.evidence_based_strategy import (
- EvidenceBasedStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = EvidenceBasedStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- assert strategy.model is mock_model
- assert strategy.search is mock_search
- assert strategy.max_iterations == 20
- assert strategy.confidence_threshold == 0.85
- assert strategy.candidate_limit == 10
-
- def test_init_with_custom_params(self):
- """Initialize with custom parameters."""
- from local_deep_research.advanced_search_system.strategies.evidence_based_strategy import (
- EvidenceBasedStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = EvidenceBasedStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- max_iterations=10,
- confidence_threshold=0.9,
- candidate_limit=5,
- evidence_threshold=0.7,
- )
-
- assert strategy.max_iterations == 10
- assert strategy.confidence_threshold == 0.9
- assert strategy.candidate_limit == 5
- assert strategy.evidence_threshold == 0.7
-
- def test_init_creates_components(self):
- """Initialize creates required components."""
- from local_deep_research.advanced_search_system.strategies.evidence_based_strategy import (
- EvidenceBasedStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = EvidenceBasedStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- assert strategy.constraint_analyzer is not None
- assert strategy.evidence_evaluator is not None
- assert strategy.findings_repository is not None
-
- def test_init_with_settings_snapshot(self):
- """Initialize with settings snapshot."""
- from local_deep_research.advanced_search_system.strategies.evidence_based_strategy import (
- EvidenceBasedStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
- settings = {
- "search.iterations": {"value": 5},
- }
-
- strategy = EvidenceBasedStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- settings_snapshot=settings,
- )
-
- assert strategy.settings_snapshot == settings
-
- def test_init_state_tracking(self):
- """Initialize state tracking lists."""
- from local_deep_research.advanced_search_system.strategies.evidence_based_strategy import (
- EvidenceBasedStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = EvidenceBasedStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- assert strategy.constraints == []
- assert strategy.candidates == []
- assert strategy.search_history == []
- assert strategy.iteration == 0
-
-
-class TestAnalyzeTopic:
- """Tests for analyze_topic method."""
-
- def test_analyze_topic_extracts_constraints(self):
- """Analyze topic extracts constraints from query."""
- from local_deep_research.advanced_search_system.strategies.evidence_based_strategy import (
- EvidenceBasedStrategy,
- )
-
- mock_search = Mock()
- mock_search.run.return_value = []
- mock_model = Mock()
- mock_model.invoke.return_value = Mock(content="Test response")
-
- strategy = EvidenceBasedStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- max_iterations=1,
- )
-
- # Mock constraint analyzer to return test constraints
- with patch.object(
- strategy.constraint_analyzer, "extract_constraints", return_value=[]
- ) as mock_extract:
- strategy.analyze_topic("test query about specific topic")
- mock_extract.assert_called_once_with(
- "test query about specific topic"
- )
-
- def test_analyze_topic_calls_progress_callback(self):
- """Analyze topic calls progress callback."""
- from local_deep_research.advanced_search_system.strategies.evidence_based_strategy import (
- EvidenceBasedStrategy,
- )
-
- mock_search = Mock()
- mock_search.run.return_value = []
- mock_model = Mock()
- mock_model.invoke.return_value = Mock(content="Test response")
-
- strategy = EvidenceBasedStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- max_iterations=1,
- )
-
- callback = Mock()
- strategy.set_progress_callback(callback)
-
- with patch.object(
- strategy.constraint_analyzer, "extract_constraints", return_value=[]
- ):
- strategy.analyze_topic("test query")
-
- assert callback.call_count >= 1
-
- def test_analyze_topic_returns_result_dict(self):
- """Analyze topic returns expected result structure."""
- from local_deep_research.advanced_search_system.strategies.evidence_based_strategy import (
- EvidenceBasedStrategy,
- )
-
- mock_search = Mock()
- mock_search.run.return_value = []
- mock_model = Mock()
- mock_model.invoke.return_value = Mock(content="Final answer")
-
- strategy = EvidenceBasedStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- max_iterations=1,
- )
-
- with patch.object(
- strategy.constraint_analyzer, "extract_constraints", return_value=[]
- ):
- result = strategy.analyze_topic("test query")
-
- assert isinstance(result, dict)
- assert "current_knowledge" in result
- assert "findings" in result
- assert "iterations" in result
- assert "strategy" in result
- assert result["strategy"] == "evidence_based"
-
-
-class TestConstraintHandling:
- """Tests for constraint handling methods."""
-
- def test_get_distinctive_constraints(self):
- """Get distinctive constraints prioritizes important types."""
- from local_deep_research.advanced_search_system.strategies.evidence_based_strategy import (
- EvidenceBasedStrategy,
- )
- from local_deep_research.advanced_search_system.constraints.base_constraint import (
- Constraint,
- ConstraintType,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = EvidenceBasedStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- # Create test constraints
- constraints = [
- Constraint(
- id="1",
- type=ConstraintType.PROPERTY,
- value="prop1",
- description="Property constraint",
- weight=0.5,
- ),
- Constraint(
- id="2",
- type=ConstraintType.LOCATION,
- value="loc1",
- description="Location constraint",
- weight=0.8,
- ),
- Constraint(
- id="3",
- type=ConstraintType.NAME_PATTERN,
- value="name1",
- description="Name pattern",
- weight=0.9,
- ),
- ]
- strategy.constraints = constraints
-
- distinctive = strategy._get_distinctive_constraints()
-
- # Name pattern should be prioritized
- assert len(distinctive) <= 3
-
- def test_create_candidate_search_query(self):
- """Create candidate search query from constraints."""
- from local_deep_research.advanced_search_system.strategies.evidence_based_strategy import (
- EvidenceBasedStrategy,
- )
- from local_deep_research.advanced_search_system.constraints.base_constraint import (
- Constraint,
- ConstraintType,
- )
-
- mock_search = Mock()
- mock_model = Mock()
- mock_model.invoke.return_value = Mock(content="search query result")
-
- strategy = EvidenceBasedStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- constraints = [
- Constraint(
- id="1",
- type=ConstraintType.PROPERTY,
- value="test value",
- description="Test constraint",
- weight=0.8,
- ),
- ]
-
- query = strategy._create_candidate_search_query(constraints)
-
- assert isinstance(query, str)
- assert len(query) > 0
-
-
-class TestCandidateHandling:
- """Tests for candidate handling methods."""
-
- def test_extract_candidates_from_results(self):
- """Extract candidates from search results."""
- from local_deep_research.advanced_search_system.strategies.evidence_based_strategy import (
- EvidenceBasedStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
- # First call for entity type, second for extraction
- mock_model.invoke.side_effect = [
- Mock(content="person"),
- Mock(content="CANDIDATE_1: John Smith\nCANDIDATE_2: Jane Doe"),
- ]
-
- strategy = EvidenceBasedStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- results = {
- "current_knowledge": "Information about John Smith and Jane Doe"
- }
-
- candidates = strategy._extract_candidates_from_results(
- results, "find person"
- )
-
- assert isinstance(candidates, list)
-
- def test_score_and_prune_candidates(self):
- """Score and prune candidates removes low scoring ones."""
- from local_deep_research.advanced_search_system.strategies.evidence_based_strategy import (
- EvidenceBasedStrategy,
- )
- from local_deep_research.advanced_search_system.candidates.base_candidate import (
- Candidate,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = EvidenceBasedStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- # Create candidates with different scores
- candidate1 = Candidate(name="High Score")
- candidate1.score = 0.9
- candidate2 = Candidate(name="Low Score")
- candidate2.score = 0.1
- candidate3 = Candidate(name="Medium Score")
- candidate3.score = 0.5
-
- strategy.candidates = [candidate1, candidate2, candidate3]
- strategy.constraints = []
-
- strategy._score_and_prune_candidates()
-
- # Candidates should be sorted by score
- assert strategy.candidates[0].name == "High Score"
-
- def test_has_sufficient_answer_no_candidates(self):
- """Has sufficient answer returns False with no candidates."""
- from local_deep_research.advanced_search_system.strategies.evidence_based_strategy import (
- EvidenceBasedStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = EvidenceBasedStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- strategy.candidates = []
-
- assert strategy._has_sufficient_answer() is False
-
- def test_has_sufficient_answer_high_score_candidate(self):
- """Has sufficient answer returns True with high scoring candidate."""
- from local_deep_research.advanced_search_system.strategies.evidence_based_strategy import (
- EvidenceBasedStrategy,
- )
- from local_deep_research.advanced_search_system.candidates.base_candidate import (
- Candidate,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = EvidenceBasedStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- confidence_threshold=0.8,
- )
-
- candidate = Candidate(name="Top Answer")
- candidate.score = 0.95
- strategy.candidates = [candidate]
- strategy.constraints = [] # No critical constraints
-
- assert strategy._has_sufficient_answer() is True
-
-
-class TestEvidenceGathering:
- """Tests for evidence gathering methods."""
-
- def test_gather_evidence_round_with_candidates(self):
- """Gather evidence round processes candidates."""
- from local_deep_research.advanced_search_system.strategies.evidence_based_strategy import (
- EvidenceBasedStrategy,
- )
- from local_deep_research.advanced_search_system.candidates.base_candidate import (
- Candidate,
- )
- from local_deep_research.advanced_search_system.constraints.base_constraint import (
- Constraint,
- ConstraintType,
- )
-
- mock_search = Mock()
- mock_search.run.return_value = []
- mock_model = Mock()
- mock_model.invoke.return_value = Mock(content="search query")
-
- strategy = EvidenceBasedStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- candidate = Candidate(name="Test Candidate")
- strategy.candidates = [candidate]
-
- constraint = Constraint(
- id="c1",
- type=ConstraintType.PROPERTY,
- value="test",
- description="Test constraint",
- weight=0.8,
- )
- strategy.constraints = [constraint]
-
- # Mock evidence evaluator
- with patch.object(
- strategy.evidence_evaluator,
- "extract_evidence",
- return_value=Mock(
- confidence=0.7, type=Mock(value="inference"), claim="Test claim"
- ),
- ):
- strategy._gather_evidence_round()
-
- assert len(candidate.evidence) > 0
-
- def test_calculate_evidence_coverage(self):
- """Calculate evidence coverage returns correct percentage."""
- from local_deep_research.advanced_search_system.strategies.evidence_based_strategy import (
- EvidenceBasedStrategy,
- )
- from local_deep_research.advanced_search_system.candidates.base_candidate import (
- Candidate,
- )
- from local_deep_research.advanced_search_system.constraints.base_constraint import (
- Constraint,
- ConstraintType,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = EvidenceBasedStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- # Create candidate with some evidence
- candidate = Candidate(name="Test")
- candidate.evidence = {"c1": Mock()}
- strategy.candidates = [candidate]
-
- constraint = Constraint(
- id="c1",
- type=ConstraintType.PROPERTY,
- value="test",
- description="Test",
- weight=0.5,
- )
- strategy.constraints = [constraint]
-
- coverage = strategy._calculate_evidence_coverage()
-
- assert 0 <= coverage <= 1.0
-
-
-class TestSearchExecution:
- """Tests for search execution methods."""
-
- def test_execute_search_direct_mode(self):
- """Execute search in direct mode."""
- from local_deep_research.advanced_search_system.strategies.evidence_based_strategy import (
- EvidenceBasedStrategy,
- )
-
- mock_search = Mock()
- mock_search.run.return_value = [
- {"title": "Result 1", "snippet": "Content 1"},
- {"title": "Result 2", "snippet": "Content 2"},
- ]
- mock_model = Mock()
-
- strategy = EvidenceBasedStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
- strategy.use_direct_search = True
-
- result = strategy._execute_search("test query")
-
- assert "current_knowledge" in result
- assert "findings" in result
- mock_search.run.assert_called_once_with("test query")
-
- def test_execute_search_updates_history(self):
- """Execute search updates search history."""
- from local_deep_research.advanced_search_system.strategies.evidence_based_strategy import (
- EvidenceBasedStrategy,
- )
-
- mock_search = Mock()
- mock_search.run.return_value = []
- mock_model = Mock()
-
- strategy = EvidenceBasedStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
- strategy.use_direct_search = True
-
- strategy._execute_search("test query")
-
- assert len(strategy.search_history) == 1
- assert strategy.search_history[0]["query"] == "test query"
-
-
-class TestFormattingMethods:
- """Tests for formatting helper methods."""
-
- def test_format_initial_analysis(self):
- """Format initial analysis creates readable output."""
- from local_deep_research.advanced_search_system.strategies.evidence_based_strategy import (
- EvidenceBasedStrategy,
- )
- from local_deep_research.advanced_search_system.constraints.base_constraint import (
- Constraint,
- ConstraintType,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = EvidenceBasedStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- constraint = Constraint(
- id="c1",
- type=ConstraintType.PROPERTY,
- value="test",
- description="Test constraint",
- weight=0.8,
- )
- strategy.constraints = [constraint]
-
- analysis = strategy._format_initial_analysis("test query")
-
- assert "test query" in analysis
- assert "Evidence-Based" in analysis
-
- def test_format_iteration_summary(self):
- """Format iteration summary shows candidate status."""
- from local_deep_research.advanced_search_system.strategies.evidence_based_strategy import (
- EvidenceBasedStrategy,
- )
- from local_deep_research.advanced_search_system.candidates.base_candidate import (
- Candidate,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = EvidenceBasedStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- candidate = Candidate(name="Test Candidate")
- candidate.score = 0.75
- strategy.candidates = [candidate]
- strategy.constraints = []
- strategy.iteration = 1
- strategy.max_iterations = 5
- strategy.search_history = []
-
- summary = strategy._format_iteration_summary()
-
- assert "Iteration 1" in summary
- assert "Test Candidate" in summary
-
- def test_format_evidence_summary_no_candidates(self):
- """Format evidence summary handles no candidates."""
- from local_deep_research.advanced_search_system.strategies.evidence_based_strategy import (
- EvidenceBasedStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = EvidenceBasedStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- strategy.candidates = []
-
- summary = strategy._format_evidence_summary()
-
- assert "No candidates found" in summary
-
-
-class TestHelperMethods:
- """Tests for utility helper methods."""
-
- def test_get_timestamp(self):
- """Get timestamp returns ISO format string."""
- from local_deep_research.advanced_search_system.strategies.evidence_based_strategy import (
- EvidenceBasedStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = EvidenceBasedStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- timestamp = strategy._get_timestamp()
-
- assert isinstance(timestamp, str)
- # ISO format should contain T separator
- assert "T" in timestamp
-
- def test_get_iteration_status_no_candidates(self):
- """Get iteration status with no candidates."""
- from local_deep_research.advanced_search_system.strategies.evidence_based_strategy import (
- EvidenceBasedStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = EvidenceBasedStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- strategy.candidates = []
-
- status = strategy._get_iteration_status()
-
- assert "initial candidates" in status.lower()
-
- def test_get_iteration_status_high_score(self):
- """Get iteration status with high scoring candidate."""
- from local_deep_research.advanced_search_system.strategies.evidence_based_strategy import (
- EvidenceBasedStrategy,
- )
- from local_deep_research.advanced_search_system.candidates.base_candidate import (
- Candidate,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = EvidenceBasedStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- candidate = Candidate(name="Top")
- candidate.score = 0.9
- strategy.candidates = [candidate]
-
- status = strategy._get_iteration_status()
-
- assert "verifying" in status.lower()
diff --git a/tests/advanced_search_system/strategies/test_evidence_based_v2.py b/tests/advanced_search_system/strategies/test_evidence_based_v2.py
deleted file mode 100644
index 369613a810..0000000000
--- a/tests/advanced_search_system/strategies/test_evidence_based_v2.py
+++ /dev/null
@@ -1,506 +0,0 @@
-"""
-Tests for evidence-based strategy v2 functionality.
-
-Tests cover:
-- Evidence claim extraction
-- Source verification
-- Confidence scoring
-- Contradiction detection
-"""
-
-
-class TestEvidenceClaimExtraction:
- """Tests for evidence claim extraction."""
-
- def test_evidence_claim_extraction(self):
- """Claims are extracted from sources."""
-
- claims = [
- "Climate change causes rising sea levels",
- "Rising sea levels lead to coastal flooding",
- ]
-
- assert len(claims) == 2
-
- def test_evidence_claim_deduplication(self):
- """Duplicate claims are removed."""
- claims = [
- "Climate change is real",
- "climate change is real",
- "Climate change is happening",
- ]
-
- unique_claims = list(set(c.lower() for c in claims))
-
- assert len(unique_claims) == 2
-
- def test_evidence_claim_categorization(self):
- """Claims are categorized by type."""
- claims = [
- {"text": "Study shows X", "type": "research"},
- {"text": "Experts say Y", "type": "opinion"},
- {"text": "Data indicates Z", "type": "data"},
- ]
-
- by_type = {}
- for claim in claims:
- t = claim["type"]
- if t not in by_type:
- by_type[t] = []
- by_type[t].append(claim)
-
- assert len(by_type) == 3
-
- def test_evidence_empty_source(self):
- """Empty sources return no claims."""
- source_text = ""
-
- if not source_text.strip():
- claims = []
- else:
- claims = ["some claim"]
-
- assert claims == []
-
-
-class TestSourceVerification:
- """Tests for source verification."""
-
- def test_evidence_source_verification(self):
- """Sources are verified for credibility."""
- sources = [
- {"url": "https://nature.com/article", "domain": "nature.com"},
- {
- "url": "https://random-blog.com/post",
- "domain": "random-blog.com",
- },
- ]
-
- trusted_domains = {"nature.com", "science.org", "gov.uk"}
-
- verified = [s for s in sources if s["domain"] in trusted_domains]
-
- assert len(verified) == 1
-
- def test_evidence_source_authority_scoring(self):
- """Sources are scored by authority."""
- authority_scores = {
- "nature.com": 0.95,
- "wikipedia.org": 0.75,
- "random-blog.com": 0.30,
- }
-
- domain = "nature.com"
- score = authority_scores.get(domain, 0.5)
-
- assert score == 0.95
-
- def test_evidence_source_recency_weighting(self):
- """Recent sources are weighted higher."""
- from datetime import datetime, timedelta
-
- now = datetime.now()
- sources = [
- {"date": now - timedelta(days=30), "score": 0.9},
- {"date": now - timedelta(days=365), "score": 0.9},
- {"date": now - timedelta(days=730), "score": 0.9},
- ]
-
- # Apply recency decay
- for source in sources:
- days_old = (now - source["date"]).days
- decay = max(0.5, 1.0 - (days_old / 365 * 0.3))
- source["adjusted_score"] = source["score"] * decay
-
- # Most recent should have highest score
- assert sources[0]["adjusted_score"] > sources[2]["adjusted_score"]
-
-
-class TestConfidenceScoring:
- """Tests for confidence scoring."""
-
- def test_evidence_confidence_scoring(self):
- """Claims are scored by confidence."""
- claim = {
- "text": "Climate change is accelerating",
- "sources": 5,
- "agreement_rate": 0.8,
- }
-
- confidence = claim["agreement_rate"] * min(1.0, claim["sources"] / 3)
-
- assert confidence >= 0.8
-
- def test_evidence_confidence_low_sources(self):
- """Low source count reduces confidence."""
- sources = 1
-
- source_factor = min(1.0, sources / 3)
-
- assert source_factor < 1.0
-
- def test_evidence_confidence_high_agreement(self):
- """High agreement increases confidence."""
- agreement_rate = 0.95
-
- confidence_boost = 1.0 + (agreement_rate - 0.5) * 0.2
-
- assert confidence_boost > 1.0
-
- def test_evidence_confidence_aggregation(self):
- """Confidence scores are aggregated."""
- claim_scores = [0.8, 0.9, 0.7, 0.85]
-
- avg_confidence = sum(claim_scores) / len(claim_scores)
-
- assert 0.8 <= avg_confidence <= 0.85
-
-
-class TestContradictionDetection:
- """Tests for contradiction detection."""
-
- def test_evidence_contradiction_detection(self):
- """Contradictions between claims are detected."""
- claims = [
- {"text": "X increases Y", "source": "source1"},
- {"text": "X decreases Y", "source": "source2"},
- ]
-
- # Simple contradiction detection
- contradictions = []
- if (
- "increases" in claims[0]["text"]
- and "decreases" in claims[1]["text"]
- ):
- if claims[0]["text"].split()[0] == claims[1]["text"].split()[0]:
- contradictions.append((claims[0], claims[1]))
-
- assert len(contradictions) == 1
-
- def test_evidence_contradiction_resolution(self):
- """Contradictions are resolved by source weight."""
- claims = [
- {"text": "X is true", "weight": 0.9},
- {"text": "X is false", "weight": 0.6},
- ]
-
- # Higher weight wins
- resolved = max(claims, key=lambda c: c["weight"])
-
- assert resolved["text"] == "X is true"
-
- def test_evidence_no_contradictions(self):
- """Non-contradictory claims pass through."""
-
- contradictions = [] # No overlap
-
- assert len(contradictions) == 0
-
-
-class TestConsensusAnalysis:
- """Tests for consensus analysis."""
-
- def test_evidence_consensus_analysis(self):
- """Consensus among sources is analyzed."""
- source_opinions = [
- {"position": "agree"},
- {"position": "agree"},
- {"position": "agree"},
- {"position": "disagree"},
- ]
-
- agree_count = sum(
- 1 for s in source_opinions if s["position"] == "agree"
- )
- consensus = agree_count / len(source_opinions)
-
- assert consensus == 0.75
-
- def test_evidence_consensus_strong(self):
- """Strong consensus is detected."""
- consensus = 0.90
-
- if consensus >= 0.8:
- strength = "strong"
- elif consensus >= 0.6:
- strength = "moderate"
- else:
- strength = "weak"
-
- assert strength == "strong"
-
- def test_evidence_consensus_weak(self):
- """Weak consensus is detected."""
- consensus = 0.55
-
- if consensus >= 0.8:
- strength = "strong"
- elif consensus >= 0.6:
- strength = "moderate"
- else:
- strength = "weak"
-
- assert strength == "weak"
-
-
-class TestCitationTracking:
- """Tests for citation tracking."""
-
- def test_evidence_citation_tracking(self):
- """Citations are tracked per claim."""
- claim = {
- "text": "Climate change is real",
- "citations": [
- {"source": "NASA", "year": 2023},
- {"source": "IPCC", "year": 2022},
- ],
- }
-
- citation_count = len(claim["citations"])
-
- assert citation_count == 2
-
- def test_evidence_citation_formatting(self):
- """Citations are formatted correctly."""
- citation = {"author": "Smith", "year": 2023, "title": "Study X"}
-
- formatted = (
- f"{citation['author']} ({citation['year']}). {citation['title']}"
- )
-
- assert formatted == "Smith (2023). Study X"
-
- def test_evidence_citation_deduplication(self):
- """Duplicate citations are removed."""
- citations = [
- {"source": "NASA", "year": 2023},
- {"source": "NASA", "year": 2023},
- {"source": "IPCC", "year": 2022},
- ]
-
- unique = []
- seen = set()
- for c in citations:
- key = (c["source"], c["year"])
- if key not in seen:
- seen.add(key)
- unique.append(c)
-
- assert len(unique) == 2
-
-
-class TestQualityAssessment:
- """Tests for evidence quality assessment."""
-
- def test_evidence_quality_assessment(self):
- """Evidence quality is assessed."""
- evidence = {
- "source_count": 5,
- "avg_authority": 0.85,
- "consensus": 0.90,
- "recency_score": 0.80,
- }
-
- quality = (
- evidence["avg_authority"] * 0.3
- + evidence["consensus"] * 0.3
- + evidence["recency_score"] * 0.2
- + min(1.0, evidence["source_count"] / 5) * 0.2
- )
-
- assert quality > 0.8
-
- def test_evidence_quality_low_sources(self):
- """Low source count reduces quality."""
- source_count = 1
- quality_factor = min(1.0, source_count / 5)
-
- assert quality_factor == 0.2
-
- def test_evidence_quality_high_authority(self):
- """High authority sources increase quality."""
- authority_scores = [0.95, 0.90, 0.85]
-
- avg_authority = sum(authority_scores) / len(authority_scores)
-
- assert avg_authority == 0.9
-
-
-class TestSynthesisGeneration:
- """Tests for evidence synthesis generation."""
-
- def test_evidence_synthesis_generation(self):
- """Synthesis is generated from evidence."""
- claims = [
- {"text": "A causes B", "confidence": 0.9},
- {"text": "B leads to C", "confidence": 0.85},
- ]
-
- # Simple synthesis
- synthesis = " Additionally, ".join(c["text"] for c in claims)
-
- assert "A causes B" in synthesis
- assert "B leads to C" in synthesis
-
- def test_evidence_synthesis_weighted(self):
- """Synthesis prioritizes high-confidence claims."""
- claims = [
- {"text": "High confidence claim", "confidence": 0.95},
- {"text": "Low confidence claim", "confidence": 0.40},
- ]
-
- # Filter low confidence
- high_conf = [c for c in claims if c["confidence"] >= 0.7]
-
- assert len(high_conf) == 1
-
- def test_evidence_synthesis_empty_claims(self):
- """Empty claims produce empty synthesis."""
- claims = []
-
- if not claims:
- synthesis = "No evidence found."
- else:
- synthesis = " ".join(c["text"] for c in claims)
-
- assert synthesis == "No evidence found."
-
-
-class TestSearchIteration:
- """Tests for iterative evidence search."""
-
- def test_evidence_search_iteration(self):
- """Evidence search iterates until threshold met."""
- confidence_threshold = 0.8
- iterations = 0
- max_iterations = 5
- current_confidence = 0.4
-
- while (
- current_confidence < confidence_threshold
- and iterations < max_iterations
- ):
- iterations += 1
- current_confidence += 0.2 # Simulate improvement
-
- assert current_confidence >= confidence_threshold
- assert iterations == 2
-
- def test_evidence_search_max_iterations(self):
- """Search stops at max iterations."""
- max_iterations = 5
- iterations = 0
-
- while iterations < max_iterations:
- iterations += 1
-
- assert iterations == max_iterations
-
- def test_evidence_result_merging(self):
- """Results from iterations are merged."""
- iteration_results = [
- [{"claim": "A"}],
- [{"claim": "B"}, {"claim": "C"}],
- ]
-
- merged = []
- for results in iteration_results:
- merged.extend(results)
-
- assert len(merged) == 3
-
-
-class TestErrorHandling:
- """Tests for evidence strategy error handling."""
-
- def test_evidence_error_handling(self):
- """Errors in evidence gathering are handled."""
- errors = []
-
- try:
- raise ConnectionError("Source unavailable")
- except ConnectionError as e:
- errors.append(str(e))
-
- assert len(errors) == 1
-
- def test_evidence_partial_failure(self):
- """Partial failures don't stop processing."""
- sources = ["source1", "source2", "source3"]
- results = []
- errors = []
-
- for source in sources:
- try:
- if source == "source2":
- raise Exception("Failed")
- results.append({"source": source, "data": "ok"})
- except Exception:
- errors.append(source)
-
- assert len(results) == 2
- assert len(errors) == 1
-
- def test_evidence_llm_failure_graceful_degradation(self):
- """LLM failure degrades gracefully."""
- llm_available = False
-
- if llm_available:
- synthesis = "LLM synthesis"
- else:
- synthesis = "Simple concatenation of claims"
-
- assert "concatenation" in synthesis
-
-
-class TestGetSynonymsExceptionHandling:
- """Tests for _get_synonyms exception handling (PR #2020).
-
- PR #2020 changed bare `except:` to `except Exception:` in _get_synonyms
- to catch any exception from the LLM call and return an empty list.
- """
-
- def test_get_synonyms_returns_list_on_success(self):
- """_get_synonyms should return list of synonyms on success."""
- from unittest.mock import MagicMock
-
- from local_deep_research.advanced_search_system.strategies.evidence_based_strategy_v2 import (
- EnhancedEvidenceBasedStrategy,
- )
-
- mock_model = MagicMock()
- mock_model.invoke.return_value = MagicMock(
- content="synonym1\nsynonym2\nsynonym3"
- )
- mock_search = MagicMock()
-
- strategy = EnhancedEvidenceBasedStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- result = strategy._get_synonyms("test term")
- assert isinstance(result, list)
- assert len(result) <= 3 # Limited to 3 synonyms
-
- def test_get_synonyms_returns_empty_on_llm_error(self):
- """_get_synonyms should return empty list when LLM raises an error."""
- from unittest.mock import MagicMock
-
- from local_deep_research.advanced_search_system.strategies.evidence_based_strategy_v2 import (
- EnhancedEvidenceBasedStrategy,
- )
-
- mock_model = MagicMock()
- mock_model.invoke.side_effect = Exception("LLM unavailable")
- mock_search = MagicMock()
-
- strategy = EnhancedEvidenceBasedStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- result = strategy._get_synonyms("test term")
- assert result == []
diff --git a/tests/advanced_search_system/strategies/test_evidence_based_v2_high_value.py b/tests/advanced_search_system/strategies/test_evidence_based_v2_high_value.py
deleted file mode 100644
index 239e19d708..0000000000
--- a/tests/advanced_search_system/strategies/test_evidence_based_v2_high_value.py
+++ /dev/null
@@ -1,553 +0,0 @@
-"""High-value tests for EnhancedEvidenceBasedStrategy pure logic.
-
-Tests focus on dataclass defaults, constructor defaults, pure logic methods
-(score calculations, pattern matching, diversity, filtering) without
-requiring LLM or search infrastructure.
-"""
-
-from datetime import datetime, UTC
-from unittest.mock import MagicMock, patch
-
-import pytest
-
-from local_deep_research.advanced_search_system.strategies.evidence_based_strategy_v2 import (
- EnhancedEvidenceBasedStrategy,
- QueryPattern,
- SourceProfile,
-)
-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,
-)
-
-
-# ---------------------------------------------------------------------------
-# Helpers
-# ---------------------------------------------------------------------------
-
-
-def _make_strategy(**overrides):
- """Create an EnhancedEvidenceBasedStrategy with __init__ bypassed."""
- with patch.object(
- EnhancedEvidenceBasedStrategy, "__init__", lambda self, *a, **kw: None
- ):
- s = EnhancedEvidenceBasedStrategy.__new__(EnhancedEvidenceBasedStrategy)
- # Set common defaults that many methods rely on
- s.model = MagicMock()
- s.search = MagicMock()
- s.candidates = []
- s.constraints = []
- s.constraint_relationships = {}
- s.failed_queries = set()
- s.query_patterns = {}
- s.source_profiles = {}
- s.enable_pattern_learning = True
- s.candidate_limit = 20
- s.evidence_threshold = 0.6
- s.min_candidates_threshold = 10
- s.max_iterations = 20
- s.iteration = 0
- s.progress_callback = None
- for k, v in overrides.items():
- setattr(s, k, v)
- return s
-
-
-def _make_constraint(
- id="c1",
- ctype=ConstraintType.PROPERTY,
- description="test",
- value="blue eyes",
- weight=1.0,
-):
- return Constraint(
- id=id, type=ctype, description=description, value=value, weight=weight
- )
-
-
-# ===========================================================================
-# QueryPattern dataclass
-# ===========================================================================
-class TestQueryPatternDataclass:
- """Tests for the QueryPattern dataclass defaults and field types."""
-
- def test_defaults_success_rate(self):
- qp = QueryPattern(pattern="test")
- assert qp.success_rate == 0.0
-
- def test_defaults_usage_count(self):
- qp = QueryPattern(pattern="test")
- assert qp.usage_count == 0
-
- def test_defaults_constraint_types_empty_list(self):
- qp = QueryPattern(pattern="test")
- assert qp.constraint_types == []
-
- def test_constraint_types_list_independence(self):
- """Each instance should get its own list."""
- qp1 = QueryPattern(pattern="a")
- qp2 = QueryPattern(pattern="b")
- qp1.constraint_types.append(ConstraintType.PROPERTY)
- assert qp2.constraint_types == []
-
- def test_explicit_values(self):
- qp = QueryPattern(
- pattern="{value}",
- success_rate=0.8,
- usage_count=5,
- constraint_types=[ConstraintType.EVENT],
- )
- assert qp.pattern == "{value}"
- assert qp.success_rate == 0.8
- assert qp.usage_count == 5
- assert qp.constraint_types == [ConstraintType.EVENT]
-
-
-# ===========================================================================
-# SourceProfile dataclass
-# ===========================================================================
-class TestSourceProfileDataclass:
- """Tests for the SourceProfile dataclass defaults and field types."""
-
- def test_defaults_success_rate(self):
- sp = SourceProfile(source_name="wiki")
- assert sp.success_rate == 0.0
-
- def test_defaults_usage_count(self):
- sp = SourceProfile(source_name="wiki")
- assert sp.usage_count == 0
-
- def test_defaults_specialties_empty_list(self):
- sp = SourceProfile(source_name="wiki")
- assert sp.specialties == []
-
- def test_defaults_last_used_none(self):
- sp = SourceProfile(source_name="wiki")
- assert sp.last_used is None
-
- def test_specialties_list_independence(self):
- sp1 = SourceProfile(source_name="a")
- sp2 = SourceProfile(source_name="b")
- sp1.specialties.append("characters")
- assert sp2.specialties == []
-
- def test_explicit_values(self):
- now = datetime.now(UTC)
- sp = SourceProfile(
- source_name="imdb",
- success_rate=0.9,
- usage_count=10,
- specialties=["tv_shows"],
- last_used=now,
- )
- assert sp.source_name == "imdb"
- assert sp.success_rate == 0.9
- assert sp.usage_count == 10
- assert sp.last_used is now
-
-
-# ===========================================================================
-# Constructor defaults (via bypassed __init__)
-# ===========================================================================
-class TestConstructorDefaults:
- """Verify default attribute values set during real __init__."""
-
- def test_initialize_patterns_returns_dict(self):
- s = _make_strategy()
- patterns = s._initialize_patterns()
- assert isinstance(patterns, dict)
- assert len(patterns) >= 5
-
- def test_initialize_patterns_contains_expected_keys(self):
- s = _make_strategy()
- patterns = s._initialize_patterns()
- expected = {
- "property_basic",
- "property_character",
- "event_show",
- "statistic_episodes",
- "cross_constraint",
- "semantic_expansion",
- }
- assert expected.issubset(patterns.keys())
-
- def test_initialize_sources_returns_dict(self):
- s = _make_strategy()
- sources = s._initialize_sources()
- assert isinstance(sources, dict)
- assert "wikipedia" in sources
- assert "imdb" in sources
- assert "web" in sources
-
- def test_initialize_sources_profiles_have_specialties(self):
- s = _make_strategy()
- sources = s._initialize_sources()
- assert "characters" in sources["wikipedia"].specialties
- assert "tv_shows" in sources["imdb"].specialties
-
-
-# ===========================================================================
-# _update_pattern_success
-# ===========================================================================
-class TestUpdatePatternSuccess:
- """Tests for the exponential moving average pattern update."""
-
- def test_success_increases_rate_from_zero(self):
- s = _make_strategy()
- qp = QueryPattern(pattern="test", success_rate=0.0, usage_count=0)
- s._update_pattern_success(qp, success=True)
- assert qp.usage_count == 1
- # alpha=0.3, new = 0.3*1 + 0.7*0.0 = 0.3
- assert qp.success_rate == pytest.approx(0.3)
-
- def test_failure_decreases_rate(self):
- s = _make_strategy()
- qp = QueryPattern(pattern="test", success_rate=1.0, usage_count=5)
- s._update_pattern_success(qp, success=False)
- assert qp.usage_count == 6
- # 0.7 * 1.0 = 0.7
- assert qp.success_rate == pytest.approx(0.7)
-
- def test_repeated_success_converges_to_one(self):
- s = _make_strategy()
- qp = QueryPattern(pattern="test", success_rate=0.0)
- for _ in range(50):
- s._update_pattern_success(qp, success=True)
- assert qp.success_rate > 0.99
-
-
-# ===========================================================================
-# _update_source_profile
-# ===========================================================================
-class TestUpdateSourceProfile:
- """Tests for source profile update logic."""
-
- def test_high_confidence_updates_success(self):
- s = _make_strategy()
- profile = SourceProfile(
- source_name="wiki", success_rate=0.0, usage_count=0
- )
- s.source_profiles = {"wiki": profile}
- s._update_source_profile("wiki", confidence=0.8)
- assert profile.usage_count == 1
- assert profile.success_rate == pytest.approx(0.3) # alpha*1 + 0.7*0
- assert profile.last_used is not None
-
- def test_low_confidence_does_not_increase(self):
- s = _make_strategy()
- profile = SourceProfile(
- source_name="wiki", success_rate=1.0, usage_count=0
- )
- s.source_profiles = {"wiki": profile}
- s._update_source_profile("wiki", confidence=0.3) # below threshold
- # 0.3*0 + 0.7*1.0 = 0.7
- assert profile.success_rate == pytest.approx(0.7)
-
- def test_unknown_source_is_ignored(self):
- s = _make_strategy()
- s.source_profiles = {}
- # Should not raise
- s._update_source_profile("nonexistent", confidence=0.9)
-
-
-# ===========================================================================
-# _find_common_terms
-# ===========================================================================
-class TestFindCommonTerms:
- """Tests for finding common terms between two constraints."""
-
- def test_common_terms_found(self):
- s = _make_strategy()
- c1 = _make_constraint(value="blue eyes character")
- c2 = _make_constraint(id="c2", value="character with wings")
- result = s._find_common_terms(c1, c2)
- assert "character" in result
-
- def test_no_common_terms(self):
- s = _make_strategy()
- c1 = _make_constraint(value="blue eyes")
- c2 = _make_constraint(id="c2", value="red wings")
- result = s._find_common_terms(c1, c2)
- assert result == []
-
- def test_case_insensitive(self):
- s = _make_strategy()
- c1 = _make_constraint(value="Blue Eyes")
- c2 = _make_constraint(id="c2", value="blue sky")
- result = s._find_common_terms(c1, c2)
- assert "blue" in result
-
-
-# ===========================================================================
-# _is_common_word
-# ===========================================================================
-class TestIsCommonWord:
- """Tests for common-word filtering."""
-
- def test_common_words_detected(self):
- s = _make_strategy()
- for word in ["the", "and", "is", "of", "with"]:
- assert s._is_common_word(word) is True
-
- def test_proper_names_not_common(self):
- s = _make_strategy()
- assert s._is_common_word("Homer") is False
- assert s._is_common_word("SpongeBob") is False
-
- def test_case_insensitive(self):
- s = _make_strategy()
- assert s._is_common_word("THE") is True
- assert s._is_common_word("And") is True
-
-
-# ===========================================================================
-# _calculate_source_diversity
-# ===========================================================================
-class TestCalculateSourceDiversity:
- """Tests for the entropy-based source diversity calculation."""
-
- def test_no_profiles_returns_zero(self):
- s = _make_strategy(source_profiles={})
- assert s._calculate_source_diversity() == 0.0
-
- def test_no_used_sources_returns_zero(self):
- s = _make_strategy(
- source_profiles={
- "a": SourceProfile(source_name="a", usage_count=0),
- "b": SourceProfile(source_name="b", usage_count=0),
- }
- )
- assert s._calculate_source_diversity() == 0.0
-
- def test_single_source_returns_one(self):
- """One used source -> entropy=0, max_entropy=0, edge case."""
- s = _make_strategy(
- source_profiles={
- "a": SourceProfile(source_name="a", usage_count=5),
- }
- )
- # log2(1/1) = 0, so max_entropy = 0 -> returns 0.0
- # This is the defined behavior for a single source
- result = s._calculate_source_diversity()
- assert result == 0.0
-
- def test_uniform_usage_returns_one(self):
- """Uniform usage across N sources should yield diversity ~ 1.0."""
- s = _make_strategy(
- source_profiles={
- "a": SourceProfile(source_name="a", usage_count=10),
- "b": SourceProfile(source_name="b", usage_count=10),
- "c": SourceProfile(source_name="c", usage_count=10),
- }
- )
- assert s._calculate_source_diversity() == pytest.approx(1.0)
-
- def test_skewed_usage_below_one(self):
- """Heavily skewed usage should yield diversity < 1.0."""
- s = _make_strategy(
- source_profiles={
- "a": SourceProfile(source_name="a", usage_count=100),
- "b": SourceProfile(source_name="b", usage_count=1),
- }
- )
- result = s._calculate_source_diversity()
- assert 0.0 < result < 1.0
-
-
-# ===========================================================================
-# _get_specialized_sources
-# ===========================================================================
-class TestGetSpecializedSources:
- """Tests for constraint-type to source mapping."""
-
- def test_property_type(self):
- s = _make_strategy()
- result = s._get_specialized_sources(ConstraintType.PROPERTY)
- assert "fandom" in result
- assert "wikipedia" in result
-
- def test_event_type(self):
- s = _make_strategy()
- result = s._get_specialized_sources(ConstraintType.EVENT)
- assert "imdb" in result
-
- def test_unknown_type_returns_web(self):
- s = _make_strategy()
- result = s._get_specialized_sources(ConstraintType.EXISTENCE)
- assert result == ["web"]
-
-
-# ===========================================================================
-# _apply_pattern_to_constraint
-# ===========================================================================
-class TestApplyPatternToConstraint:
- """Tests for pattern application to constraints."""
-
- def test_basic_replacement(self):
- s = _make_strategy()
- qp = QueryPattern(pattern="{value} {constraint_type}")
- c = _make_constraint(value="blue eyes", ctype=ConstraintType.PROPERTY)
- result = s._apply_pattern_to_constraint(qp, c)
- assert result == "blue eyes property"
-
- def test_synonym_placeholders_trigger_llm(self):
- s = _make_strategy()
- s.model.invoke.return_value = MagicMock(content="azure\ncobalt")
- qp = QueryPattern(pattern='"{value}" OR "{synonym1}" OR "{synonym2}"')
- c = _make_constraint(value="blue")
- result = s._apply_pattern_to_constraint(qp, c)
- assert '"blue"' in result
- assert '"azure"' in result
-
-
-# ===========================================================================
-# _build_cross_constraint_query
-# ===========================================================================
-class TestBuildCrossConstraintQuery:
- """Tests for cross-constraint query building."""
-
- def test_no_common_terms_uses_and(self):
- s = _make_strategy()
- c1 = _make_constraint(value="blue eyes", ctype=ConstraintType.PROPERTY)
- c2 = _make_constraint(
- id="c2", value="red hair", ctype=ConstraintType.STATISTIC
- )
- result = s._build_cross_constraint_query(c1, c2)
- assert "AND" in result
-
- def test_common_terms_used_as_base(self):
- s = _make_strategy()
- c1 = _make_constraint(
- value="TV character blue", ctype=ConstraintType.PROPERTY
- )
- c2 = _make_constraint(
- id="c2", value="TV show event", ctype=ConstraintType.EVENT
- )
- result = s._build_cross_constraint_query(c1, c2)
- assert "tv" in result.lower()
-
- def test_property_event_adds_tv_show_suffix(self):
- s = _make_strategy()
- c1 = _make_constraint(value="blue eyes", ctype=ConstraintType.PROPERTY)
- c2 = _make_constraint(
- id="c2", value="cancelled", ctype=ConstraintType.EVENT
- )
- result = s._build_cross_constraint_query(c1, c2)
- assert "TV show character" in result
-
-
-# ===========================================================================
-# _add_unique_candidates
-# ===========================================================================
-class TestAddUniqueCandidates:
- """Tests for deduplication and limit logic."""
-
- def test_deduplicates_by_name_case_insensitive(self):
- s = _make_strategy()
- s.candidates = [Candidate(name="Homer")]
- s._add_unique_candidates(
- [Candidate(name="homer"), Candidate(name="Bart")]
- )
- names = [c.name for c in s.candidates]
- assert len(names) == 2
- assert "Bart" in names
-
- def test_respects_candidate_limit(self):
- s = _make_strategy(candidate_limit=3)
- s.candidates = []
- s._add_unique_candidates([Candidate(name=f"c{i}") for i in range(10)])
- assert len(s.candidates) == 3
-
-
-# ===========================================================================
-# _generate_semantic_variations
-# ===========================================================================
-class TestGenerateSemanticVariations:
- """Tests for semantic query variation generation."""
-
- def test_property_type_variations(self):
- s = _make_strategy()
- c = _make_constraint(value="blue eyes", ctype=ConstraintType.PROPERTY)
- variations = s._generate_semantic_variations(c)
- assert any("entity with blue eyes" in v for v in variations)
-
- def test_event_type_variations(self):
- s = _make_strategy()
- c = _make_constraint(value="cancelled 2020", ctype=ConstraintType.EVENT)
- variations = s._generate_semantic_variations(c)
- assert any("event" in v for v in variations)
-
- def test_statistic_type_variations(self):
- s = _make_strategy()
- c = _make_constraint(
- value="100 episodes", ctype=ConstraintType.STATISTIC
- )
- variations = s._generate_semantic_variations(c)
- assert any("number" in v or "count" in v for v in variations)
-
- def test_max_five_variations(self):
- s = _make_strategy()
- c = _make_constraint(value="test", ctype=ConstraintType.PROPERTY)
- variations = s._generate_semantic_variations(c)
- assert len(variations) <= 5
-
-
-# ===========================================================================
-# _learn_query_pattern
-# ===========================================================================
-class TestLearnQueryPattern:
- """Tests for pattern learning from query outcomes."""
-
- def test_learning_disabled_does_nothing(self):
- s = _make_strategy(enable_pattern_learning=False)
- s.query_patterns = {}
- c = _make_constraint()
- s._learn_query_pattern("test query", c, success=True)
- assert len(s.query_patterns) == 0
-
- def test_learning_enabled_creates_pattern(self):
- s = _make_strategy(enable_pattern_learning=True)
- s.query_patterns = {}
- c = _make_constraint(ctype=ConstraintType.PROPERTY)
- s._learn_query_pattern("test query", c, success=True)
- assert "property_custom" in s.query_patterns
-
- def test_learning_updates_existing_pattern(self):
- s = _make_strategy(enable_pattern_learning=True)
- qp = QueryPattern(
- pattern="old",
- constraint_types=[ConstraintType.PROPERTY],
- success_rate=0.5,
- usage_count=3,
- )
- s.query_patterns = {"property_custom": qp}
- c = _make_constraint(ctype=ConstraintType.PROPERTY)
- s._learn_query_pattern("new query", c, success=True)
- assert qp.usage_count == 4
- assert qp.success_rate > 0.5
-
-
-# ===========================================================================
-# _generate_relaxed_queries
-# ===========================================================================
-class TestGenerateRelaxedQueries:
- """Tests for relaxed/fallback query generation."""
-
- def test_returns_queries_from_top_constraints(self):
- s = _make_strategy()
- s.constraints = [
- _make_constraint(id="c1", value="blue eyes", weight=2.0),
- _make_constraint(id="c2", value="red hair", weight=1.0),
- ]
- queries = s._generate_relaxed_queries()
- assert "blue eyes" in queries
- assert any("property" in q for q in queries)
-
- def test_empty_constraints_returns_empty(self):
- s = _make_strategy()
- s.constraints = []
- queries = s._generate_relaxed_queries()
- assert queries == []
diff --git a/tests/advanced_search_system/strategies/test_evidence_formatting_pure_logic.py b/tests/advanced_search_system/strategies/test_evidence_formatting_pure_logic.py
deleted file mode 100644
index 711d25e18e..0000000000
--- a/tests/advanced_search_system/strategies/test_evidence_formatting_pure_logic.py
+++ /dev/null
@@ -1,216 +0,0 @@
-"""
-Pure-logic tests for EvidenceBasedStrategy formatting methods.
-
-Tests _format_evidence_summary and _format_final_synthesis output structure,
-constraint satisfaction breakdown, and edge cases — no LLM or search calls.
-"""
-
-from unittest.mock import Mock
-
-from local_deep_research.advanced_search_system.candidates.base_candidate import (
- Candidate,
-)
-from local_deep_research.advanced_search_system.constraints.base_constraint import (
- Constraint,
- ConstraintType,
-)
-from local_deep_research.advanced_search_system.evidence.base_evidence import (
- Evidence,
- EvidenceType,
-)
-from local_deep_research.advanced_search_system.strategies.evidence_based_strategy import (
- EvidenceBasedStrategy,
-)
-
-
-def _evidence(confidence=0.8, claim="test claim"):
- return Evidence(
- type=EvidenceType.DIRECT_STATEMENT,
- confidence=confidence,
- claim=claim,
- source="test source",
- )
-
-
-def _constraint(cid, desc="test constraint"):
- return Constraint(
- id=cid,
- type=ConstraintType.PROPERTY,
- description=desc,
- value=desc,
- weight=1.0,
- )
-
-
-def _candidate(name, evidence_map=None, score=0.8):
- c = Candidate(name=name)
- c.evidence = evidence_map or {}
- c.score = score
- return c
-
-
-def _make_strategy(candidates=None, constraints=None, evidence_threshold=0.5):
- """Build a minimal Mock for EvidenceBasedStrategy."""
- s = Mock(spec=[])
- s.candidates = candidates or []
- s.constraints = constraints or []
- s.evidence_threshold = evidence_threshold
- s.iteration = 3
- s.max_iterations = 5
- s.search_history = [{"query": "q1"}, {"query": "q2"}]
- s.findings = []
- # Bind _format_evidence_summary so _format_final_synthesis can call it
- s._format_evidence_summary = (
- EvidenceBasedStrategy._format_evidence_summary.__get__(s)
- )
- return s
-
-
-# ---------------------------------------------------------------------------
-# _format_evidence_summary
-# ---------------------------------------------------------------------------
-
-
-class TestFormatEvidenceSummary:
- """Verify evidence summary formatting."""
-
- def test_no_candidates(self):
- """No candidates returns fallback message."""
- s = _make_strategy()
- result = EvidenceBasedStrategy._format_evidence_summary(s)
- assert result == "No candidates found"
-
- def test_single_candidate_with_evidence(self):
- """Candidate with evidence shows claim and confidence."""
- c1 = _constraint("c1", "height check")
- cand = _candidate("Mount Rainier", {"c1": _evidence(0.9, "14,411 ft")})
- s = _make_strategy(candidates=[cand], constraints=[c1])
- result = EvidenceBasedStrategy._format_evidence_summary(s)
- assert "Mount Rainier" in result
- assert "14,411 ft" in result
- assert "0.90" in result
-
- def test_missing_evidence_shows_no_evidence(self):
- """Constraint without evidence shows 'No evidence'."""
- c1 = _constraint("c1", "location check")
- cand = _candidate("Alice", {})
- s = _make_strategy(candidates=[cand], constraints=[c1])
- result = EvidenceBasedStrategy._format_evidence_summary(s)
- assert "No evidence" in result
-
- def test_shows_top_two_candidates(self):
- """Only first two candidates are shown."""
- c1 = _constraint("c1")
- cands = [
- _candidate("A", {"c1": _evidence()}, score=0.9),
- _candidate("B", {"c1": _evidence()}, score=0.8),
- _candidate("C", {"c1": _evidence()}, score=0.7),
- ]
- s = _make_strategy(candidates=cands, constraints=[c1])
- result = EvidenceBasedStrategy._format_evidence_summary(s)
- assert "A" in result
- assert "B" in result
- assert "C" not in result
-
-
-# ---------------------------------------------------------------------------
-# _format_final_synthesis
-# ---------------------------------------------------------------------------
-
-
-class TestFormatFinalSynthesis:
- """Verify final synthesis formatting."""
-
- def test_no_candidates_fallback(self):
- """No candidates shows fallback messages."""
- s = _make_strategy()
- result = EvidenceBasedStrategy._format_final_synthesis(
- s, "No answer", 0
- )
- assert "No candidates found" in result
- assert "No answer" in result
-
- def test_with_candidates_shows_satisfaction(self):
- """With candidates, shows constraint satisfaction count."""
- c1 = _constraint("c1", "height")
- c2 = _constraint("c2", "location")
- cand = _candidate(
- "Peak",
- {"c1": _evidence(0.9), "c2": _evidence(0.3)},
- score=0.7,
- )
- s = _make_strategy(
- candidates=[cand],
- constraints=[c1, c2],
- evidence_threshold=0.5,
- )
- result = EvidenceBasedStrategy._format_final_synthesis(s, "Peak", 70)
- # c1 is above threshold, c2 is below
- assert "Satisfied 1/2" in result
-
- def test_confidence_percentage_shown(self):
- """Confidence percentage appears in output."""
- c1 = _constraint("c1")
- cand = _candidate("X", {"c1": _evidence(0.8)}, score=0.8)
- s = _make_strategy(candidates=[cand], constraints=[c1])
- result = EvidenceBasedStrategy._format_final_synthesis(s, "X", 85)
- assert "85%" in result
-
- def test_constraint_breakdown_checkmarks(self):
- """Satisfied constraints get checkmark, unsatisfied get cross."""
- c1 = _constraint("c1", "passes")
- c2 = _constraint("c2", "fails")
- cand = _candidate(
- "Test",
- {"c1": _evidence(0.9)}, # c2 has no evidence
- score=0.5,
- )
- s = _make_strategy(
- candidates=[cand],
- constraints=[c1, c2],
- evidence_threshold=0.5,
- )
- result = EvidenceBasedStrategy._format_final_synthesis(s, "Test", 50)
- assert "✓" in result
- assert "✗" in result
-
- def test_below_threshold_warning(self):
- """Evidence below threshold gets warning marker."""
- c1 = _constraint("c1", "weak evidence")
- cand = _candidate(
- "Test",
- {"c1": _evidence(0.3)},
- score=0.3,
- )
- s = _make_strategy(
- candidates=[cand],
- constraints=[c1],
- evidence_threshold=0.5,
- )
- result = EvidenceBasedStrategy._format_final_synthesis(s, "Test", 30)
- assert "⚠" in result
- assert "below threshold" in result
-
- def test_iteration_count_shown(self):
- """Iteration count is included."""
- c1 = _constraint("c1")
- cand = _candidate("X", {"c1": _evidence()}, score=0.8)
- s = _make_strategy(candidates=[cand], constraints=[c1])
- result = EvidenceBasedStrategy._format_final_synthesis(s, "X", 80)
- assert "3/5" in result
-
- def test_top_candidates_listed(self):
- """Top 3 candidates are listed with scores."""
- c1 = _constraint("c1")
- cands = [
- _candidate("Alpha", {"c1": _evidence()}, score=0.9),
- _candidate("Beta", {"c1": _evidence()}, score=0.8),
- _candidate("Gamma", {"c1": _evidence()}, score=0.7),
- _candidate("Delta", {"c1": _evidence()}, score=0.6),
- ]
- s = _make_strategy(candidates=cands, constraints=[c1])
- result = EvidenceBasedStrategy._format_final_synthesis(s, "Alpha", 90)
- assert "Alpha" in result
- assert "Beta" in result
- assert "Gamma" in result
- # Delta (4th) might appear in evidence summary but not in top candidates list
diff --git a/tests/advanced_search_system/strategies/test_evidence_strategy_long_paths.py b/tests/advanced_search_system/strategies/test_evidence_strategy_long_paths.py
deleted file mode 100644
index 7f4f91dd0a..0000000000
--- a/tests/advanced_search_system/strategies/test_evidence_strategy_long_paths.py
+++ /dev/null
@@ -1,286 +0,0 @@
-"""
-Pure-logic tests for EvidenceBasedStrategy long code paths.
-
-Tests _score_and_prune_candidates (threshold formula, sorting, limit enforcement),
-_calculate_evidence_coverage (slicing, partial coverage), and
-_get_iteration_status (all 5 branches) — no LLM or search calls.
-"""
-
-from unittest.mock import Mock
-
-from local_deep_research.advanced_search_system.candidates.base_candidate import (
- Candidate,
-)
-from local_deep_research.advanced_search_system.constraints.base_constraint import (
- Constraint,
- ConstraintType,
-)
-from local_deep_research.advanced_search_system.evidence.base_evidence import (
- Evidence,
- EvidenceType,
-)
-from local_deep_research.advanced_search_system.strategies.evidence_based_strategy import (
- EvidenceBasedStrategy,
-)
-
-
-def _constraint(id, ctype=ConstraintType.PROPERTY, weight=1.0, value="v"):
- return Constraint(
- id=id, type=ctype, description="", value=value, weight=weight
- )
-
-
-def _evidence(confidence=0.8):
- return Evidence(
- claim="test",
- type=EvidenceType.DIRECT_STATEMENT,
- source="test",
- confidence=confidence,
- )
-
-
-def _make_strategy(
- candidates=None,
- constraints=None,
- confidence_threshold=0.85,
- candidate_limit=10,
- progress_callback=None,
-):
- """Build a minimal Mock with attributes used by pure-logic methods."""
- s = Mock(spec=[])
- s.candidates = candidates or []
- s.constraints = constraints or []
- s.confidence_threshold = confidence_threshold
- s.candidate_limit = candidate_limit
- s.progress_callback = progress_callback
- return s
-
-
-# ---------------------------------------------------------------------------
-# _score_and_prune_candidates
-# ---------------------------------------------------------------------------
-
-
-class TestScoreAndPruneCandidates:
- """Verify scoring, sorting, threshold pruning, and limit enforcement."""
-
- def test_empty_candidates(self):
- """Empty candidate list produces no error and stays empty."""
- s = _make_strategy(candidates=[])
- EvidenceBasedStrategy._score_and_prune_candidates(s)
- assert s.candidates == []
-
- def test_single_candidate_kept(self):
- """A single candidate above threshold is kept."""
- c = Candidate(name="A", score=0.5)
- cons = [_constraint("c1")]
- c.evidence = {"c1": _evidence(0.8)}
- s = _make_strategy(candidates=[c], constraints=cons)
- EvidenceBasedStrategy._score_and_prune_candidates(s)
- assert len(s.candidates) == 1
- assert s.candidates[0].name == "A"
-
- def test_threshold_uses_floor_when_top_score_low(self):
- """When top_score * 0.3 < 0.2, threshold is 0.2 (the floor)."""
- # top_score=0.5 -> 0.5*0.3=0.15 < 0.2, so threshold=0.2
- c1 = Candidate(name="High", score=0.5)
- c2 = Candidate(name="Low", score=0.19)
- cons = [_constraint("c1")]
- # Give c1 evidence so calculate_score keeps it high
- c1.evidence = {"c1": _evidence(0.9)}
- c2.evidence = {}
- s = _make_strategy(candidates=[c1, c2], constraints=cons)
- EvidenceBasedStrategy._score_and_prune_candidates(s)
- # c2 has score < 0.2 after calculate_score (no evidence -> score=0)
- names = [c.name for c in s.candidates]
- assert "High" in names
- # c2 should be pruned (score becomes 0.0 from calculate_score with no evidence)
- assert "Low" not in names
-
- def test_threshold_scales_with_top_score(self):
- """When top_score * 0.3 > 0.2, threshold scales with top score."""
- # top_score=0.9 -> 0.9*0.3=0.27, which is > 0.2, so threshold=0.27
- cons = [_constraint("c1"), _constraint("c2")]
- c1 = Candidate(name="Star")
- c1.evidence = {"c1": _evidence(0.95), "c2": _evidence(0.95)}
- c2 = Candidate(name="OK")
- c2.evidence = {"c1": _evidence(0.5)}
- c3 = Candidate(name="Weak")
- c3.evidence = {}
- s = _make_strategy(candidates=[c1, c2, c3], constraints=cons)
- EvidenceBasedStrategy._score_and_prune_candidates(s)
- # Star should be first (highest score)
- assert s.candidates[0].name == "Star"
- # Weak (score=0.0) should be pruned
- names = [c.name for c in s.candidates]
- assert "Weak" not in names
-
- def test_all_candidates_pruned(self):
- """When all candidates have score 0, all are pruned below min_score."""
- cons = [_constraint("c1")]
- candidates = [Candidate(name=f"C{i}") for i in range(3)]
- for c in candidates:
- c.evidence = {} # no evidence -> score becomes 0
- s = _make_strategy(candidates=candidates, constraints=cons)
- EvidenceBasedStrategy._score_and_prune_candidates(s)
- assert s.candidates == []
-
- def test_candidate_limit_enforced(self):
- """Only top candidate_limit candidates are kept after pruning."""
- cons = [_constraint("c1")]
- candidates = []
- for i in range(10):
- c = Candidate(name=f"C{i}")
- c.evidence = {"c1": _evidence(0.8)}
- candidates.append(c)
- s = _make_strategy(
- candidates=candidates, constraints=cons, candidate_limit=3
- )
- EvidenceBasedStrategy._score_and_prune_candidates(s)
- assert len(s.candidates) <= 3
-
- def test_sorting_by_score_descending(self):
- """Candidates are sorted by score, highest first."""
- cons = [_constraint("c1"), _constraint("c2")]
- c1 = Candidate(name="Low")
- c1.evidence = {"c1": _evidence(0.3)}
- c2 = Candidate(name="High")
- c2.evidence = {"c1": _evidence(0.9), "c2": _evidence(0.9)}
- s = _make_strategy(candidates=[c1, c2], constraints=cons)
- EvidenceBasedStrategy._score_and_prune_candidates(s)
- if len(s.candidates) >= 2:
- assert s.candidates[0].score >= s.candidates[1].score
-
- def test_progress_callback_not_called_when_none(self):
- """No error when progress_callback is None."""
- c = Candidate(name="A")
- c.evidence = {"c1": _evidence(0.8)}
- s = _make_strategy(
- candidates=[c],
- constraints=[_constraint("c1")],
- progress_callback=None,
- )
- EvidenceBasedStrategy._score_and_prune_candidates(s)
- assert len(s.candidates) == 1
-
-
-# ---------------------------------------------------------------------------
-# _calculate_evidence_coverage
-# ---------------------------------------------------------------------------
-
-
-class TestCalculateEvidenceCoverage:
- """Verify evidence coverage calculation including edge cases and slicing."""
-
- def test_empty_candidates(self):
- """No candidates -> coverage 0.0."""
- s = _make_strategy(candidates=[])
- assert EvidenceBasedStrategy._calculate_evidence_coverage(s) == 0.0
-
- def test_empty_constraints(self):
- """No constraints -> coverage 0.0."""
- c = Candidate(name="A")
- s = _make_strategy(candidates=[c], constraints=[])
- assert EvidenceBasedStrategy._calculate_evidence_coverage(s) == 0.0
-
- def test_no_evidence_collected(self):
- """Candidates with no evidence -> coverage 0.0."""
- c = Candidate(name="A")
- c.evidence = {}
- s = _make_strategy(candidates=[c], constraints=[_constraint("c1")])
- assert EvidenceBasedStrategy._calculate_evidence_coverage(s) == 0.0
-
- def test_partial_coverage(self):
- """One candidate with evidence for 1 of 2 constraints -> 0.5."""
- c = Candidate(name="A")
- c.evidence = {"c1": _evidence()}
- cons = [_constraint("c1"), _constraint("c2")]
- s = _make_strategy(candidates=[c], constraints=cons)
- coverage = EvidenceBasedStrategy._calculate_evidence_coverage(s)
- assert coverage == 0.5
-
- def test_full_coverage(self):
- """All candidates have evidence for all constraints -> 1.0."""
- cons = [_constraint("c1"), _constraint("c2")]
- c = Candidate(name="A")
- c.evidence = {"c1": _evidence(), "c2": _evidence()}
- s = _make_strategy(candidates=[c], constraints=cons)
- coverage = EvidenceBasedStrategy._calculate_evidence_coverage(s)
- assert coverage == 1.0
-
- def test_slicing_to_top_5(self):
- """Only top 5 candidates are considered for coverage calculation."""
- cons = [_constraint("c1")]
- candidates = []
- for i in range(7):
- c = Candidate(name=f"C{i}")
- c.evidence = {"c1": _evidence()} if i < 3 else {}
- candidates.append(c)
- s = _make_strategy(candidates=candidates, constraints=cons)
- coverage = EvidenceBasedStrategy._calculate_evidence_coverage(s)
- # Only first 5 candidates: 3 have evidence, 2 don't -> 3/5 = 0.6
- assert coverage == 3 / 5
-
-
-# ---------------------------------------------------------------------------
-# _get_iteration_status
-# ---------------------------------------------------------------------------
-
-
-class TestGetIterationStatus:
- """Verify all 5 status branches based on candidates and score."""
-
- def test_no_candidates(self):
- """No candidates -> 'Searching for initial candidates'."""
- s = _make_strategy(candidates=[])
- result = EvidenceBasedStrategy._get_iteration_status(s)
- assert result == "Searching for initial candidates"
-
- def test_score_at_threshold(self):
- """Score exactly at confidence_threshold -> 'Verifying top candidate'."""
- c = Candidate(name="A", score=0.85)
- s = _make_strategy(candidates=[c], confidence_threshold=0.85)
- result = EvidenceBasedStrategy._get_iteration_status(s)
- assert result == "Verifying top candidate"
-
- def test_score_above_threshold(self):
- """Score above confidence_threshold -> 'Verifying top candidate'."""
- c = Candidate(name="A", score=0.95)
- s = _make_strategy(candidates=[c], confidence_threshold=0.85)
- result = EvidenceBasedStrategy._get_iteration_status(s)
- assert result == "Verifying top candidate"
-
- def test_score_just_below_threshold(self):
- """Score 0.84 (below 0.85 threshold, >= 0.7) -> 'Gathering final evidence'."""
- c = Candidate(name="A", score=0.84)
- s = _make_strategy(candidates=[c], confidence_threshold=0.85)
- result = EvidenceBasedStrategy._get_iteration_status(s)
- assert result == "Gathering final evidence"
-
- def test_score_at_070(self):
- """Score exactly 0.7 -> 'Gathering final evidence'."""
- c = Candidate(name="A", score=0.7)
- s = _make_strategy(candidates=[c], confidence_threshold=0.85)
- result = EvidenceBasedStrategy._get_iteration_status(s)
- assert result == "Gathering final evidence"
-
- def test_score_at_069(self):
- """Score 0.69 (below 0.7, >= 0.5) -> 'Refining candidate scores'."""
- c = Candidate(name="A", score=0.69)
- s = _make_strategy(candidates=[c], confidence_threshold=0.85)
- result = EvidenceBasedStrategy._get_iteration_status(s)
- assert result == "Refining candidate scores"
-
- def test_score_at_050(self):
- """Score exactly 0.5 -> 'Refining candidate scores'."""
- c = Candidate(name="A", score=0.5)
- s = _make_strategy(candidates=[c], confidence_threshold=0.85)
- result = EvidenceBasedStrategy._get_iteration_status(s)
- assert result == "Refining candidate scores"
-
- def test_score_below_050(self):
- """Score 0.49 (below 0.5) -> 'Exploring candidate evidence'."""
- c = Candidate(name="A", score=0.49)
- s = _make_strategy(candidates=[c], confidence_threshold=0.85)
- result = EvidenceBasedStrategy._get_iteration_status(s)
- assert result == "Exploring candidate evidence"
diff --git a/tests/advanced_search_system/strategies/test_evidence_v2_pure_logic.py b/tests/advanced_search_system/strategies/test_evidence_v2_pure_logic.py
deleted file mode 100644
index 3a0a1e93ea..0000000000
--- a/tests/advanced_search_system/strategies/test_evidence_v2_pure_logic.py
+++ /dev/null
@@ -1,396 +0,0 @@
-"""
-Pure-logic tests for EnhancedEvidenceBasedStrategy.
-
-Tests algorithmic methods that require no LLM or search calls:
-pattern initialization, source diversity scoring, deduplication,
-semantic variation generation, and pattern application.
-"""
-
-from unittest.mock import Mock
-
-from local_deep_research.advanced_search_system.candidates.base_candidate import (
- Candidate,
-)
-from local_deep_research.advanced_search_system.constraints.base_constraint import (
- Constraint,
- ConstraintType,
-)
-from local_deep_research.advanced_search_system.strategies.evidence_based_strategy_v2 import (
- EnhancedEvidenceBasedStrategy,
- QueryPattern,
- SourceProfile,
-)
-
-
-def _make_strategy(**overrides):
- """Build a minimal Mock with attributes that the pure-logic methods read."""
- s = Mock(spec=[])
- s.candidates = overrides.get("candidates", [])
- s.candidate_limit = overrides.get("candidate_limit", 20)
- s.source_profiles = overrides.get("source_profiles", {})
- return s
-
-
-# ---------------------------------------------------------------------------
-# _initialize_patterns
-# ---------------------------------------------------------------------------
-
-
-class TestInitializePatterns:
- """Verify _initialize_patterns returns correct pattern catalogue."""
-
- def test_returns_dict(self):
- """Should return a dict of QueryPattern instances."""
- result = EnhancedEvidenceBasedStrategy._initialize_patterns(Mock())
- assert isinstance(result, dict)
-
- def test_expected_keys(self):
- """All six named patterns should be present."""
- result = EnhancedEvidenceBasedStrategy._initialize_patterns(Mock())
- expected = {
- "property_basic",
- "property_character",
- "event_show",
- "statistic_episodes",
- "cross_constraint",
- "semantic_expansion",
- }
- assert set(result.keys()) == expected
-
- def test_property_patterns_have_property_type(self):
- """Property patterns should list PROPERTY in constraint_types."""
- result = EnhancedEvidenceBasedStrategy._initialize_patterns(Mock())
- for key in ("property_basic", "property_character"):
- assert ConstraintType.PROPERTY in result[key].constraint_types
-
- def test_event_pattern_has_event_type(self):
- """Event pattern should list EVENT in constraint_types."""
- result = EnhancedEvidenceBasedStrategy._initialize_patterns(Mock())
- assert ConstraintType.EVENT in result["event_show"].constraint_types
-
- def test_statistic_pattern_has_statistic_type(self):
- """Statistic pattern should list STATISTIC in constraint_types."""
- result = EnhancedEvidenceBasedStrategy._initialize_patterns(Mock())
- assert (
- ConstraintType.STATISTIC
- in result["statistic_episodes"].constraint_types
- )
-
- def test_cross_constraint_has_empty_types(self):
- """Cross-constraint pattern is type-agnostic."""
- result = EnhancedEvidenceBasedStrategy._initialize_patterns(Mock())
- assert result["cross_constraint"].constraint_types == []
-
- def test_patterns_are_querypattern_instances(self):
- """Every value should be a QueryPattern dataclass."""
- result = EnhancedEvidenceBasedStrategy._initialize_patterns(Mock())
- for v in result.values():
- assert isinstance(v, QueryPattern)
-
-
-# ---------------------------------------------------------------------------
-# _initialize_sources
-# ---------------------------------------------------------------------------
-
-
-class TestInitializeSources:
- """Verify _initialize_sources returns correct source catalogue."""
-
- def test_returns_dict(self):
- """Should return a dict of SourceProfile instances."""
- result = EnhancedEvidenceBasedStrategy._initialize_sources(Mock())
- assert isinstance(result, dict)
-
- def test_expected_sources(self):
- """All five named sources should be present."""
- result = EnhancedEvidenceBasedStrategy._initialize_sources(Mock())
- expected = {"wikipedia", "imdb", "fandom", "tv_databases", "web"}
- assert set(result.keys()) == expected
-
- def test_source_names_match_keys(self):
- """Each source_name field should match its dict key."""
- result = EnhancedEvidenceBasedStrategy._initialize_sources(Mock())
- for key, profile in result.items():
- assert profile.source_name == key
-
- def test_profiles_are_sourceprofile_instances(self):
- """Every value should be a SourceProfile dataclass."""
- result = EnhancedEvidenceBasedStrategy._initialize_sources(Mock())
- for v in result.values():
- assert isinstance(v, SourceProfile)
-
- def test_wikipedia_specialties(self):
- """Wikipedia should cover characters, properties, general."""
- result = EnhancedEvidenceBasedStrategy._initialize_sources(Mock())
- assert "characters" in result["wikipedia"].specialties
- assert "general" in result["wikipedia"].specialties
-
-
-# ---------------------------------------------------------------------------
-# _calculate_source_diversity (Shannon entropy)
-# ---------------------------------------------------------------------------
-
-
-class TestCalculateSourceDiversity:
- """Verify Shannon-entropy source diversity calculation."""
-
- def _call(self, profiles):
- s = _make_strategy(source_profiles=profiles)
- return EnhancedEvidenceBasedStrategy._calculate_source_diversity(s)
-
- def test_empty_profiles(self):
- """No profiles at all -> 0.0."""
- assert self._call({}) == 0.0
-
- def test_no_usage(self):
- """Profiles exist but none used -> 0.0."""
- profiles = {
- "a": SourceProfile(source_name="a", usage_count=0),
- "b": SourceProfile(source_name="b", usage_count=0),
- }
- assert self._call(profiles) == 0.0
-
- def test_single_source_used(self):
- """Only one source used -> 0.0 (log2(1) = 0)."""
- profiles = {
- "a": SourceProfile(source_name="a", usage_count=5),
- "b": SourceProfile(source_name="b", usage_count=0),
- }
- # Only one source in used_sources -> max_entropy = -log2(1/1) = 0
- # Division by zero guard returns 0.0
- assert self._call(profiles) == 0.0
-
- def test_uniform_two_sources(self):
- """Two sources used equally -> diversity = 1.0."""
- profiles = {
- "a": SourceProfile(source_name="a", usage_count=10),
- "b": SourceProfile(source_name="b", usage_count=10),
- }
- assert self._call(profiles) == 1.0
-
- def test_uniform_three_sources(self):
- """Three sources used equally -> diversity = 1.0."""
- profiles = {
- "a": SourceProfile(source_name="a", usage_count=5),
- "b": SourceProfile(source_name="b", usage_count=5),
- "c": SourceProfile(source_name="c", usage_count=5),
- }
- assert abs(self._call(profiles) - 1.0) < 1e-9
-
- def test_skewed_distribution(self):
- """Skewed usage -> 0 < diversity < 1."""
- profiles = {
- "a": SourceProfile(source_name="a", usage_count=90),
- "b": SourceProfile(source_name="b", usage_count=10),
- }
- diversity = self._call(profiles)
- assert 0.0 < diversity < 1.0
-
- def test_heavily_skewed(self):
- """Very skewed usage -> close to 0 but positive."""
- profiles = {
- "a": SourceProfile(source_name="a", usage_count=999),
- "b": SourceProfile(source_name="b", usage_count=1),
- }
- diversity = self._call(profiles)
- assert 0.0 < diversity < 0.2
-
-
-# ---------------------------------------------------------------------------
-# _find_common_terms
-# ---------------------------------------------------------------------------
-
-
-class TestFindCommonTerms:
- """Verify set-intersection of constraint value words."""
-
- def _call(self, val1, val2):
- c1 = Constraint(
- id="c1", type=ConstraintType.PROPERTY, description="", value=val1
- )
- c2 = Constraint(
- id="c2", type=ConstraintType.PROPERTY, description="", value=val2
- )
- return EnhancedEvidenceBasedStrategy._find_common_terms(Mock(), c1, c2)
-
- def test_overlapping_terms(self):
- """Shared words should be returned."""
- result = self._call("red blue green", "blue green yellow")
- assert set(result) == {"blue", "green"}
-
- def test_no_overlap(self):
- """No shared words -> empty list."""
- assert self._call("cat dog", "fish bird") == []
-
- def test_case_insensitive(self):
- """Matching should be case-insensitive (lowered)."""
- result = self._call("Alpha Beta", "alpha gamma")
- assert "alpha" in result
-
- def test_empty_values(self):
- """Empty constraint values -> empty result."""
- # split() on empty string returns [] -> empty set intersection
- assert self._call("", "") == []
-
-
-# ---------------------------------------------------------------------------
-# _is_common_word
-# ---------------------------------------------------------------------------
-
-
-class TestIsCommonWord:
- """Verify stopword detection."""
-
- def _call(self, name):
- return EnhancedEvidenceBasedStrategy._is_common_word(Mock(), name)
-
- def test_common_word(self):
- """'the' is a common word."""
- assert self._call("the") is True
-
- def test_proper_name(self):
- """A proper name should not be flagged."""
- assert self._call("Elizabeth") is False
-
- def test_case_insensitive(self):
- """'THE' should still be detected."""
- assert self._call("THE") is True
-
- def test_preposition(self):
- """'from' is in the common word set."""
- assert self._call("from") is True
-
- def test_uncommon_short_word(self):
- """'ax' is short but not in the set."""
- assert self._call("ax") is False
-
-
-# ---------------------------------------------------------------------------
-# _add_unique_candidates
-# ---------------------------------------------------------------------------
-
-
-class TestAddUniqueCandidates:
- """Verify deduplication and limit enforcement."""
-
- def test_adds_new_candidates(self):
- """New candidates are appended."""
- s = _make_strategy(candidates=[], candidate_limit=10)
- new = [Candidate(name="Alice"), Candidate(name="Bob")]
- EnhancedEvidenceBasedStrategy._add_unique_candidates(s, new)
- names = [c.name for c in s.candidates]
- assert names == ["Alice", "Bob"]
-
- def test_deduplicates_by_name(self):
- """Duplicate names (case-insensitive) are skipped."""
- s = _make_strategy(
- candidates=[Candidate(name="Alice")],
- candidate_limit=10,
- )
- new = [Candidate(name="alice"), Candidate(name="Bob")]
- EnhancedEvidenceBasedStrategy._add_unique_candidates(s, new)
- names = [c.name for c in s.candidates]
- assert names == ["Alice", "Bob"]
-
- def test_enforces_limit(self):
- """Total candidates should not exceed candidate_limit."""
- s = _make_strategy(candidates=[], candidate_limit=3)
- new = [Candidate(name=f"C{i}") for i in range(5)]
- EnhancedEvidenceBasedStrategy._add_unique_candidates(s, new)
- assert len(s.candidates) == 3
-
- def test_empty_input(self):
- """Empty new-candidates list doesn't modify existing."""
- existing = [Candidate(name="Alice")]
- s = _make_strategy(candidates=existing, candidate_limit=10)
- EnhancedEvidenceBasedStrategy._add_unique_candidates(s, [])
- assert len(s.candidates) == 1
-
-
-# ---------------------------------------------------------------------------
-# _generate_semantic_variations
-# ---------------------------------------------------------------------------
-
-
-class TestGenerateSemanticVariations:
- """Verify query variation generation by constraint type."""
-
- def _call(self, ctype, value="test value"):
- c = Constraint(id="c1", type=ctype, description="desc", value=value)
- return EnhancedEvidenceBasedStrategy._generate_semantic_variations(
- Mock(), c
- )
-
- def test_property_variations(self):
- """PROPERTY type should produce 'entity with …' style variations."""
- result = self._call(ConstraintType.PROPERTY)
- assert any("entity with" in v for v in result)
-
- def test_event_variations(self):
- """EVENT type should produce 'when …' style variation."""
- result = self._call(ConstraintType.EVENT)
- assert any("when" in v for v in result)
-
- def test_statistic_variations(self):
- """STATISTIC type should produce 'number …' style variation."""
- result = self._call(ConstraintType.STATISTIC)
- assert any("number" in v for v in result)
-
- def test_unknown_type_generic(self):
- """Non-standard type falls through to generic variations."""
- result = self._call(ConstraintType.LOCATION)
- assert any(
- "specific" in v or "about" in v or "regarding" in v for v in result
- )
-
- def test_capped_at_five(self):
- """No more than 5 variations returned."""
- result = self._call(ConstraintType.PROPERTY)
- assert len(result) <= 5
-
- def test_variations_contain_value(self):
- """All variations should incorporate the constraint value."""
- result = self._call(ConstraintType.PROPERTY, "blue eyes")
- assert all("blue eyes" in v for v in result)
-
-
-# ---------------------------------------------------------------------------
-# _apply_pattern_to_constraint
-# ---------------------------------------------------------------------------
-
-
-class TestApplyPatternToConstraint:
- """Verify placeholder substitution in query patterns."""
-
- def _call(self, pattern_str, value, ctype=ConstraintType.PROPERTY):
- pattern = QueryPattern(pattern=pattern_str, constraint_types=[])
- constraint = Constraint(
- id="c1", type=ctype, description="", value=value
- )
- return EnhancedEvidenceBasedStrategy._apply_pattern_to_constraint(
- Mock(), pattern, constraint
- )
-
- def test_value_substitution(self):
- """'{value}' placeholder is replaced."""
- result = self._call("{value} query", "blue eyes")
- assert result == "blue eyes query"
-
- def test_constraint_type_substitution(self):
- """'{constraint_type}' placeholder is replaced with enum value."""
- result = self._call(
- "{value} {constraint_type}", "test", ConstraintType.EVENT
- )
- assert result == "test event"
-
- def test_no_placeholders(self):
- """Pattern without placeholders is returned unchanged."""
- result = self._call("static query", "ignored")
- assert result == "static query"
-
- def test_both_placeholders(self):
- """Both {value} and {constraint_type} replaced in one pass."""
- result = self._call(
- "find {value} type {constraint_type}", "X", ConstraintType.STATISTIC
- )
- assert result == "find X type statistic"
diff --git a/tests/advanced_search_system/strategies/test_iterative_reasoning_high_value.py b/tests/advanced_search_system/strategies/test_iterative_reasoning_high_value.py
deleted file mode 100644
index 0420ef71b3..0000000000
--- a/tests/advanced_search_system/strategies/test_iterative_reasoning_high_value.py
+++ /dev/null
@@ -1,396 +0,0 @@
-"""High-value pure logic tests for IterativeReasoningStrategy and KnowledgeState."""
-
-import pytest
-from unittest.mock import patch
-
-from local_deep_research.advanced_search_system.strategies.iterative_reasoning_strategy import (
- IterativeReasoningStrategy,
- KnowledgeState,
-)
-
-
-def _make_strategy(**overrides):
- """Create an IterativeReasoningStrategy with mocked __init__."""
- with patch.object(
- IterativeReasoningStrategy, "__init__", lambda self, *a, **kw: None
- ):
- strat = IterativeReasoningStrategy.__new__(IterativeReasoningStrategy)
- strat.knowledge_state = KnowledgeState(original_query="test query")
- # Apply any overrides
- for key, val in overrides.items():
- setattr(strat, key, val)
- return strat
-
-
-class TestKnowledgeStateDefaults:
- """Test KnowledgeState dataclass default values."""
-
- def test_defaults(self):
- ks = KnowledgeState(original_query="hello")
- assert ks.original_query == "hello"
- assert ks.key_facts == []
- assert ks.uncertainties == []
- assert ks.search_history == []
- assert ks.candidate_answers == []
- assert ks.confidence == 0.0
- assert ks.iteration == 0
-
- def test_default_lists_are_independent(self):
- ks1 = KnowledgeState(original_query="a")
- ks2 = KnowledgeState(original_query="b")
- ks1.key_facts.append("fact")
- assert ks2.key_facts == []
-
- def test_custom_values(self):
- ks = KnowledgeState(
- original_query="q",
- key_facts=["f1"],
- uncertainties=["u1"],
- confidence=0.5,
- iteration=3,
- )
- assert ks.key_facts == ["f1"]
- assert ks.confidence == 0.5
- assert ks.iteration == 3
-
-
-class TestKnowledgeStateToString:
- """Test KnowledgeState.to_string() formatting."""
-
- def test_empty_state_shows_defaults(self):
- ks = KnowledgeState(original_query="my query")
- result = ks.to_string()
- assert "Original Query: my query" in result
- assert "- Nothing yet" in result
- assert "- Nothing specific" in result
- assert "- No searches yet" in result
- assert "- None yet" in result
- assert "0.0%" in result
-
- def test_with_facts(self):
- ks = KnowledgeState(
- original_query="q", key_facts=["Earth is round", "Sky is blue"]
- )
- result = ks.to_string()
- assert "- Earth is round" in result
- assert "- Sky is blue" in result
- assert "Nothing yet" not in result
-
- def test_with_uncertainties(self):
- ks = KnowledgeState(original_query="q", uncertainties=["Is Mars red?"])
- result = ks.to_string()
- assert "- Is Mars red?" in result
- assert "Nothing specific" not in result
-
- def test_search_history_shows_last_three(self):
- history = [{"query": f"search {i}"} for i in range(5)]
- ks = KnowledgeState(original_query="q", search_history=history)
- result = ks.to_string()
- assert "5 searches" in result
- # Only last 3 should appear
- assert "search 2" in result
- assert "search 3" in result
- assert "search 4" in result
- # First two should NOT appear
- assert "Search 1: search 0" not in result
- assert "Search 2: search 1" not in result
-
- def test_candidate_answers_sorted_by_confidence(self):
- candidates = [
- {"answer": "low", "confidence": 0.3},
- {"answer": "high", "confidence": 0.9},
- {"answer": "mid", "confidence": 0.6},
- ]
- ks = KnowledgeState(original_query="q", candidate_answers=candidates)
- result = ks.to_string()
- assert "3 total" in result
- # High confidence should appear before low
- high_pos = result.index("high")
- low_pos = result.index("- low")
- assert high_pos < low_pos
-
- def test_confidence_formatting(self):
- ks = KnowledgeState(original_query="q", confidence=0.753)
- result = ks.to_string()
- assert "75.3%" in result
-
-
-class TestAssessAnswerNoCandidates:
- """Test _assess_answer with no candidates."""
-
- def test_no_candidates_sets_zero(self):
- strat = _make_strategy()
- strat.knowledge_state.candidate_answers = []
- strat.knowledge_state.confidence = 0.5 # pre-existing value
- strat._assess_answer()
- assert strat.knowledge_state.confidence == 0.0
-
-
-class TestAssessAnswerSingleCandidate:
- """Test _assess_answer with a single candidate."""
-
- def test_single_candidate_no_extras(self):
- strat = _make_strategy()
- strat.knowledge_state.candidate_answers = [
- {"answer": "A", "confidence": 0.7}
- ]
- strat.knowledge_state.key_facts = []
- strat.knowledge_state.uncertainties = []
- strat.knowledge_state.search_history = []
- strat._assess_answer()
- # base=0.7, fact_boost=0, uncertainty_penalty=0, search_boost=0, candidate_penalty=0
- assert strat.knowledge_state.confidence == 0.7
-
- def test_single_candidate_with_facts_boost(self):
- strat = _make_strategy()
- strat.knowledge_state.candidate_answers = [
- {"answer": "A", "confidence": 0.6}
- ]
- strat.knowledge_state.key_facts = ["f1", "f2", "f3"] # 3*0.05 = 0.15
- strat.knowledge_state.uncertainties = []
- strat.knowledge_state.search_history = []
- strat._assess_answer()
- assert strat.knowledge_state.confidence == pytest.approx(0.75)
-
- def test_fact_boost_capped_at_0_2(self):
- strat = _make_strategy()
- strat.knowledge_state.candidate_answers = [
- {"answer": "A", "confidence": 0.5}
- ]
- strat.knowledge_state.key_facts = [
- "f"
- ] * 10 # 10*0.05=0.5, capped at 0.2
- strat.knowledge_state.uncertainties = []
- strat.knowledge_state.search_history = []
- strat._assess_answer()
- # base=0.5 + fact_boost=0.2 = 0.7
- assert strat.knowledge_state.confidence == pytest.approx(0.7)
-
- def test_uncertainty_penalty(self):
- strat = _make_strategy()
- strat.knowledge_state.candidate_answers = [
- {"answer": "A", "confidence": 0.8}
- ]
- strat.knowledge_state.key_facts = []
- strat.knowledge_state.uncertainties = ["u1", "u2"] # 2*0.05=0.1
- strat.knowledge_state.search_history = []
- strat._assess_answer()
- assert strat.knowledge_state.confidence == pytest.approx(0.7)
-
- def test_uncertainty_penalty_capped_at_0_2(self):
- strat = _make_strategy()
- strat.knowledge_state.candidate_answers = [
- {"answer": "A", "confidence": 0.8}
- ]
- strat.knowledge_state.key_facts = []
- strat.knowledge_state.uncertainties = ["u"] * 20 # capped at 0.2
- strat.knowledge_state.search_history = []
- strat._assess_answer()
- assert strat.knowledge_state.confidence == pytest.approx(0.6)
-
- def test_search_boost(self):
- strat = _make_strategy()
- strat.knowledge_state.candidate_answers = [
- {"answer": "A", "confidence": 0.5}
- ]
- strat.knowledge_state.key_facts = []
- strat.knowledge_state.uncertainties = []
- strat.knowledge_state.search_history = [
- {"query": "q"}
- ] * 3 # 3*0.02=0.06
- strat._assess_answer()
- assert strat.knowledge_state.confidence == pytest.approx(0.56)
-
- def test_search_boost_capped_at_0_1(self):
- strat = _make_strategy()
- strat.knowledge_state.candidate_answers = [
- {"answer": "A", "confidence": 0.5}
- ]
- strat.knowledge_state.key_facts = []
- strat.knowledge_state.uncertainties = []
- strat.knowledge_state.search_history = [
- {"query": "q"}
- ] * 20 # capped at 0.1
- strat._assess_answer()
- assert strat.knowledge_state.confidence == pytest.approx(0.6)
-
-
-class TestAssessAnswerConfidenceSpread:
- """Test _assess_answer confidence spread logic with two candidates."""
-
- def test_close_candidates_reduce_confidence(self):
- """Two candidates within 0.1 spread triggers 0.8 multiplier on base."""
- strat = _make_strategy()
- strat.knowledge_state.candidate_answers = [
- {"answer": "A", "confidence": 0.8},
- {"answer": "B", "confidence": 0.75},
- ]
- strat.knowledge_state.key_facts = []
- strat.knowledge_state.uncertainties = []
- strat.knowledge_state.search_history = []
- strat._assess_answer()
- # spread=0.05 < 0.1 => base = 0.8 * 0.8 = 0.64
- assert strat.knowledge_state.confidence == pytest.approx(0.64)
-
- def test_spread_exactly_0_1_triggers_reduction(self):
- """Spread of exactly 0.1 is NOT < 0.1, so no reduction."""
- strat = _make_strategy()
- strat.knowledge_state.candidate_answers = [
- {"answer": "A", "confidence": 0.8},
- {"answer": "B", "confidence": 0.7},
- ]
- strat.knowledge_state.key_facts = []
- strat.knowledge_state.uncertainties = []
- strat.knowledge_state.search_history = []
- strat._assess_answer()
- # spread=0.1, NOT < 0.1, so base stays 0.8
- assert strat.knowledge_state.confidence == pytest.approx(0.8)
-
- def test_wide_spread_no_reduction(self):
- strat = _make_strategy()
- strat.knowledge_state.candidate_answers = [
- {"answer": "A", "confidence": 0.9},
- {"answer": "B", "confidence": 0.3},
- ]
- strat.knowledge_state.key_facts = []
- strat.knowledge_state.uncertainties = []
- strat.knowledge_state.search_history = []
- strat._assess_answer()
- assert strat.knowledge_state.confidence == pytest.approx(0.9)
-
-
-class TestAssessAnswerCandidatePenalty:
- """Test candidate_penalty for > 3 candidates."""
-
- def test_three_candidates_no_penalty(self):
- strat = _make_strategy()
- strat.knowledge_state.candidate_answers = [
- {"answer": "A", "confidence": 0.9},
- {"answer": "B", "confidence": 0.5},
- {"answer": "C", "confidence": 0.3},
- ]
- strat.knowledge_state.key_facts = []
- strat.knowledge_state.uncertainties = []
- strat.knowledge_state.search_history = []
- strat._assess_answer()
- # spread = 0.9-0.5=0.4 > 0.1 => no reduction, base=0.9
- # no candidate_penalty (3 candidates, threshold > 3)
- assert strat.knowledge_state.confidence == pytest.approx(0.9)
-
- def test_four_candidates_small_penalty(self):
- strat = _make_strategy()
- strat.knowledge_state.candidate_answers = [
- {"answer": "A", "confidence": 0.8},
- {"answer": "B", "confidence": 0.3},
- {"answer": "C", "confidence": 0.2},
- {"answer": "D", "confidence": 0.1},
- ]
- strat.knowledge_state.key_facts = []
- strat.knowledge_state.uncertainties = []
- strat.knowledge_state.search_history = []
- strat._assess_answer()
- # base=0.8, spread=0.5 no reduction, candidate_penalty = (4-3)*0.05 = 0.05
- assert strat.knowledge_state.confidence == pytest.approx(0.75)
-
- def test_candidate_penalty_capped_at_0_15(self):
- strat = _make_strategy()
- strat.knowledge_state.candidate_answers = [
- {"answer": f"ans{i}", "confidence": 0.9 - i * 0.05}
- for i in range(10)
- ]
- strat.knowledge_state.key_facts = []
- strat.knowledge_state.uncertainties = []
- strat.knowledge_state.search_history = []
- strat._assess_answer()
- # 10 candidates, spread = 0.9-0.85=0.05 < 0.1 => base=0.9*0.8=0.72
- # candidate_penalty = min((10-3)*0.05, 0.15) = min(0.35, 0.15) = 0.15
- assert strat.knowledge_state.confidence == pytest.approx(0.72 - 0.15)
-
-
-class TestAssessAnswerCap:
- """Test the 0.95 confidence cap."""
-
- def test_cap_at_0_95(self):
- strat = _make_strategy()
- strat.knowledge_state.candidate_answers = [
- {"answer": "A", "confidence": 0.99}
- ]
- strat.knowledge_state.key_facts = ["f"] * 5 # +0.2 boost (capped)
- strat.knowledge_state.uncertainties = []
- strat.knowledge_state.search_history = [
- {"query": "q"}
- ] * 10 # +0.1 boost (capped)
- strat._assess_answer()
- # base=0.99 + 0.2 + 0.1 = 1.29, capped at 0.95
- assert strat.knowledge_state.confidence == 0.95
-
- def test_exactly_at_cap(self):
- """When all components sum to exactly 0.95."""
- strat = _make_strategy()
- strat.knowledge_state.candidate_answers = [
- {"answer": "A", "confidence": 0.95}
- ]
- strat.knowledge_state.key_facts = []
- strat.knowledge_state.uncertainties = []
- strat.knowledge_state.search_history = []
- strat._assess_answer()
- assert strat.knowledge_state.confidence == 0.95
-
-
-class TestAssessAnswerCombined:
- """Test _assess_answer with multiple factors combined."""
-
- def test_all_factors_combined(self):
- strat = _make_strategy()
- strat.knowledge_state.candidate_answers = [
- {"answer": "A", "confidence": 0.7},
- {"answer": "B", "confidence": 0.3},
- {"answer": "C", "confidence": 0.2},
- {"answer": "D", "confidence": 0.1},
- ]
- strat.knowledge_state.key_facts = ["f1", "f2"] # +0.10
- strat.knowledge_state.uncertainties = ["u1"] # -0.05
- strat.knowledge_state.search_history = [{"query": "q"}] * 2 # +0.04
- strat._assess_answer()
- # base=0.7 (spread=0.4, no reduction)
- # fact_boost=0.10, search_boost=0.04, uncertainty_penalty=0.05
- # candidate_penalty=(4-3)*0.05=0.05
- # total = 0.7 + 0.10 + 0.04 - 0.05 - 0.05 = 0.74
- assert strat.knowledge_state.confidence == pytest.approx(0.74)
-
- def test_negative_result_possible(self):
- """If penalties exceed base + boosts, confidence can go negative."""
- strat = _make_strategy()
- strat.knowledge_state.candidate_answers = [
- {"answer": "A", "confidence": 0.1},
- {
- "answer": "B",
- "confidence": 0.09,
- }, # spread=0.01 < 0.1 => base=0.1*0.8=0.08
- {"answer": "C", "confidence": 0.05},
- {"answer": "D", "confidence": 0.04},
- {"answer": "E", "confidence": 0.03},
- {"answer": "F", "confidence": 0.02},
- ]
- strat.knowledge_state.key_facts = []
- strat.knowledge_state.uncertainties = ["u"] * 4 # -0.2
- strat.knowledge_state.search_history = []
- strat._assess_answer()
- # base=0.08, candidate_penalty=min((6-3)*0.05,0.15)=0.15, uncertainty=0.2
- # total = 0.08 - 0.2 - 0.15 = -0.27
- assert strat.knowledge_state.confidence < 0
-
- def test_close_spread_with_boosts(self):
- """Close spread reduction combined with fact/search boosts."""
- strat = _make_strategy()
- strat.knowledge_state.candidate_answers = [
- {"answer": "A", "confidence": 0.9},
- {"answer": "B", "confidence": 0.88},
- ]
- strat.knowledge_state.key_facts = ["f"] * 4 # +0.2
- strat.knowledge_state.uncertainties = []
- strat.knowledge_state.search_history = [{"query": "q"}] * 5 # +0.1
- strat._assess_answer()
- # spread=0.02 < 0.1 => base = 0.9*0.8 = 0.72
- # total = 0.72 + 0.2 + 0.1 = 1.02, capped at 0.95
- assert strat.knowledge_state.confidence == 0.95
diff --git a/tests/advanced_search_system/strategies/test_iterative_reasoning_pure_logic.py b/tests/advanced_search_system/strategies/test_iterative_reasoning_pure_logic.py
deleted file mode 100644
index dbfd9e0608..0000000000
--- a/tests/advanced_search_system/strategies/test_iterative_reasoning_pure_logic.py
+++ /dev/null
@@ -1,198 +0,0 @@
-"""
-Pure-logic tests for IterativeReasoningStrategy._assess_answer
-and KnowledgeState.to_string.
-
-Tests the multi-factor confidence model (spread penalty, fact boost,
-uncertainty penalty, search boost, candidate penalty, 0.95 cap) and
-knowledge state formatting — no LLM or search calls.
-"""
-
-from unittest.mock import Mock
-
-from local_deep_research.advanced_search_system.strategies.iterative_reasoning_strategy import (
- IterativeReasoningStrategy,
- KnowledgeState,
-)
-
-
-def _make_strategy(
- candidate_answers=None,
- key_facts=None,
- uncertainties=None,
- search_history=None,
-):
- """Build a minimal Mock with a KnowledgeState."""
- s = Mock(spec=[])
- s.knowledge_state = KnowledgeState(
- original_query="test query",
- candidate_answers=candidate_answers or [],
- key_facts=key_facts or [],
- uncertainties=uncertainties or [],
- search_history=search_history or [],
- )
- return s
-
-
-# ---------------------------------------------------------------------------
-# KnowledgeState.to_string
-# ---------------------------------------------------------------------------
-
-
-class TestKnowledgeStateToString:
- """Verify knowledge state formatting."""
-
- def test_empty_state(self):
- """Empty state shows 'Nothing yet' for facts and uncertainties."""
- ks = KnowledgeState(original_query="What is X?")
- result = ks.to_string()
- assert "What is X?" in result
- assert "Nothing yet" in result
- assert "No searches yet" in result
- assert "None yet" in result
-
- def test_with_facts(self):
- """Key facts are listed."""
- ks = KnowledgeState(
- original_query="Q",
- key_facts=["Fact A", "Fact B"],
- )
- result = ks.to_string()
- assert "Fact A" in result
- assert "Fact B" in result
-
- def test_with_candidates(self):
- """Candidates are sorted by confidence descending."""
- ks = KnowledgeState(
- original_query="Q",
- candidate_answers=[
- {"answer": "Low", "confidence": 0.3},
- {"answer": "High", "confidence": 0.9},
- ],
- )
- result = ks.to_string()
- # High should appear before Low
- assert result.index("High") < result.index("Low")
-
- def test_search_history_shows_last_three(self):
- """Only last 3 searches are shown."""
- ks = KnowledgeState(
- original_query="Q",
- search_history=[{"query": f"search {i}"} for i in range(5)],
- )
- result = ks.to_string()
- assert "search 2" in result
- assert "search 4" in result
- # search 0 and 1 should not be shown (only last 3)
- assert "search 0" not in result
-
- def test_confidence_formatted(self):
- """Current confidence is formatted as percentage."""
- ks = KnowledgeState(original_query="Q", confidence=0.75)
- result = ks.to_string()
- assert "75.0%" in result
-
-
-# ---------------------------------------------------------------------------
-# _assess_answer
-# ---------------------------------------------------------------------------
-
-
-class TestAssessAnswer:
- """Verify multi-factor confidence assessment."""
-
- def _assess(self, **kwargs):
- s = _make_strategy(**kwargs)
- IterativeReasoningStrategy._assess_answer(s)
- return s.knowledge_state.confidence
-
- def test_no_candidates(self):
- """No candidates -> confidence 0.0."""
- assert self._assess(candidate_answers=[]) == 0.0
-
- def test_single_candidate_base(self):
- """Single candidate: confidence = candidate confidence + boosts."""
- conf = self._assess(
- candidate_answers=[{"answer": "A", "confidence": 0.7}],
- )
- # base 0.7 + fact_boost 0 + search_boost 0 - uncertainty 0 - candidate_penalty 0
- assert abs(conf - 0.7) < 1e-9
-
- def test_close_spread_penalty(self):
- """Two candidates within 0.1 spread -> 20% reduction of base."""
- conf = self._assess(
- candidate_answers=[
- {"answer": "A", "confidence": 0.8},
- {"answer": "B", "confidence": 0.75},
- ],
- )
- # spread = 0.05 < 0.1 -> base = 0.8 * 0.8 = 0.64
- assert abs(conf - 0.64) < 1e-9
-
- def test_wide_spread_no_penalty(self):
- """Two candidates with spread >= 0.1 -> no reduction."""
- conf = self._assess(
- candidate_answers=[
- {"answer": "A", "confidence": 0.8},
- {"answer": "B", "confidence": 0.5},
- ],
- )
- # spread = 0.3 >= 0.1 -> base stays 0.8
- assert abs(conf - 0.8) < 1e-9
-
- def test_fact_boost(self):
- """Key facts add 0.05 each, capped at 0.2."""
- conf = self._assess(
- candidate_answers=[{"answer": "A", "confidence": 0.5}],
- key_facts=["f1", "f2", "f3"],
- )
- # base 0.5 + fact_boost min(3*0.05, 0.2) = 0.15
- assert abs(conf - 0.65) < 1e-9
-
- def test_fact_boost_capped(self):
- """Fact boost capped at 0.2."""
- conf = self._assess(
- candidate_answers=[{"answer": "A", "confidence": 0.5}],
- key_facts=[f"f{i}" for i in range(10)],
- )
- # base 0.5 + fact_boost 0.2
- assert abs(conf - 0.7) < 1e-9
-
- def test_uncertainty_penalty(self):
- """Uncertainties subtract 0.05 each, capped at 0.2."""
- conf = self._assess(
- candidate_answers=[{"answer": "A", "confidence": 0.8}],
- uncertainties=["u1", "u2"],
- )
- # base 0.8 - uncertainty min(2*0.05, 0.2) = 0.1
- assert abs(conf - 0.7) < 1e-9
-
- def test_search_boost(self):
- """Search history adds 0.02 each, capped at 0.1."""
- conf = self._assess(
- candidate_answers=[{"answer": "A", "confidence": 0.5}],
- search_history=[{"query": f"q{i}"} for i in range(3)],
- )
- # base 0.5 + search_boost min(3*0.02, 0.1) = 0.06
- assert abs(conf - 0.56) < 1e-9
-
- def test_candidate_penalty(self):
- """More than 3 candidates incur penalty of 0.05 each, capped at 0.15."""
- conf = self._assess(
- candidate_answers=[
- {"answer": f"A{i}", "confidence": 0.8 - i * 0.15}
- for i in range(5)
- ],
- )
- # 5 candidates -> penalty = min((5-3)*0.05, 0.15) = 0.1
- # spread: 0.8 vs 0.65 = 0.15 >= 0.1 -> no spread penalty
- # base 0.8 - 0.1 = 0.7
- assert abs(conf - 0.7) < 1e-9
-
- def test_capped_at_095(self):
- """Confidence never exceeds 0.95."""
- conf = self._assess(
- candidate_answers=[{"answer": "A", "confidence": 0.95}],
- key_facts=[f"f{i}" for i in range(10)],
- search_history=[{"query": f"q{i}"} for i in range(10)],
- )
- assert conf == 0.95
diff --git a/tests/advanced_search_system/strategies/test_iterative_refinement_high_value.py b/tests/advanced_search_system/strategies/test_iterative_refinement_high_value.py
deleted file mode 100644
index 09a48101a2..0000000000
--- a/tests/advanced_search_system/strategies/test_iterative_refinement_high_value.py
+++ /dev/null
@@ -1,360 +0,0 @@
-"""
-High-value pure logic tests for IterativeRefinementStrategy.
-
-Focuses on constructor validation, _merge_results(), and _build_research_context()
-without any LLM or network calls.
-"""
-
-import pytest
-from unittest.mock import MagicMock, patch
-
-from local_deep_research.advanced_search_system.strategies.iterative_refinement_strategy import (
- IterativeRefinementStrategy,
-)
-
-
-# ---------------------------------------------------------------------------
-# Helpers
-# ---------------------------------------------------------------------------
-
-
-def _make_strategy_no_init():
- """Create an IterativeRefinementStrategy with __init__ bypassed."""
- with patch.object(
- IterativeRefinementStrategy, "__init__", lambda self, *a, **kw: None
- ):
- strategy = IterativeRefinementStrategy.__new__(
- IterativeRefinementStrategy
- )
- # Set minimal attributes that _merge_results / _build_research_context may need
- strategy.initial_strategy = MagicMock()
- strategy.initial_strategy.__class__.__name__ = "MockStrategy"
- strategy.progress_callback = None
- strategy.refinement_history = []
- return strategy
-
-
-def _make_strategy_via_constructor(**overrides):
- """Create an IterativeRefinementStrategy through the real constructor."""
- mock_model = MagicMock()
- mock_search = MagicMock()
- mock_initial = MagicMock()
- mock_initial.__class__.__name__ = "MockStrategy"
-
- defaults = {
- "model": mock_model,
- "search": mock_search,
- "initial_strategy": mock_initial,
- }
- defaults.update(overrides)
- return IterativeRefinementStrategy(**defaults)
-
-
-# ===========================================================================
-# Constructor validation tests
-# ===========================================================================
-
-
-class TestConstructorValidation:
- """Tests for parameter validation in __init__."""
-
- def test_confidence_threshold_below_zero_raises(self):
- with pytest.raises(ValueError, match="confidence_threshold"):
- _make_strategy_via_constructor(confidence_threshold=-0.1)
-
- def test_confidence_threshold_above_one_raises(self):
- with pytest.raises(ValueError, match="confidence_threshold"):
- _make_strategy_via_constructor(confidence_threshold=1.01)
-
- def test_confidence_threshold_zero_accepted(self):
- strategy = _make_strategy_via_constructor(confidence_threshold=0.0)
- assert strategy.confidence_threshold == 0.0
-
- def test_confidence_threshold_one_accepted(self):
- strategy = _make_strategy_via_constructor(confidence_threshold=1.0)
- assert strategy.confidence_threshold == 1.0
-
- def test_confidence_threshold_mid_accepted(self):
- strategy = _make_strategy_via_constructor(confidence_threshold=0.5)
- assert strategy.confidence_threshold == 0.5
-
- def test_max_refinements_negative_raises(self):
- with pytest.raises(ValueError, match="max_refinements"):
- _make_strategy_via_constructor(max_refinements=-1)
-
- def test_max_refinements_zero_accepted(self):
- strategy = _make_strategy_via_constructor(max_refinements=0)
- assert strategy.max_refinements == 0
-
- def test_max_refinements_positive_accepted(self):
- strategy = _make_strategy_via_constructor(max_refinements=5)
- assert strategy.max_refinements == 5
-
- def test_evaluation_frequency_zero_raises(self):
- with pytest.raises(ValueError, match="evaluation_frequency"):
- _make_strategy_via_constructor(evaluation_frequency=0)
-
- def test_evaluation_frequency_negative_raises(self):
- with pytest.raises(ValueError, match="evaluation_frequency"):
- _make_strategy_via_constructor(evaluation_frequency=-2)
-
- def test_evaluation_frequency_one_accepted(self):
- strategy = _make_strategy_via_constructor(evaluation_frequency=1)
- assert strategy.evaluation_frequency == 1
-
- def test_max_evaluation_tokens_zero_raises(self):
- with pytest.raises(ValueError, match="max_evaluation_tokens"):
- _make_strategy_via_constructor(max_evaluation_tokens=0)
-
- def test_max_evaluation_tokens_negative_raises(self):
- with pytest.raises(ValueError, match="max_evaluation_tokens"):
- _make_strategy_via_constructor(max_evaluation_tokens=-10)
-
- def test_max_evaluation_tokens_none_accepted(self):
- strategy = _make_strategy_via_constructor(max_evaluation_tokens=None)
- assert strategy.max_evaluation_tokens is None
-
- def test_max_evaluation_tokens_positive_accepted(self):
- strategy = _make_strategy_via_constructor(max_evaluation_tokens=500)
- assert strategy.max_evaluation_tokens == 500
-
- def test_defaults_stored_correctly(self):
- strategy = _make_strategy_via_constructor()
- assert strategy.max_refinements == 3
- assert strategy.confidence_threshold == 0.8
- assert strategy.evaluation_frequency == 1
- assert strategy.max_evaluation_tokens is None
- assert strategy.refinement_history == []
-
-
-# ===========================================================================
-# _merge_results tests
-# ===========================================================================
-
-
-class TestMergeResults:
- """Tests for _merge_results() pure dict merging logic."""
-
- def test_findings_appended_with_separator(self):
- strategy = _make_strategy_no_init()
- original = {"findings": [{"content": "A"}]}
- followup = {"findings": [{"content": "B"}]}
- merged = strategy._merge_results(original, followup, "follow query")
-
- # Should have original finding + separator + followup finding = 3
- assert len(merged["findings"]) == 3
- assert merged["findings"][0]["content"] == "A"
- assert merged["findings"][1]["type"] == "refinement_separator"
- assert "follow query" in merged["findings"][1]["phase"]
- assert merged["findings"][2]["content"] == "B"
-
- def test_findings_created_when_missing_in_original(self):
- strategy = _make_strategy_no_init()
- original = {}
- followup = {"findings": [{"content": "new"}]}
- merged = strategy._merge_results(original, followup, "q")
-
- assert "findings" in merged
- # separator + new finding
- assert len(merged["findings"]) == 2
-
- def test_no_findings_key_when_followup_lacks_findings(self):
- strategy = _make_strategy_no_init()
- original = {"findings": [{"content": "old"}]}
- followup = {}
- merged = strategy._merge_results(original, followup, "q")
-
- # Original findings preserved, nothing appended
- assert len(merged["findings"]) == 1
-
- def test_formatted_findings_concatenation(self):
- strategy = _make_strategy_no_init()
- original = {"formatted_findings": "Initial research text"}
- followup = {"formatted_findings": "Follow-up text"}
- merged = strategy._merge_results(original, followup, "my query")
-
- result = merged["formatted_findings"]
- assert "Initial research text" in result
- assert "Follow-up text" in result
- assert "---" in result
- assert "## Refinement: my query" in result
-
- def test_formatted_findings_with_empty_original(self):
- strategy = _make_strategy_no_init()
- original = {}
- followup = {"formatted_findings": "New findings"}
- merged = strategy._merge_results(original, followup, "q")
-
- assert "New findings" in merged["formatted_findings"]
- assert "## Refinement: q" in merged["formatted_findings"]
-
- def test_current_knowledge_updated_to_followup(self):
- strategy = _make_strategy_no_init()
- original = {"current_knowledge": "old knowledge"}
- followup = {"current_knowledge": "new knowledge"}
- merged = strategy._merge_results(original, followup, "q")
-
- assert merged["current_knowledge"] == "new knowledge"
-
- def test_current_knowledge_preserved_when_followup_lacks_it(self):
- strategy = _make_strategy_no_init()
- original = {"current_knowledge": "old knowledge"}
- followup = {}
- merged = strategy._merge_results(original, followup, "q")
-
- assert merged["current_knowledge"] == "old knowledge"
-
- def test_questions_by_iteration_offset_merge(self):
- strategy = _make_strategy_no_init()
- original = {"questions_by_iteration": {1: ["q1"], 2: ["q2"]}}
- followup = {"questions_by_iteration": {1: ["fq1"], 2: ["fq2"]}}
- merged = strategy._merge_results(original, followup, "q")
-
- qbi = merged["questions_by_iteration"]
- # max key in original is 2, so followup keys offset by 2
- assert qbi[1] == ["q1"]
- assert qbi[2] == ["q2"]
- assert qbi[3] == ["fq1"] # 2 + 1
- assert qbi[4] == ["fq2"] # 2 + 2
-
- def test_questions_by_iteration_created_when_missing_in_original(self):
- strategy = _make_strategy_no_init()
- original = {}
- followup = {"questions_by_iteration": {1: ["fq1"]}}
- merged = strategy._merge_results(original, followup, "q")
-
- qbi = merged["questions_by_iteration"]
- # max of empty dict = 0, so offset is 0
- assert qbi[1] == ["fq1"]
-
- def test_questions_by_iteration_empty_original_dict(self):
- strategy = _make_strategy_no_init()
- original = {"questions_by_iteration": {}}
- followup = {"questions_by_iteration": {1: ["fq1"]}}
- merged = strategy._merge_results(original, followup, "q")
-
- # Empty dict -> max_iter = 0, so key = 0 + 1 = 1
- assert merged["questions_by_iteration"][1] == ["fq1"]
-
- def test_merge_does_not_mutate_original(self):
- strategy = _make_strategy_no_init()
- original = {
- "findings": [{"content": "A"}],
- "formatted_findings": "text",
- }
- followup = {
- "findings": [{"content": "B"}],
- "formatted_findings": "new",
- }
- strategy._merge_results(original, followup, "q")
-
- # The original dict's top-level keys should still be present
- # (shallow copy means top-level is not mutated)
- assert "findings" in original
- assert original["formatted_findings"] == "text"
-
- def test_merge_empty_dicts(self):
- strategy = _make_strategy_no_init()
- merged = strategy._merge_results({}, {}, "q")
- assert isinstance(merged, dict)
-
- def test_separator_finding_truncates_long_query(self):
- strategy = _make_strategy_no_init()
- long_query = "x" * 200
- original = {"findings": []}
- followup = {"findings": [{"content": "B"}]}
- merged = strategy._merge_results(original, followup, long_query)
-
- separator = merged["findings"][0]
- # The phase truncates to first 100 chars
- assert len(separator["phase"]) <= len("Refinement: ") + 100
-
-
-# ===========================================================================
-# _build_research_context tests
-# ===========================================================================
-
-
-class TestBuildResearchContext:
- """Tests for _build_research_context() pure dict construction."""
-
- def test_basic_context_fields(self):
- strategy = _make_strategy_no_init()
- results = {
- "formatted_findings": "some findings",
- "all_links_of_system": [{"url": "http://a.com"}],
- }
- ctx = strategy._build_research_context(results, "test query")
-
- assert ctx["original_query"] == "test query"
- assert ctx["past_findings"] == "some findings"
- assert ctx["past_sources"] == [{"url": "http://a.com"}]
- assert ctx["resources"] == [{"url": "http://a.com"}]
-
- def test_delegate_strategy_name_cleaned(self):
- strategy = _make_strategy_no_init()
- strategy.initial_strategy.__class__.__name__ = "ParallelSearchStrategy"
- ctx = strategy._build_research_context({}, "q")
-
- # Code does .replace("Strategy", "").replace("SearchStrategy", "").lower()
- # "ParallelSearchStrategy" -> "ParallelSearch" -> "ParallelSearch" -> "parallelsearch"
- assert ctx["delegate_strategy"] == "parallelsearch"
-
- def test_delegate_strategy_name_strategy_suffix(self):
- strategy = _make_strategy_no_init()
- strategy.initial_strategy.__class__.__name__ = "StandardStrategy"
- ctx = strategy._build_research_context({}, "q")
-
- assert ctx["delegate_strategy"] == "standard"
-
- def test_questions_by_iteration_included_when_present(self):
- strategy = _make_strategy_no_init()
- results = {"questions_by_iteration": {1: ["q1"]}}
- ctx = strategy._build_research_context(results, "q")
-
- assert ctx["questions_by_iteration"] == {1: ["q1"]}
-
- def test_questions_by_iteration_absent_when_not_in_results(self):
- strategy = _make_strategy_no_init()
- ctx = strategy._build_research_context({}, "q")
-
- assert "questions_by_iteration" not in ctx
-
- def test_findings_included_when_present(self):
- strategy = _make_strategy_no_init()
- results = {"findings": [{"content": "finding1"}]}
- ctx = strategy._build_research_context(results, "q")
-
- assert ctx["findings"] == [{"content": "finding1"}]
-
- def test_findings_absent_when_not_in_results(self):
- strategy = _make_strategy_no_init()
- ctx = strategy._build_research_context({}, "q")
-
- assert "findings" not in ctx
-
- def test_defaults_for_missing_keys(self):
- strategy = _make_strategy_no_init()
- ctx = strategy._build_research_context({}, "q")
-
- assert ctx["past_findings"] == ""
- assert ctx["past_sources"] == []
- assert ctx["resources"] == []
-
- def test_context_with_all_fields_populated(self):
- strategy = _make_strategy_no_init()
- results = {
- "formatted_findings": "full findings",
- "all_links_of_system": [{"url": "http://x.com"}],
- "questions_by_iteration": {1: ["a"], 2: ["b"]},
- "findings": [{"content": "c"}],
- }
- ctx = strategy._build_research_context(results, "full query")
-
- assert ctx["original_query"] == "full query"
- assert ctx["past_findings"] == "full findings"
- assert ctx["past_sources"] == [{"url": "http://x.com"}]
- assert ctx["resources"] == [{"url": "http://x.com"}]
- assert ctx["questions_by_iteration"] == {1: ["a"], 2: ["b"]}
- assert ctx["findings"] == [{"content": "c"}]
- assert "delegate_strategy" in ctx
diff --git a/tests/advanced_search_system/strategies/test_iterative_refinement_strategy.py b/tests/advanced_search_system/strategies/test_iterative_refinement_strategy.py
deleted file mode 100644
index 71d984cc42..0000000000
--- a/tests/advanced_search_system/strategies/test_iterative_refinement_strategy.py
+++ /dev/null
@@ -1,1044 +0,0 @@
-"""
-Tests for IterativeRefinementStrategy.
-
-Tests cover:
-- Initialization with default and custom parameters
-- Parameter validation
-- LLM evaluation parsing and error handling
-- Result merging logic
-- Research context building
-- Full analyze_topic flow with mocked dependencies
-- Progress callback propagation
-- Refinement history tracking
-- Edge cases and error paths
-"""
-
-import pytest
-from unittest.mock import Mock, patch
-
-
-class TestIterativeRefinementStrategyInit:
- """Tests for IterativeRefinementStrategy initialization."""
-
- def test_init_with_defaults(self):
- """Initialize with default parameters."""
- from local_deep_research.advanced_search_system.strategies.iterative_refinement_strategy import (
- IterativeRefinementStrategy,
- )
-
- mock_initial = Mock()
- strategy = IterativeRefinementStrategy(
- model=Mock(),
- search=Mock(),
- initial_strategy=mock_initial,
- )
-
- assert strategy.evaluation_frequency == 1
- assert strategy.max_refinements == 3
- assert strategy.confidence_threshold == 0.8
- assert strategy.max_evaluation_tokens is None
- assert strategy.initial_strategy is mock_initial
- assert strategy.refinement_history == []
-
- def test_init_with_custom_params(self):
- """Initialize with custom parameters."""
- from local_deep_research.advanced_search_system.strategies.iterative_refinement_strategy import (
- IterativeRefinementStrategy,
- )
-
- strategy = IterativeRefinementStrategy(
- model=Mock(),
- search=Mock(),
- initial_strategy=Mock(),
- evaluation_frequency=2,
- max_refinements=5,
- confidence_threshold=0.9,
- max_evaluation_tokens=1000,
- )
-
- assert strategy.evaluation_frequency == 2
- assert strategy.max_refinements == 5
- assert strategy.confidence_threshold == 0.9
- assert strategy.max_evaluation_tokens == 1000
-
- def test_init_invalid_confidence_threshold_too_high(self):
- """Raises ValueError for confidence_threshold > 1."""
- from local_deep_research.advanced_search_system.strategies.iterative_refinement_strategy import (
- IterativeRefinementStrategy,
- )
-
- with pytest.raises(ValueError, match="confidence_threshold"):
- IterativeRefinementStrategy(
- model=Mock(),
- search=Mock(),
- initial_strategy=Mock(),
- confidence_threshold=1.5,
- )
-
- def test_init_invalid_confidence_threshold_negative(self):
- """Raises ValueError for negative confidence_threshold."""
- from local_deep_research.advanced_search_system.strategies.iterative_refinement_strategy import (
- IterativeRefinementStrategy,
- )
-
- with pytest.raises(ValueError, match="confidence_threshold"):
- IterativeRefinementStrategy(
- model=Mock(),
- search=Mock(),
- initial_strategy=Mock(),
- confidence_threshold=-0.1,
- )
-
- def test_init_invalid_max_refinements(self):
- """Raises ValueError for negative max_refinements."""
- from local_deep_research.advanced_search_system.strategies.iterative_refinement_strategy import (
- IterativeRefinementStrategy,
- )
-
- with pytest.raises(ValueError, match="max_refinements"):
- IterativeRefinementStrategy(
- model=Mock(),
- search=Mock(),
- initial_strategy=Mock(),
- max_refinements=-1,
- )
-
- def test_init_invalid_evaluation_frequency(self):
- """Raises ValueError for evaluation_frequency < 1."""
- from local_deep_research.advanced_search_system.strategies.iterative_refinement_strategy import (
- IterativeRefinementStrategy,
- )
-
- with pytest.raises(ValueError, match="evaluation_frequency"):
- IterativeRefinementStrategy(
- model=Mock(),
- search=Mock(),
- initial_strategy=Mock(),
- evaluation_frequency=0,
- )
-
- def test_init_invalid_max_evaluation_tokens(self):
- """Raises ValueError for non-positive max_evaluation_tokens."""
- from local_deep_research.advanced_search_system.strategies.iterative_refinement_strategy import (
- IterativeRefinementStrategy,
- )
-
- with pytest.raises(ValueError, match="max_evaluation_tokens"):
- IterativeRefinementStrategy(
- model=Mock(),
- search=Mock(),
- initial_strategy=Mock(),
- max_evaluation_tokens=0,
- )
-
- def test_init_boundary_values(self):
- """Accepts boundary parameter values."""
- from local_deep_research.advanced_search_system.strategies.iterative_refinement_strategy import (
- IterativeRefinementStrategy,
- )
-
- # All at boundaries should not raise
- strategy = IterativeRefinementStrategy(
- model=Mock(),
- search=Mock(),
- initial_strategy=Mock(),
- confidence_threshold=0.0,
- max_refinements=0,
- evaluation_frequency=1,
- )
-
- assert strategy.confidence_threshold == 0.0
- assert strategy.max_refinements == 0
-
-
-class TestEvaluateWithLlm:
- """Tests for _evaluate_with_llm method."""
-
- def _make_strategy(self):
- from local_deep_research.advanced_search_system.strategies.iterative_refinement_strategy import (
- IterativeRefinementStrategy,
- )
-
- return IterativeRefinementStrategy(
- model=Mock(),
- search=Mock(),
- initial_strategy=Mock(),
- )
-
- def test_parses_valid_refine_response(self):
- """Parses valid REFINE JSON response."""
- strategy = self._make_strategy()
- strategy.model.invoke.return_value = Mock(
- content='{"action": "REFINE", "confidence": 0.6, "gaps": ["missing context"], "reasoning": "Need more data", "refinement_query": "What about X?"}'
- )
-
- result = strategy._evaluate_with_llm(
- {"formatted_findings": "findings", "all_links_of_system": []},
- "test query",
- 0,
- )
-
- assert result["action"] == "REFINE"
- assert result["confidence"] == 0.6
- assert result["gaps"] == ["missing context"]
- assert result["refinement_query"] == "What about X?"
-
- def test_parses_valid_complete_response(self):
- """Parses valid COMPLETE JSON response."""
- strategy = self._make_strategy()
- strategy.model.invoke.return_value = Mock(
- content='{"action": "COMPLETE", "confidence": 0.95, "gaps": [], "reasoning": "All good"}'
- )
-
- result = strategy._evaluate_with_llm(
- {"formatted_findings": "findings", "all_links_of_system": []},
- "test query",
- 0,
- )
-
- assert result["action"] == "COMPLETE"
- assert result["confidence"] == 0.95
-
- def test_clamps_confidence_to_0_1(self):
- """Clamps confidence to [0.0, 1.0] range."""
- strategy = self._make_strategy()
- strategy.model.invoke.return_value = Mock(
- content='{"action": "REFINE", "confidence": 1.5}'
- )
-
- result = strategy._evaluate_with_llm(
- {"formatted_findings": "", "all_links_of_system": []},
- "query",
- 0,
- )
-
- assert result["confidence"] == 1.0
-
- def test_clamps_negative_confidence(self):
- """Clamps negative confidence to 0.0."""
- strategy = self._make_strategy()
- strategy.model.invoke.return_value = Mock(
- content='{"action": "REFINE", "confidence": -0.5}'
- )
-
- result = strategy._evaluate_with_llm(
- {"formatted_findings": "", "all_links_of_system": []},
- "query",
- 0,
- )
-
- assert result["confidence"] == 0.0
-
- def test_missing_action_defaults_to_complete(self):
- """Missing action defaults to COMPLETE."""
- strategy = self._make_strategy()
- strategy.model.invoke.return_value = Mock(
- content='{"confidence": 0.7, "gaps": []}'
- )
-
- result = strategy._evaluate_with_llm(
- {"formatted_findings": "", "all_links_of_system": []},
- "query",
- 0,
- )
-
- assert result["action"] == "COMPLETE"
-
- def test_invalid_action_defaults_to_complete(self):
- """Invalid action value defaults to COMPLETE."""
- strategy = self._make_strategy()
- strategy.model.invoke.return_value = Mock(
- content='{"action": "INVALID_ACTION", "confidence": 0.5}'
- )
-
- result = strategy._evaluate_with_llm(
- {"formatted_findings": "", "all_links_of_system": []},
- "query",
- 0,
- )
-
- assert result["action"] == "COMPLETE"
-
- def test_non_list_gaps_replaced_with_empty(self):
- """Non-list gaps value is replaced with empty list."""
- strategy = self._make_strategy()
- strategy.model.invoke.return_value = Mock(
- content='{"action": "REFINE", "confidence": 0.5, "gaps": "not a list"}'
- )
-
- result = strategy._evaluate_with_llm(
- {"formatted_findings": "", "all_links_of_system": []},
- "query",
- 0,
- )
-
- assert result["gaps"] == []
-
- def test_missing_confidence_defaults_to_half(self):
- """Missing confidence defaults to 0.5."""
- strategy = self._make_strategy()
- strategy.model.invoke.return_value = Mock(
- content='{"action": "COMPLETE"}'
- )
-
- result = strategy._evaluate_with_llm(
- {"formatted_findings": "", "all_links_of_system": []},
- "query",
- 0,
- )
-
- assert result["confidence"] == 0.5
-
- def test_llm_exception_returns_complete(self):
- """LLM exception returns COMPLETE with 0.5 confidence."""
- strategy = self._make_strategy()
- strategy.model.invoke.side_effect = Exception("LLM failed")
-
- result = strategy._evaluate_with_llm(
- {"formatted_findings": "", "all_links_of_system": []},
- "query",
- 0,
- )
-
- assert result["action"] == "COMPLETE"
- assert result["confidence"] == 0.5
- assert "Evaluation error" in result["reasoning"]
-
- def test_malformed_json_returns_complete(self):
- """Malformed JSON returns COMPLETE."""
- strategy = self._make_strategy()
- strategy.model.invoke.return_value = Mock(
- content="This is not JSON at all"
- )
-
- result = strategy._evaluate_with_llm(
- {"formatted_findings": "", "all_links_of_system": []},
- "query",
- 0,
- )
-
- assert result["action"] == "COMPLETE"
-
- def test_truncates_findings_to_max_evaluation_tokens(self):
- """Truncates findings to max_evaluation_tokens."""
- from local_deep_research.advanced_search_system.strategies.iterative_refinement_strategy import (
- IterativeRefinementStrategy,
- )
-
- strategy = IterativeRefinementStrategy(
- model=Mock(),
- search=Mock(),
- initial_strategy=Mock(),
- max_evaluation_tokens=10,
- )
- strategy.model.invoke.return_value = Mock(
- content='{"action": "COMPLETE", "confidence": 0.9}'
- )
-
- long_findings = "x" * 1000
- strategy._evaluate_with_llm(
- {"formatted_findings": long_findings, "all_links_of_system": []},
- "query",
- 0,
- )
-
- # The prompt should contain truncated findings
- prompt_used = strategy.model.invoke.call_args[0][0]
- # The full 1000-char findings should NOT appear in the prompt
- assert "x" * 1000 not in prompt_used
- # But some truncated version should
- assert "x" * 10 in prompt_used
-
- def test_includes_previous_gaps_in_prompt(self):
- """Previous gaps are included in the evaluation prompt."""
- strategy = self._make_strategy()
- strategy.refinement_history = [
- {"evaluation": {"gaps": ["gap1", "gap2"]}},
- ]
- strategy.model.invoke.return_value = Mock(
- content='{"action": "COMPLETE", "confidence": 0.9}'
- )
-
- strategy._evaluate_with_llm(
- {"formatted_findings": "findings", "all_links_of_system": []},
- "query",
- 1,
- )
-
- prompt = strategy.model.invoke.call_args[0][0]
- assert "gap1" in prompt
- assert "gap2" in prompt
-
-
-class TestMergeResults:
- """Tests for _merge_results method."""
-
- def _make_strategy(self):
- from local_deep_research.advanced_search_system.strategies.iterative_refinement_strategy import (
- IterativeRefinementStrategy,
- )
-
- return IterativeRefinementStrategy(
- model=Mock(),
- search=Mock(),
- initial_strategy=Mock(),
- )
-
- def test_appends_followup_findings(self):
- """Followup findings are appended to original."""
- strategy = self._make_strategy()
-
- original = {"findings": [{"phase": "initial"}]}
- followup = {"findings": [{"phase": "followup"}]}
-
- merged = strategy._merge_results(original, followup, "followup query")
-
- # Should have: original + separator + followup = 3
- assert len(merged["findings"]) == 3
- assert merged["findings"][0]["phase"] == "initial"
- assert merged["findings"][1]["type"] == "refinement_separator"
- assert merged["findings"][2]["phase"] == "followup"
-
- def test_creates_findings_list_if_missing(self):
- """Creates findings list if not in original."""
- strategy = self._make_strategy()
-
- original = {}
- followup = {"findings": [{"phase": "followup"}]}
-
- merged = strategy._merge_results(original, followup, "query")
-
- assert "findings" in merged
- assert len(merged["findings"]) >= 1
-
- def test_merges_formatted_findings(self):
- """Formatted findings are concatenated with separator."""
- strategy = self._make_strategy()
-
- original = {"formatted_findings": "Original text"}
- followup = {"formatted_findings": "Followup text"}
-
- merged = strategy._merge_results(original, followup, "followup query")
-
- assert "Original text" in merged["formatted_findings"]
- assert "Followup text" in merged["formatted_findings"]
- assert "## Refinement:" in merged["formatted_findings"]
-
- def test_updates_current_knowledge(self):
- """Current knowledge is updated to latest followup."""
- strategy = self._make_strategy()
-
- original = {"current_knowledge": "old knowledge"}
- followup = {"current_knowledge": "new knowledge"}
-
- merged = strategy._merge_results(original, followup, "query")
-
- assert merged["current_knowledge"] == "new knowledge"
-
- def test_merges_questions_by_iteration_with_offset(self):
- """Follow-up questions are merged with offset keys."""
- strategy = self._make_strategy()
-
- original = {
- "questions_by_iteration": {1: ["Q1"], 2: ["Q2"]},
- }
- followup = {
- "questions_by_iteration": {1: ["FQ1"], 2: ["FQ2"]},
- }
-
- merged = strategy._merge_results(original, followup, "query")
-
- # Original has max key 2, followup keys should be 2+1=3, 2+2=4
- assert 1 in merged["questions_by_iteration"]
- assert 2 in merged["questions_by_iteration"]
- assert 3 in merged["questions_by_iteration"]
- assert 4 in merged["questions_by_iteration"]
- assert merged["questions_by_iteration"][3] == ["FQ1"]
- assert merged["questions_by_iteration"][4] == ["FQ2"]
-
- def test_does_not_mutate_original(self):
- """Original results dict is not mutated."""
- strategy = self._make_strategy()
-
- original = {
- "findings": [{"phase": "initial"}],
- "formatted_findings": "text",
- }
- original_copy = {
- "findings": [{"phase": "initial"}],
- "formatted_findings": "text",
- }
- followup = {"findings": [{"phase": "followup"}]}
-
- strategy._merge_results(original, followup, "query")
-
- # Original dict reference should have the same findings list length
- # because .copy() is shallow - but the original variable's list shouldn't grow
- assert len(original_copy["findings"]) == 1
-
- def test_handles_missing_followup_data(self):
- """Handles followup results with missing keys."""
- strategy = self._make_strategy()
-
- original = {"formatted_findings": "text"}
- followup = {} # No findings, no formatted_findings, no knowledge
-
- merged = strategy._merge_results(original, followup, "query")
-
- # Should not raise, original data preserved
- assert "text" in merged["formatted_findings"]
-
-
-class TestBuildResearchContext:
- """Tests for _build_research_context method."""
-
- def _make_strategy(self):
- from local_deep_research.advanced_search_system.strategies.iterative_refinement_strategy import (
- IterativeRefinementStrategy,
- )
-
- mock_initial = Mock()
- mock_initial.__class__.__name__ = "FocusedIterationStrategy"
- return IterativeRefinementStrategy(
- model=Mock(),
- search=Mock(),
- initial_strategy=mock_initial,
- )
-
- def test_includes_required_keys(self):
- """Context includes all required keys."""
- strategy = self._make_strategy()
-
- results = {
- "formatted_findings": "findings text",
- "all_links_of_system": [{"url": "https://example.com"}],
- }
-
- context = strategy._build_research_context(results, "test query")
-
- assert context["original_query"] == "test query"
- assert context["past_findings"] == "findings text"
- assert len(context["past_sources"]) == 1
- assert "delegate_strategy" in context
-
- def test_formats_delegate_strategy_name(self):
- """Delegate strategy name is formatted correctly."""
- strategy = self._make_strategy()
-
- context = strategy._build_research_context(
- {"formatted_findings": "", "all_links_of_system": []},
- "query",
- )
-
- # "FocusedIterationStrategy" -> remove "Strategy" -> "FocusedIteration" -> lower
- assert context["delegate_strategy"] == "focusediteration"
-
- def test_includes_questions_if_present(self):
- """Includes questions_by_iteration when present in results."""
- strategy = self._make_strategy()
-
- results = {
- "formatted_findings": "",
- "all_links_of_system": [],
- "questions_by_iteration": {1: ["Q1"]},
- }
-
- context = strategy._build_research_context(results, "query")
- assert "questions_by_iteration" in context
-
- def test_includes_findings_if_present(self):
- """Includes findings when present in results."""
- strategy = self._make_strategy()
-
- results = {
- "formatted_findings": "",
- "all_links_of_system": [],
- "findings": [{"phase": "test"}],
- }
-
- context = strategy._build_research_context(results, "query")
- assert "findings" in context
-
- def test_omits_optional_keys_when_absent(self):
- """Does not include optional keys when not in results."""
- strategy = self._make_strategy()
-
- results = {"formatted_findings": "", "all_links_of_system": []}
-
- context = strategy._build_research_context(results, "query")
- assert "questions_by_iteration" not in context
- assert "findings" not in context
-
-
-class TestSetProgressCallback:
- """Tests for set_progress_callback method."""
-
- def test_sets_callback_on_self(self):
- """Sets callback on the strategy itself."""
- from local_deep_research.advanced_search_system.strategies.iterative_refinement_strategy import (
- IterativeRefinementStrategy,
- )
-
- strategy = IterativeRefinementStrategy(
- model=Mock(),
- search=Mock(),
- initial_strategy=Mock(),
- )
-
- callback = Mock()
- strategy.set_progress_callback(callback)
-
- assert strategy.progress_callback is callback
-
- def test_propagates_callback_to_initial_strategy(self):
- """Propagates callback to initial strategy."""
- from local_deep_research.advanced_search_system.strategies.iterative_refinement_strategy import (
- IterativeRefinementStrategy,
- )
-
- mock_initial = Mock()
- strategy = IterativeRefinementStrategy(
- model=Mock(),
- search=Mock(),
- initial_strategy=mock_initial,
- )
-
- callback = Mock()
- strategy.set_progress_callback(callback)
-
- mock_initial.set_progress_callback.assert_called_once_with(callback)
-
-
-class TestAnalyzeTopic:
- """Tests for analyze_topic method."""
-
- def _make_strategy(self, **kwargs):
- from local_deep_research.advanced_search_system.strategies.iterative_refinement_strategy import (
- IterativeRefinementStrategy,
- )
-
- defaults = {
- "model": Mock(),
- "search": Mock(),
- "initial_strategy": Mock(),
- }
- defaults.update(kwargs)
- return IterativeRefinementStrategy(**defaults)
-
- def test_returns_error_on_none_initial_results(self):
- """Returns error response when initial strategy returns None."""
- mock_initial = Mock()
- mock_initial.analyze_topic.return_value = None
-
- strategy = self._make_strategy(initial_strategy=mock_initial)
- result = strategy.analyze_topic("test query")
-
- assert "error" in result
- assert result["findings"] == []
-
- def test_returns_error_on_empty_initial_results(self):
- """Returns error response when initial strategy returns empty dict."""
- mock_initial = Mock()
- mock_initial.analyze_topic.return_value = {}
-
- strategy = self._make_strategy(initial_strategy=mock_initial)
- result = strategy.analyze_topic("test query")
-
- assert "error" in result
-
- def test_passes_through_initial_error(self):
- """Passes through error from initial strategy."""
- mock_initial = Mock()
- mock_initial.analyze_topic.return_value = {
- "error": "Initial failed",
- "findings": [],
- }
-
- strategy = self._make_strategy(initial_strategy=mock_initial)
- result = strategy.analyze_topic("test query")
-
- assert result["error"] == "Initial failed"
-
- def test_skips_refinement_when_no_sources(self):
- """Skips refinement when initial results have no sources."""
- mock_initial = Mock()
- mock_initial.analyze_topic.return_value = {
- "findings": [{"phase": "initial"}],
- "formatted_findings": "Some findings",
- "all_links_of_system": [], # No sources
- }
-
- strategy = self._make_strategy(initial_strategy=mock_initial)
- result = strategy.analyze_topic("test query")
-
- assert "refinement_metadata" in result
- assert result["refinement_metadata"]["refinements_performed"] == 0
- assert (
- result["refinement_metadata"]["skipped_reason"]
- == "No initial sources found"
- )
-
- def test_stops_on_complete_evaluation(self):
- """Stops refinement when LLM evaluates as COMPLETE."""
- mock_initial = Mock()
- mock_initial.analyze_topic.return_value = {
- "findings": [{"phase": "initial"}],
- "formatted_findings": "Findings",
- "all_links_of_system": [{"url": "https://example.com"}],
- }
- mock_initial.__class__.__name__ = "TestStrategy"
-
- strategy = self._make_strategy(
- initial_strategy=mock_initial,
- max_refinements=5,
- )
-
- # LLM evaluates as COMPLETE on first evaluation
- with patch.object(
- strategy,
- "_evaluate_with_llm",
- return_value={
- "action": "COMPLETE",
- "confidence": 0.9,
- "gaps": [],
- "reasoning": "Research is complete",
- "refinement_query": None,
- },
- ):
- result = strategy.analyze_topic("test query")
-
- assert result["refinement_metadata"]["refinements_performed"] == 0
-
- def test_stops_on_confidence_threshold(self):
- """Stops refinement when confidence meets threshold."""
- mock_initial = Mock()
- mock_initial.analyze_topic.return_value = {
- "findings": [{"phase": "initial"}],
- "formatted_findings": "Findings",
- "all_links_of_system": [{"url": "https://example.com"}],
- }
- mock_initial.__class__.__name__ = "TestStrategy"
-
- strategy = self._make_strategy(
- initial_strategy=mock_initial,
- confidence_threshold=0.8,
- )
-
- with patch.object(
- strategy,
- "_evaluate_with_llm",
- return_value={
- "action": "REFINE",
- "confidence": 0.85, # Above threshold
- "gaps": ["minor gap"],
- "reasoning": "Good enough",
- "refinement_query": "minor question",
- },
- ):
- result = strategy.analyze_topic("test query")
-
- assert result["refinement_metadata"]["refinements_performed"] == 0
-
- def test_stops_when_no_refinement_query(self):
- """Stops when evaluation returns no refinement query."""
- mock_initial = Mock()
- mock_initial.analyze_topic.return_value = {
- "findings": [{"phase": "initial"}],
- "formatted_findings": "Findings",
- "all_links_of_system": [{"url": "https://example.com"}],
- }
- mock_initial.__class__.__name__ = "TestStrategy"
-
- strategy = self._make_strategy(initial_strategy=mock_initial)
-
- with patch.object(
- strategy,
- "_evaluate_with_llm",
- return_value={
- "action": "REFINE",
- "confidence": 0.3,
- "gaps": ["gap"],
- "reasoning": "Needs work",
- "refinement_query": None, # No query
- },
- ):
- result = strategy.analyze_topic("test query")
-
- assert result["refinement_metadata"]["refinements_performed"] == 0
-
- def test_max_refinements_enforced(self):
- """Max refinements limit is enforced."""
- mock_initial = Mock()
- mock_initial.analyze_topic.return_value = {
- "findings": [],
- "formatted_findings": "Findings",
- "all_links_of_system": [{"url": "https://example.com"}],
- "current_knowledge": "knowledge",
- }
- mock_initial.__class__.__name__ = "TestStrategy"
-
- strategy = self._make_strategy(
- initial_strategy=mock_initial,
- max_refinements=2,
- )
-
- # Always return REFINE with query
- with patch.object(
- strategy,
- "_evaluate_with_llm",
- return_value={
- "action": "REFINE",
- "confidence": 0.3,
- "gaps": ["gap"],
- "reasoning": "Needs work",
- "refinement_query": "Refine this",
- },
- ):
- with patch(
- "local_deep_research.advanced_search_system.strategies.iterative_refinement_strategy.EnhancedContextualFollowUpStrategy"
- ) as mock_followup_cls:
- mock_followup = Mock()
- mock_followup.analyze_topic.return_value = {
- "findings": [],
- "formatted_findings": "Refined",
- "all_links_of_system": [
- {"url": "https://new.com"},
- {"url": "https://new2.com"},
- ],
- "current_knowledge": "updated",
- }
- mock_followup_cls.return_value = mock_followup
-
- result = strategy.analyze_topic("test query")
-
- assert result["refinement_metadata"]["refinements_performed"] <= 2
-
- def test_stops_when_few_new_sources(self):
- """Stops when followup yields fewer than 2 new sources."""
- mock_initial = Mock()
- mock_initial.analyze_topic.return_value = {
- "findings": [],
- "formatted_findings": "Findings",
- "all_links_of_system": [{"url": "https://example.com"}],
- }
- mock_initial.__class__.__name__ = "TestStrategy"
-
- strategy = self._make_strategy(initial_strategy=mock_initial)
-
- with patch.object(
- strategy,
- "_evaluate_with_llm",
- return_value={
- "action": "REFINE",
- "confidence": 0.3,
- "gaps": ["gap"],
- "reasoning": "Needs work",
- "refinement_query": "Refine this",
- },
- ):
- with patch(
- "local_deep_research.advanced_search_system.strategies.iterative_refinement_strategy.EnhancedContextualFollowUpStrategy"
- ) as mock_followup_cls:
- mock_followup = Mock()
- mock_followup.analyze_topic.return_value = {
- "findings": [],
- "formatted_findings": "Refined",
- "all_links_of_system": [
- {"url": "https://single.com"}
- ], # Only 1 source
- }
- mock_followup_cls.return_value = mock_followup
-
- result = strategy.analyze_topic("test query")
-
- # Should stop after first refinement attempt due to few sources
- assert result["refinement_metadata"]["refinements_performed"] <= 1
-
- def test_includes_refinement_metadata(self):
- """Result includes refinement_metadata."""
- mock_initial = Mock()
- mock_initial.analyze_topic.return_value = {
- "findings": [],
- "formatted_findings": "Findings",
- "all_links_of_system": [{"url": "https://example.com"}],
- }
- mock_initial.__class__.__name__ = "TestStrategy"
-
- strategy = self._make_strategy(initial_strategy=mock_initial)
-
- with patch.object(
- strategy,
- "_evaluate_with_llm",
- return_value={
- "action": "COMPLETE",
- "confidence": 0.9,
- "gaps": [],
- "reasoning": "Done",
- },
- ):
- result = strategy.analyze_topic("test query")
-
- meta = result["refinement_metadata"]
- assert meta["strategy"] == "iterative_refinement"
- assert "refinements_performed" in meta
- assert "max_refinements" in meta
- assert "final_confidence" in meta
- assert "total_sources" in meta
- assert "refinement_history" in meta
-
- def test_source_deduplication(self):
- """Duplicate sources are deduplicated by URL."""
- mock_initial = Mock()
- mock_initial.analyze_topic.return_value = {
- "findings": [],
- "formatted_findings": "Findings",
- "all_links_of_system": [{"url": "https://example.com"}],
- }
- mock_initial.__class__.__name__ = "TestStrategy"
-
- strategy = self._make_strategy(initial_strategy=mock_initial)
-
- with patch.object(
- strategy,
- "_evaluate_with_llm",
- return_value={
- "action": "REFINE",
- "confidence": 0.3,
- "gaps": ["gap"],
- "reasoning": "Needs work",
- "refinement_query": "Refine",
- },
- ):
- with patch(
- "local_deep_research.advanced_search_system.strategies.iterative_refinement_strategy.EnhancedContextualFollowUpStrategy"
- ) as mock_followup_cls:
- mock_followup = Mock()
- mock_followup.analyze_topic.return_value = {
- "findings": [],
- "formatted_findings": "Refined",
- "all_links_of_system": [
- {"url": "https://example.com"}, # Duplicate
- {"url": "https://new.com"},
- ],
- "current_knowledge": "updated",
- }
- mock_followup_cls.return_value = mock_followup
-
- # Make next evaluation return COMPLETE to stop the loop
- call_count = [0]
-
- def eval_side_effect(*args):
- call_count[0] += 1
- if call_count[0] == 1:
- return {
- "action": "REFINE",
- "confidence": 0.3,
- "gaps": ["gap"],
- "reasoning": "Needs work",
- "refinement_query": "Refine",
- }
- return {
- "action": "COMPLETE",
- "confidence": 0.9,
- "gaps": [],
- "reasoning": "Done",
- }
-
- with patch.object(
- strategy, "_evaluate_with_llm", side_effect=eval_side_effect
- ):
- result = strategy.analyze_topic("test query")
-
- # Should have 2 unique URLs, not 3
- urls = [s.get("url") for s in result["all_links_of_system"]]
- assert len(set(urls)) == len(urls)
-
-
-class TestRefinementHistoryTracking:
- """Tests for refinement history tracking."""
-
- def test_history_populated_after_evaluation(self):
- """Refinement history is populated after LLM evaluation."""
- from local_deep_research.advanced_search_system.strategies.iterative_refinement_strategy import (
- IterativeRefinementStrategy,
- )
-
- mock_initial = Mock()
- mock_initial.analyze_topic.return_value = {
- "findings": [],
- "formatted_findings": "Findings",
- "all_links_of_system": [{"url": "https://example.com"}],
- }
- mock_initial.__class__.__name__ = "TestStrategy"
-
- strategy = IterativeRefinementStrategy(
- model=Mock(),
- search=Mock(),
- initial_strategy=mock_initial,
- )
-
- with patch.object(
- strategy,
- "_evaluate_with_llm",
- return_value={
- "action": "COMPLETE",
- "confidence": 0.9,
- "gaps": ["gap1"],
- "reasoning": "All good",
- "refinement_query": None,
- },
- ):
- strategy.analyze_topic("test query")
-
- assert len(strategy.refinement_history) == 1
- entry = strategy.refinement_history[0]
- assert entry["iteration"] == 1
- assert entry["action"] == "COMPLETE"
- assert entry["confidence"] == 0.9
- assert entry["gaps"] == ["gap1"]
- assert entry["reasoning"] == "All good"
-
- def test_empty_history_when_no_sources(self):
- """No history when refinement skipped due to no sources."""
- from local_deep_research.advanced_search_system.strategies.iterative_refinement_strategy import (
- IterativeRefinementStrategy,
- )
-
- mock_initial = Mock()
- mock_initial.analyze_topic.return_value = {
- "findings": [],
- "formatted_findings": "Findings",
- "all_links_of_system": [],
- }
-
- strategy = IterativeRefinementStrategy(
- model=Mock(),
- search=Mock(),
- initial_strategy=mock_initial,
- )
-
- strategy.analyze_topic("test query")
- assert strategy.refinement_history == []
-
- def test_zero_max_refinements_produces_no_history(self):
- """Zero max_refinements produces no refinement history."""
- from local_deep_research.advanced_search_system.strategies.iterative_refinement_strategy import (
- IterativeRefinementStrategy,
- )
-
- mock_initial = Mock()
- mock_initial.analyze_topic.return_value = {
- "findings": [],
- "formatted_findings": "Findings",
- "all_links_of_system": [{"url": "https://example.com"}],
- }
-
- strategy = IterativeRefinementStrategy(
- model=Mock(),
- search=Mock(),
- initial_strategy=mock_initial,
- max_refinements=0,
- )
-
- result = strategy.analyze_topic("test query")
- assert result["refinement_metadata"]["refinements_performed"] == 0
diff --git a/tests/advanced_search_system/strategies/test_iterdrag_strategy.py b/tests/advanced_search_system/strategies/test_iterdrag_strategy.py
deleted file mode 100644
index ec886379c7..0000000000
--- a/tests/advanced_search_system/strategies/test_iterdrag_strategy.py
+++ /dev/null
@@ -1,731 +0,0 @@
-"""
-Tests for advanced_search_system/strategies/iterdrag_strategy.py
-
-Tests cover:
-- IterDRAGStrategy initialization
-- _update_progress method
-- _generate_subqueries method
-- analyze_topic method
-- Error handling and fallback behavior
-"""
-
-from unittest.mock import Mock, patch
-
-
-class TestIterDRAGStrategyInit:
- """Tests for IterDRAGStrategy initialization."""
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.CitationHandler"
- )
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.DecompositionQuestionGenerator"
- )
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.StandardKnowledge"
- )
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.FindingsRepository"
- )
- def test_init_with_defaults(
- self, mock_findings, mock_knowledge, mock_question, mock_citation
- ):
- """Test initialization with default values."""
- from local_deep_research.advanced_search_system.strategies.iterdrag_strategy import (
- IterDRAGStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = IterDRAGStrategy(search=mock_search, model=mock_model)
-
- assert strategy.search is mock_search
- assert strategy.model is mock_model
- assert strategy.max_iterations == 3
- assert strategy.subqueries_per_iteration == 2
- assert strategy.progress_callback is None
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.CitationHandler"
- )
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.DecompositionQuestionGenerator"
- )
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.StandardKnowledge"
- )
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.FindingsRepository"
- )
- def test_init_with_custom_values(
- self, mock_findings, mock_knowledge, mock_question, mock_citation
- ):
- """Test initialization with custom values."""
- from local_deep_research.advanced_search_system.strategies.iterdrag_strategy import (
- IterDRAGStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = IterDRAGStrategy(
- search=mock_search,
- model=mock_model,
- max_iterations=5,
- subqueries_per_iteration=4,
- settings_snapshot={"key": "value"},
- )
-
- assert strategy.max_iterations == 5
- assert strategy.subqueries_per_iteration == 4
- assert strategy.settings_snapshot == {"key": "value"}
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.CitationHandler"
- )
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.DecompositionQuestionGenerator"
- )
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.StandardKnowledge"
- )
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.FindingsRepository"
- )
- def test_init_creates_components(
- self, mock_findings, mock_knowledge, mock_question, mock_citation
- ):
- """Test that initialization creates required components."""
- from local_deep_research.advanced_search_system.strategies.iterdrag_strategy import (
- IterDRAGStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- IterDRAGStrategy(search=mock_search, model=mock_model)
-
- mock_citation.assert_called_once_with(
- mock_model, settings_snapshot=None
- )
- mock_question.assert_called_once_with(mock_model)
- mock_knowledge.assert_called_once_with(mock_model)
- mock_findings.assert_called_once_with(mock_model)
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.CitationHandler"
- )
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.DecompositionQuestionGenerator"
- )
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.StandardKnowledge"
- )
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.FindingsRepository"
- )
- def test_init_with_existing_links(
- self, mock_findings, mock_knowledge, mock_question, mock_citation
- ):
- """Test initialization with existing links."""
- from local_deep_research.advanced_search_system.strategies.iterdrag_strategy import (
- IterDRAGStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
- existing_links = ["http://example.com", "http://test.com"]
-
- strategy = IterDRAGStrategy(
- search=mock_search,
- model=mock_model,
- all_links_of_system=existing_links,
- )
-
- assert strategy.all_links_of_system == existing_links
-
-
-class TestUpdateProgress:
- """Tests for _update_progress method."""
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.CitationHandler"
- )
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.DecompositionQuestionGenerator"
- )
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.StandardKnowledge"
- )
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.FindingsRepository"
- )
- def test_update_progress_with_callback(
- self, mock_findings, mock_knowledge, mock_question, mock_citation
- ):
- """Test that progress callback is called when set."""
- from local_deep_research.advanced_search_system.strategies.iterdrag_strategy import (
- IterDRAGStrategy,
- )
-
- strategy = IterDRAGStrategy(search=Mock(), model=Mock())
- callback = Mock()
- strategy.progress_callback = callback
-
- strategy._update_progress("Test message", 50, {"key": "value"})
-
- callback.assert_called_once_with("Test message", 50, {"key": "value"})
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.CitationHandler"
- )
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.DecompositionQuestionGenerator"
- )
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.StandardKnowledge"
- )
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.FindingsRepository"
- )
- def test_update_progress_without_callback(
- self, mock_findings, mock_knowledge, mock_question, mock_citation
- ):
- """Test that no error occurs when callback is not set."""
- from local_deep_research.advanced_search_system.strategies.iterdrag_strategy import (
- IterDRAGStrategy,
- )
-
- strategy = IterDRAGStrategy(search=Mock(), model=Mock())
-
- # Should not raise
- strategy._update_progress("Test message", 50, {"key": "value"})
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.CitationHandler"
- )
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.DecompositionQuestionGenerator"
- )
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.StandardKnowledge"
- )
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.FindingsRepository"
- )
- def test_update_progress_with_none_metadata(
- self, mock_findings, mock_knowledge, mock_question, mock_citation
- ):
- """Test that None metadata is converted to empty dict."""
- from local_deep_research.advanced_search_system.strategies.iterdrag_strategy import (
- IterDRAGStrategy,
- )
-
- strategy = IterDRAGStrategy(search=Mock(), model=Mock())
- callback = Mock()
- strategy.progress_callback = callback
-
- strategy._update_progress("Test message", 50)
-
- callback.assert_called_once_with("Test message", 50, {})
-
-
-class TestGenerateSubqueries:
- """Tests for _generate_subqueries method."""
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.CitationHandler"
- )
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.DecompositionQuestionGenerator"
- )
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.StandardKnowledge"
- )
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.FindingsRepository"
- )
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.get_setting_from_snapshot"
- )
- def test_generate_subqueries_success(
- self,
- mock_get_setting,
- mock_findings,
- mock_knowledge,
- mock_question,
- mock_citation,
- ):
- """Test successful sub-query generation."""
- from local_deep_research.advanced_search_system.strategies.iterdrag_strategy import (
- IterDRAGStrategy,
- )
-
- mock_get_setting.return_value = 3
-
- mock_question_gen = Mock()
- mock_question_gen.generate_questions.return_value = [
- "Sub-query 1",
- "Sub-query 2",
- "Sub-query 3",
- ]
- mock_question.return_value = mock_question_gen
-
- strategy = IterDRAGStrategy(search=Mock(), model=Mock())
-
- result = strategy._generate_subqueries(
- "Main query", [{"title": "Result 1"}], "Current knowledge"
- )
-
- assert len(result) == 3
- assert "Sub-query 1" in result
- mock_question_gen.generate_questions.assert_called_once()
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.CitationHandler"
- )
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.DecompositionQuestionGenerator"
- )
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.StandardKnowledge"
- )
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.FindingsRepository"
- )
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.get_setting_from_snapshot"
- )
- def test_generate_subqueries_handles_exception(
- self,
- mock_get_setting,
- mock_findings,
- mock_knowledge,
- mock_question,
- mock_citation,
- ):
- """Test that exceptions return empty list."""
- from local_deep_research.advanced_search_system.strategies.iterdrag_strategy import (
- IterDRAGStrategy,
- )
-
- mock_get_setting.return_value = 3
-
- mock_question_gen = Mock()
- mock_question_gen.generate_questions.side_effect = RuntimeError(
- "LLM error"
- )
- mock_question.return_value = mock_question_gen
-
- strategy = IterDRAGStrategy(search=Mock(), model=Mock())
-
- result = strategy._generate_subqueries("Main query", [], "")
-
- assert result == []
-
-
-class TestAnalyzeTopic:
- """Tests for analyze_topic method."""
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.CitationHandler"
- )
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.DecompositionQuestionGenerator"
- )
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.StandardKnowledge"
- )
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.FindingsRepository"
- )
- def test_analyze_topic_no_search_engine(
- self, mock_findings, mock_knowledge, mock_question, mock_citation
- ):
- """Test analyze_topic when search engine is None."""
- from local_deep_research.advanced_search_system.strategies.iterdrag_strategy import (
- IterDRAGStrategy,
- )
-
- strategy = IterDRAGStrategy(search=None, model=Mock())
-
- result = strategy.analyze_topic("Test query")
-
- assert "error" in result
- assert result["findings"] == []
- assert result["iterations"] == 0
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.CitationHandler"
- )
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.DecompositionQuestionGenerator"
- )
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.StandardKnowledge"
- )
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.FindingsRepository"
- )
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.extract_links_from_search_results"
- )
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.get_setting_from_snapshot"
- )
- def test_analyze_topic_no_initial_results(
- self,
- mock_get_setting,
- mock_extract_links,
- mock_findings,
- mock_knowledge,
- mock_question,
- mock_citation,
- ):
- """Test analyze_topic when initial search returns no results."""
- from local_deep_research.advanced_search_system.strategies.iterdrag_strategy import (
- IterDRAGStrategy,
- )
-
- mock_get_setting.return_value = 3
- mock_extract_links.return_value = []
-
- mock_search = Mock()
- mock_search.run.return_value = []
-
- mock_question_gen = Mock()
- mock_question_gen.generate_questions.return_value = []
- mock_question.return_value = mock_question_gen
-
- mock_findings_repo = Mock()
- mock_findings.return_value = mock_findings_repo
-
- strategy = IterDRAGStrategy(search=mock_search, model=Mock())
-
- result = strategy.analyze_topic("Test query")
-
- assert "findings" in result
- mock_search.run.assert_called_once_with("Test query")
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.CitationHandler"
- )
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.DecompositionQuestionGenerator"
- )
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.StandardKnowledge"
- )
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.FindingsRepository"
- )
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.extract_links_from_search_results"
- )
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.get_setting_from_snapshot"
- )
- def test_analyze_topic_with_subqueries(
- self,
- mock_get_setting,
- mock_extract_links,
- mock_findings,
- mock_knowledge,
- mock_question,
- mock_citation,
- ):
- """Test analyze_topic with sub-query generation."""
- from local_deep_research.advanced_search_system.strategies.iterdrag_strategy import (
- IterDRAGStrategy,
- )
-
- mock_get_setting.return_value = 3
- mock_extract_links.return_value = ["http://example.com"]
-
- mock_search = Mock()
- mock_search.run.return_value = [
- {"title": "Result 1", "snippet": "Content"}
- ]
-
- mock_question_gen = Mock()
- mock_question_gen.generate_questions.return_value = ["Sub-query 1"]
- mock_question.return_value = mock_question_gen
-
- mock_citation_handler = Mock()
- mock_citation_handler.analyze_followup.return_value = {
- "content": "Analysis result",
- "documents": [],
- }
- mock_citation.return_value = mock_citation_handler
-
- mock_findings_repo = Mock()
- mock_findings_repo.synthesize_findings.return_value = "Final synthesis"
- mock_findings_repo.format_findings_to_text.return_value = (
- "Formatted findings"
- )
- mock_findings.return_value = mock_findings_repo
-
- strategy = IterDRAGStrategy(search=mock_search, model=Mock())
-
- result = strategy.analyze_topic("Test query")
-
- assert "findings" in result
- assert "formatted_findings" in result
- assert result["iterations"] == 1
- mock_citation_handler.analyze_followup.assert_called()
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.CitationHandler"
- )
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.DecompositionQuestionGenerator"
- )
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.StandardKnowledge"
- )
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.FindingsRepository"
- )
- def test_analyze_topic_calls_progress_callback(
- self, mock_findings, mock_knowledge, mock_question, mock_citation
- ):
- """Test that progress callback is called during analysis."""
- from local_deep_research.advanced_search_system.strategies.iterdrag_strategy import (
- IterDRAGStrategy,
- )
-
- mock_search = Mock()
- mock_search.run.return_value = []
-
- mock_question_gen = Mock()
- mock_question_gen.generate_questions.return_value = []
- mock_question.return_value = mock_question_gen
-
- mock_findings_repo = Mock()
- mock_findings.return_value = mock_findings_repo
-
- strategy = IterDRAGStrategy(search=mock_search, model=Mock())
- callback = Mock()
- strategy.progress_callback = callback
-
- strategy.analyze_topic("Test query")
-
- # Progress callback should be called multiple times
- assert callback.call_count > 0
-
-
-class TestResultStructure:
- """Tests for analyze_topic result structure."""
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.CitationHandler"
- )
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.DecompositionQuestionGenerator"
- )
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.StandardKnowledge"
- )
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.FindingsRepository"
- )
- def test_result_has_required_keys(
- self, mock_findings, mock_knowledge, mock_question, mock_citation
- ):
- """Test that result has all required keys."""
- from local_deep_research.advanced_search_system.strategies.iterdrag_strategy import (
- IterDRAGStrategy,
- )
-
- mock_search = Mock()
- mock_search.run.return_value = []
-
- mock_question_gen = Mock()
- mock_question_gen.generate_questions.return_value = []
- mock_question.return_value = mock_question_gen
-
- mock_findings_repo = Mock()
- mock_findings.return_value = mock_findings_repo
-
- strategy = IterDRAGStrategy(search=mock_search, model=Mock())
-
- result = strategy.analyze_topic("Test query")
-
- assert "findings" in result
- assert "iterations" in result
- assert "questions" in result
- assert "formatted_findings" in result
- assert "current_knowledge" in result
-
-
-class TestKnowledgeCompression:
- """Tests for knowledge compression behavior."""
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.CitationHandler"
- )
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.DecompositionQuestionGenerator"
- )
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.StandardKnowledge"
- )
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.FindingsRepository"
- )
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.extract_links_from_search_results"
- )
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.get_setting_from_snapshot"
- )
- def test_knowledge_compression_called_when_enabled(
- self,
- mock_get_setting,
- mock_extract_links,
- mock_findings,
- mock_knowledge,
- mock_question,
- mock_citation,
- ):
- """Test that knowledge compression is called when enabled."""
- from local_deep_research.advanced_search_system.strategies.iterdrag_strategy import (
- IterDRAGStrategy,
- )
-
- def setting_side_effect(key, *args, **kwargs):
- if "knowledge_accumulation" in key:
- return "ITERATION"
- return 3
-
- mock_get_setting.side_effect = setting_side_effect
- mock_extract_links.return_value = []
-
- mock_search = Mock()
- mock_search.run.return_value = []
-
- mock_question_gen = Mock()
- mock_question_gen.generate_questions.return_value = []
- mock_question.return_value = mock_question_gen
-
- mock_knowledge_gen = Mock()
- mock_knowledge_gen.compress_knowledge.return_value = "Compressed"
- mock_knowledge.return_value = mock_knowledge_gen
-
- mock_findings_repo = Mock()
- mock_findings_repo.format_findings_to_text.return_value = "Formatted"
- mock_findings.return_value = mock_findings_repo
-
- strategy = IterDRAGStrategy(search=mock_search, model=Mock())
-
- strategy.analyze_topic("Test query")
-
- mock_knowledge_gen.compress_knowledge.assert_called()
-
-
-class TestSynthesisFallback:
- """Tests for synthesis fallback behavior."""
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.CitationHandler"
- )
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.DecompositionQuestionGenerator"
- )
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.StandardKnowledge"
- )
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.FindingsRepository"
- )
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.extract_links_from_search_results"
- )
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.get_setting_from_snapshot"
- )
- def test_synthesis_error_triggers_fallback(
- self,
- mock_get_setting,
- mock_extract_links,
- mock_findings,
- mock_knowledge,
- mock_question,
- mock_citation,
- ):
- """Test that synthesis error triggers fallback behavior."""
- from local_deep_research.advanced_search_system.strategies.iterdrag_strategy import (
- IterDRAGStrategy,
- )
-
- mock_get_setting.return_value = 3
- mock_extract_links.return_value = []
-
- mock_search = Mock()
- mock_search.run.return_value = [{"title": "Result"}]
-
- mock_question_gen = Mock()
- mock_question_gen.generate_questions.return_value = ["Sub-query"]
- mock_question.return_value = mock_question_gen
-
- mock_citation_handler = Mock()
- mock_citation_handler.analyze_followup.return_value = {
- "content": "Finding content",
- "documents": [],
- }
- mock_citation.return_value = mock_citation_handler
-
- mock_findings_repo = Mock()
- mock_findings_repo.synthesize_findings.return_value = "Error: timeout"
- mock_findings_repo.format_findings_to_text.return_value = "Formatted"
- mock_findings.return_value = mock_findings_repo
-
- strategy = IterDRAGStrategy(search=mock_search, model=Mock())
-
- result = strategy.analyze_topic("Test query")
-
- # Should still return a result with findings
- assert "findings" in result
- assert len(result["findings"]) > 0
-
-
-class TestInheritance:
- """Tests for IterDRAGStrategy inheritance."""
-
- def test_inherits_from_base_strategy(self):
- """Test that IterDRAGStrategy inherits from BaseSearchStrategy."""
- from local_deep_research.advanced_search_system.strategies.iterdrag_strategy import (
- IterDRAGStrategy,
- )
- from local_deep_research.advanced_search_system.strategies.base_strategy import (
- BaseSearchStrategy,
- )
-
- assert issubclass(IterDRAGStrategy, BaseSearchStrategy)
-
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.CitationHandler"
- )
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.DecompositionQuestionGenerator"
- )
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.StandardKnowledge"
- )
- @patch(
- "local_deep_research.advanced_search_system.strategies.iterdrag_strategy.FindingsRepository"
- )
- def test_has_base_class_attributes(
- self, mock_findings, mock_knowledge, mock_question, mock_citation
- ):
- """Test that instance has base class attributes."""
- from local_deep_research.advanced_search_system.strategies.iterdrag_strategy import (
- IterDRAGStrategy,
- )
-
- strategy = IterDRAGStrategy(search=Mock(), model=Mock())
-
- assert hasattr(strategy, "all_links_of_system")
- assert hasattr(strategy, "questions_by_iteration")
- assert hasattr(strategy, "settings_snapshot")
diff --git a/tests/advanced_search_system/strategies/test_modular_strategy.py b/tests/advanced_search_system/strategies/test_modular_strategy.py
deleted file mode 100644
index cbceacc531..0000000000
--- a/tests/advanced_search_system/strategies/test_modular_strategy.py
+++ /dev/null
@@ -1,376 +0,0 @@
-"""
-Tests for ModularStrategy.
-
-Tests cover:
-- Initialization and configuration
-- LLM constraint processing
-- Early rejection management
-- Candidate confidence tracking
-- Component integration
-- Error handling
-"""
-
-from unittest.mock import Mock, patch, AsyncMock
-import pytest
-
-
-class TestModularStrategyInit:
- """Tests for ModularStrategy initialization."""
-
- def test_init_with_required_params(self):
- """Initialize with required parameters."""
- from local_deep_research.advanced_search_system.strategies.modular_strategy import (
- ModularStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = ModularStrategy(
- search=mock_search,
- model=mock_model,
- all_links_of_system=[],
- )
-
- assert strategy.model is mock_model
- assert (
- strategy.search_engine is mock_search
- ) # ModularStrategy uses search_engine
-
- def test_init_creates_components(self):
- """Initialize creates required components."""
- from local_deep_research.advanced_search_system.strategies.modular_strategy import (
- ModularStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = ModularStrategy(
- search=mock_search,
- model=mock_model,
- all_links_of_system=[],
- )
-
- # Should create constraint analyzer and question generator
- assert hasattr(strategy, "constraint_analyzer")
- assert hasattr(strategy, "question_generator")
-
-
-class TestLLMConstraintProcessor:
- """Tests for LLMConstraintProcessor class."""
-
- def test_init(self):
- """Initialize LLM constraint processor."""
- from local_deep_research.advanced_search_system.strategies.modular_strategy import (
- LLMConstraintProcessor,
- )
-
- mock_model = Mock()
- processor = LLMConstraintProcessor(mock_model)
-
- assert processor.model is mock_model
-
- def test_parse_combinations_valid_json(self):
- """Parse combinations handles valid JSON array."""
- from local_deep_research.advanced_search_system.strategies.modular_strategy import (
- LLMConstraintProcessor,
- )
-
- mock_model = Mock()
- processor = LLMConstraintProcessor(mock_model)
-
- content = '["query1", "query2", "query3"]'
- result = processor._parse_combinations(content)
-
- assert isinstance(result, list)
- assert len(result) == 3
-
- def test_parse_combinations_invalid_json(self):
- """Parse combinations handles invalid JSON."""
- from local_deep_research.advanced_search_system.strategies.modular_strategy import (
- LLMConstraintProcessor,
- )
-
- mock_model = Mock()
- processor = LLMConstraintProcessor(mock_model)
-
- content = "invalid json"
- result = processor._parse_combinations(content)
-
- assert result == []
-
- def test_parse_combinations_embedded_json(self):
- """Parse combinations extracts JSON from text."""
- from local_deep_research.advanced_search_system.strategies.modular_strategy import (
- LLMConstraintProcessor,
- )
-
- mock_model = Mock()
- processor = LLMConstraintProcessor(mock_model)
-
- content = 'Here are the queries: ["query1", "query2"] that should work.'
- result = processor._parse_combinations(content)
-
- assert isinstance(result, list)
- assert "query1" in result
-
-
-class TestEarlyRejectionManager:
- """Tests for EarlyRejectionManager class."""
-
- def test_init(self):
- """Initialize early rejection manager."""
- from local_deep_research.advanced_search_system.strategies.modular_strategy import (
- EarlyRejectionManager,
- )
-
- mock_model = Mock()
- manager = EarlyRejectionManager(mock_model)
-
- assert manager.model is mock_model
- assert manager.positive_threshold == 0.6
- assert manager.negative_threshold == 0.3
- assert manager.rejected_candidates == set()
-
- def test_init_with_custom_thresholds(self):
- """Initialize with custom thresholds."""
- from local_deep_research.advanced_search_system.strategies.modular_strategy import (
- EarlyRejectionManager,
- )
-
- mock_model = Mock()
- manager = EarlyRejectionManager(
- mock_model,
- positive_threshold=0.8,
- negative_threshold=0.2,
- )
-
- assert manager.positive_threshold == 0.8
- assert manager.negative_threshold == 0.2
-
-
-class TestCandidateConfidence:
- """Tests for CandidateConfidence dataclass."""
-
- def test_create_candidate_confidence(self):
- """Create candidate confidence object."""
- from local_deep_research.advanced_search_system.strategies.modular_strategy import (
- CandidateConfidence,
- )
-
- mock_candidate = Mock()
- confidence = CandidateConfidence(
- candidate=mock_candidate,
- positive_confidence=0.8,
- negative_confidence=0.1,
- )
-
- assert confidence.candidate is mock_candidate
- assert confidence.positive_confidence == 0.8
- assert confidence.negative_confidence == 0.1
- assert confidence.rejection_reason is None
- assert confidence.should_continue is True
-
- def test_candidate_confidence_with_rejection(self):
- """Create candidate confidence with rejection reason."""
- from local_deep_research.advanced_search_system.strategies.modular_strategy import (
- CandidateConfidence,
- )
-
- mock_candidate = Mock()
- confidence = CandidateConfidence(
- candidate=mock_candidate,
- positive_confidence=0.2,
- negative_confidence=0.7,
- rejection_reason="Failed constraint check",
- should_continue=False,
- )
-
- assert confidence.rejection_reason == "Failed constraint check"
- assert confidence.should_continue is False
-
-
-class TestModularStrategyAnalyze:
- """Tests for ModularStrategy analyze_topic method."""
-
- def test_analyze_topic_returns_dict(self):
- """Analyze topic returns result dictionary."""
- from local_deep_research.advanced_search_system.strategies.modular_strategy import (
- ModularStrategy,
- )
-
- mock_search = Mock()
- mock_search.run.return_value = []
- mock_model = Mock()
- mock_model.invoke.return_value = Mock(content="Test response")
-
- strategy = ModularStrategy(
- search=mock_search,
- model=mock_model,
- all_links_of_system=[],
- )
-
- # Mock the constraint analyzer
- with patch.object(
- strategy.constraint_analyzer, "extract_constraints", return_value=[]
- ):
- with patch.object(
- strategy.question_generator,
- "generate_questions",
- return_value=[],
- ):
- result = strategy.analyze_topic("test query")
-
- assert isinstance(result, dict)
-
- def test_analyze_topic_with_progress_callback(self):
- """Analyze topic calls progress callback."""
- from local_deep_research.advanced_search_system.strategies.modular_strategy import (
- ModularStrategy,
- )
-
- mock_search = Mock()
- mock_search.run.return_value = []
- mock_model = Mock()
- mock_model.invoke.return_value = Mock(content="Test")
-
- strategy = ModularStrategy(
- search=mock_search,
- model=mock_model,
- all_links_of_system=[],
- )
-
- callback = Mock()
- strategy.set_progress_callback(callback)
-
- with patch.object(
- strategy.constraint_analyzer, "extract_constraints", return_value=[]
- ):
- with patch.object(
- strategy.question_generator,
- "generate_questions",
- return_value=[],
- ):
- strategy.analyze_topic("test query")
-
- # Callback should be called at least once
- assert callback.call_count >= 0 # May not be called depending on flow
-
-
-class TestSearchCache:
- """Tests for search cache integration."""
-
- def test_search_cache_imported(self):
- """Search cache is properly imported."""
- from local_deep_research.advanced_search_system.strategies.modular_strategy import (
- get_search_cache,
- normalize_entity_query,
- )
-
- assert callable(get_search_cache)
- assert callable(normalize_entity_query)
-
-
-class TestConstraintCheckerIntegration:
- """Tests for constraint checker integration."""
-
- def test_constraint_checkers_available(self):
- """Constraint checkers can be imported."""
- from local_deep_research.advanced_search_system.constraint_checking import (
- DualConfidenceChecker,
- StrictChecker,
- ThresholdChecker,
- )
-
- assert DualConfidenceChecker is not None
- assert StrictChecker is not None
- assert ThresholdChecker is not None
-
-
-class TestExplorerIntegration:
- """Tests for explorer integration."""
-
- def test_explorers_available(self):
- """Explorers can be imported."""
- from local_deep_research.advanced_search_system.candidate_exploration import (
- AdaptiveExplorer,
- ConstraintGuidedExplorer,
- DiversityExplorer,
- ParallelExplorer,
- )
-
- assert AdaptiveExplorer is not None
- assert ConstraintGuidedExplorer is not None
- assert DiversityExplorer is not None
- assert ParallelExplorer is not None
-
-
-class TestAsyncMethods:
- """Tests for async methods in modular strategy."""
-
- @pytest.mark.asyncio
- async def test_generate_intelligent_combinations(self):
- """Test async combination generation."""
- from local_deep_research.advanced_search_system.strategies.modular_strategy import (
- LLMConstraintProcessor,
- )
-
- mock_model = Mock()
- mock_model.ainvoke = AsyncMock(
- return_value=Mock(content='["query1", "query2"]')
- )
-
- processor = LLMConstraintProcessor(mock_model)
-
- result = await processor.generate_intelligent_combinations(
- existing_queries=[],
- original_query="test query",
- )
-
- assert isinstance(result, list)
-
- @pytest.mark.asyncio
- async def test_quick_confidence_check(self):
- """Test async quick confidence check."""
- from local_deep_research.advanced_search_system.strategies.modular_strategy import (
- EarlyRejectionManager,
- )
-
- mock_model = Mock()
- mock_model.ainvoke = AsyncMock(
- return_value=Mock(
- content="POSITIVE: 0.8\nNEGATIVE: 0.1\nUNCERTAINTY: 0.1"
- )
- )
-
- manager = EarlyRejectionManager(mock_model)
-
- mock_candidate = Mock()
- mock_constraints = []
-
- result = await manager.quick_confidence_check(
- mock_candidate, mock_constraints
- )
-
- # Should return some result (CandidateConfidence or similar)
- assert result is not None
-
-
-class TestErrorHandling:
- """Tests for error handling in modular strategy."""
-
- def test_parse_combinations_handles_exception(self):
- """Parse combinations handles parsing exceptions."""
- from local_deep_research.advanced_search_system.strategies.modular_strategy import (
- LLMConstraintProcessor,
- )
-
- mock_model = Mock()
- processor = LLMConstraintProcessor(mock_model)
-
- # Malformed JSON that would cause exception
- content = '["incomplete'
- result = processor._parse_combinations(content)
-
- assert result == []
diff --git a/tests/advanced_search_system/strategies/test_modular_strategy_high_value.py b/tests/advanced_search_system/strategies/test_modular_strategy_high_value.py
deleted file mode 100644
index fab2e91965..0000000000
--- a/tests/advanced_search_system/strategies/test_modular_strategy_high_value.py
+++ /dev/null
@@ -1,254 +0,0 @@
-"""High-value pure logic tests for modular_strategy.py.
-
-Tests CandidateConfidence dataclass, LLMConstraintProcessor parsing,
-and EarlyRejectionManager decision logic without any LLM or network calls.
-"""
-
-import json
-from unittest.mock import MagicMock
-
-
-from local_deep_research.advanced_search_system.strategies.modular_strategy import (
- CandidateConfidence,
- EarlyRejectionManager,
- LLMConstraintProcessor,
-)
-
-
-# ---------------------------------------------------------------------------
-# CandidateConfidence dataclass
-# ---------------------------------------------------------------------------
-class TestCandidateConfidence:
- """Tests for the CandidateConfidence dataclass fields and defaults."""
-
- def test_required_fields(self):
- cc = CandidateConfidence(
- candidate="item_a",
- positive_confidence=0.9,
- negative_confidence=0.1,
- )
- assert cc.candidate == "item_a"
- assert cc.positive_confidence == 0.9
- assert cc.negative_confidence == 0.1
-
- def test_default_rejection_reason_is_none(self):
- cc = CandidateConfidence(
- candidate="x", positive_confidence=0.5, negative_confidence=0.5
- )
- assert cc.rejection_reason is None
-
- def test_default_should_continue_is_true(self):
- cc = CandidateConfidence(
- candidate="x", positive_confidence=0.5, negative_confidence=0.5
- )
- assert cc.should_continue is True
-
- def test_explicit_rejection_reason(self):
- cc = CandidateConfidence(
- candidate="x",
- positive_confidence=0.1,
- negative_confidence=0.9,
- rejection_reason="Too unlikely",
- )
- assert cc.rejection_reason == "Too unlikely"
-
- def test_explicit_should_continue_false(self):
- cc = CandidateConfidence(
- candidate="x",
- positive_confidence=0.1,
- negative_confidence=0.9,
- should_continue=False,
- )
- assert cc.should_continue is False
-
- def test_candidate_accepts_any_object(self):
- obj = {"name": "test", "score": 42}
- cc = CandidateConfidence(
- candidate=obj, positive_confidence=0.7, negative_confidence=0.3
- )
- assert cc.candidate is obj
-
-
-# ---------------------------------------------------------------------------
-# LLMConstraintProcessor parsing methods
-# ---------------------------------------------------------------------------
-class TestLLMConstraintProcessorParseCombinations:
- """Tests for LLMConstraintProcessor._parse_combinations()."""
-
- def setup_method(self):
- self.processor = LLMConstraintProcessor(model=MagicMock())
-
- def test_valid_json_list(self):
- content = json.dumps(["query1", "query2", "query3"])
- result = self.processor._parse_combinations(content)
- assert result == ["query1", "query2", "query3"]
-
- def test_json_embedded_in_markdown(self):
- content = 'Some text\n```json\n["a", "b"]\n```'
- result = self.processor._parse_combinations(content)
- assert result == ["a", "b"]
-
- def test_invalid_json_returns_empty_list(self):
- content = "not json [[[broken"
- result = self.processor._parse_combinations(content)
- assert result == []
-
- def test_empty_string_returns_empty_list(self):
- result = self.processor._parse_combinations("")
- assert result == []
-
- def test_json_dict_returns_empty_list_because_expected_type_is_list(self):
- content = json.dumps({"key": "value"})
- result = self.processor._parse_combinations(content)
- # extract_json with expected_type=list should reject a dict -> fallback []
- assert result == []
-
- def test_empty_list_json(self):
- content = json.dumps([])
- result = self.processor._parse_combinations(content)
- assert result == []
-
-
-# ---------------------------------------------------------------------------
-# EarlyRejectionManager
-# ---------------------------------------------------------------------------
-class TestEarlyRejectionManagerShouldRejectEarly:
- """Tests for EarlyRejectionManager.should_reject_early()."""
-
- def setup_method(self):
- self.manager = EarlyRejectionManager(model=MagicMock())
-
- def test_reject_when_negative_above_threshold(self):
- reject, reason = self.manager.should_reject_early(
- {"negative_confidence": 0.86}
- )
- assert reject is True
- assert reason is not None
- assert "0.86" in reason
-
- def test_no_reject_at_exact_boundary(self):
- """0.85 is NOT greater than 0.85, so should not reject."""
- reject, reason = self.manager.should_reject_early(
- {"negative_confidence": 0.85}
- )
- assert reject is False
- assert reason is None
-
- def test_no_reject_just_below_boundary(self):
- reject, reason = self.manager.should_reject_early(
- {"negative_confidence": 0.84}
- )
- assert reject is False
- assert reason is None
-
- def test_no_reject_low_negative(self):
- reject, reason = self.manager.should_reject_early(
- {"negative_confidence": 0.1}
- )
- assert reject is False
- assert reason is None
-
- def test_reject_at_1_0(self):
- reject, reason = self.manager.should_reject_early(
- {"negative_confidence": 1.0}
- )
- assert reject is True
-
- def test_missing_negative_confidence_uses_default(self):
- """Missing key defaults to 0.3 via dict.get, so no rejection."""
- reject, reason = self.manager.should_reject_early({})
- assert reject is False
- assert reason is None
-
-
-class TestEarlyRejectionManagerShouldContinueSearch:
- """Tests for EarlyRejectionManager.should_continue_search()."""
-
- def setup_method(self):
- self.manager = EarlyRejectionManager(model=MagicMock())
-
- def test_stop_when_5_high_confidence(self):
- candidates = list(range(10))
- should_continue, reason = self.manager.should_continue_search(
- candidates, 5
- )
- assert should_continue is False
- assert "high-confidence" in reason
-
- def test_stop_when_more_than_5_high_confidence(self):
- candidates = list(range(20))
- should_continue, reason = self.manager.should_continue_search(
- candidates, 7
- )
- assert should_continue is False
-
- def test_continue_when_4_high_confidence(self):
- candidates = list(range(10))
- should_continue, reason = self.manager.should_continue_search(
- candidates, 4
- )
- assert should_continue is True
- assert reason is None
-
- def test_stop_when_over_50_candidates_zero_high_confidence(self):
- candidates = list(range(51))
- should_continue, reason = self.manager.should_continue_search(
- candidates, 0
- )
- assert should_continue is False
- assert "low-quality" in reason
-
- def test_continue_at_exactly_50_candidates_zero_high_confidence(self):
- """50 is not > 50, so search should continue."""
- candidates = list(range(50))
- should_continue, reason = self.manager.should_continue_search(
- candidates, 0
- )
- assert should_continue is True
- assert reason is None
-
- def test_continue_with_few_candidates_zero_high_confidence(self):
- candidates = list(range(5))
- should_continue, reason = self.manager.should_continue_search(
- candidates, 0
- )
- assert should_continue is True
-
- def test_continue_with_many_candidates_some_high_confidence(self):
- """51 candidates but 1 high confidence - should continue (not 0)."""
- candidates = list(range(51))
- should_continue, reason = self.manager.should_continue_search(
- candidates, 1
- )
- assert should_continue is True
- assert reason is None
-
-
-class TestEarlyRejectionManagerParseConfidence:
- """Tests for EarlyRejectionManager._parse_confidence()."""
-
- def setup_method(self):
- self.manager = EarlyRejectionManager(model=MagicMock())
-
- def test_valid_json(self):
- content = json.dumps(
- {
- "positive_confidence": 0.8,
- "negative_confidence": 0.2,
- "reasoning": "looks good",
- }
- )
- result = self.manager._parse_confidence(content)
- assert result["positive_confidence"] == 0.8
- assert result["negative_confidence"] == 0.2
-
- def test_invalid_json_returns_fallback(self):
- result = self.manager._parse_confidence("totally broken json {{{")
- assert result["positive_confidence"] == 0.5
- assert result["negative_confidence"] == 0.3
- assert result["reasoning"] == "parse_error"
-
- def test_empty_string_returns_fallback(self):
- result = self.manager._parse_confidence("")
- assert result["positive_confidence"] == 0.5
- assert result["negative_confidence"] == 0.3
diff --git a/tests/advanced_search_system/strategies/test_parallel_constrained_high_value.py b/tests/advanced_search_system/strategies/test_parallel_constrained_high_value.py
deleted file mode 100644
index 51460d087a..0000000000
--- a/tests/advanced_search_system/strategies/test_parallel_constrained_high_value.py
+++ /dev/null
@@ -1,270 +0,0 @@
-"""High-value tests for ParallelConstrainedStrategy pure logic methods."""
-
-import pytest
-from unittest.mock import patch
-
-from local_deep_research.advanced_search_system.constraints.base_constraint import (
- Constraint,
- ConstraintType,
-)
-from local_deep_research.advanced_search_system.strategies.parallel_constrained_strategy import (
- ParallelConstrainedStrategy,
- SearchCombination,
-)
-
-
-def make_constraint(ctype, value, weight=1.0, cid=None):
- return Constraint(
- id=cid or f"c_{value[:8]}",
- type=ctype,
- description=value,
- value=value,
- weight=weight,
- )
-
-
-# --- SearchCombination dataclass ---
-
-
-class TestSearchCombination:
- def test_hash_by_query(self):
- c1 = SearchCombination(constraints=[], query="foo", priority=1)
- c2 = SearchCombination(constraints=[], query="foo", priority=2)
- assert hash(c1) == hash(c2)
-
- def test_different_query_different_hash(self):
- c1 = SearchCombination(constraints=[], query="foo", priority=1)
- c2 = SearchCombination(constraints=[], query="bar", priority=1)
- assert hash(c1) != hash(c2)
-
- def test_fields(self):
- constraints = [make_constraint(ConstraintType.PROPERTY, "test")]
- combo = SearchCombination(
- constraints=constraints, query="test query", priority=5
- )
- assert combo.constraints == constraints
- assert combo.query == "test query"
- assert combo.priority == 5
-
- def test_same_hash_for_same_query(self):
- c1 = SearchCombination(constraints=[], query="foo", priority=1)
- c2 = SearchCombination(constraints=[], query="foo", priority=2)
- # Same hash but no __eq__ override, so set uses identity
- assert hash(c1) == hash(c2)
-
-
-# --- _classify_constraints ---
-
-
-def strategy():
- """Create a ParallelConstrainedStrategy with mocked parent init."""
- with patch.object(
- ParallelConstrainedStrategy, "__init__", lambda self, *a, **kw: None
- ):
- s = ParallelConstrainedStrategy.__new__(ParallelConstrainedStrategy)
- s.parallel_workers = 100
- s.min_results_threshold = 10
- return s
-
-
-class TestClassifyConstraints:
- def test_temporal_is_hard(self, strategy):
- strategy.constraint_ranking = [
- make_constraint(ConstraintType.TEMPORAL, "in 2020"),
- ]
- strategy._classify_constraints()
- assert len(strategy.hard_constraints) == 1
- assert len(strategy.soft_constraints) == 0
-
- def test_statistic_is_hard(self, strategy):
- strategy.constraint_ranking = [
- make_constraint(ConstraintType.STATISTIC, "84.5x ratio"),
- ]
- strategy._classify_constraints()
- assert len(strategy.hard_constraints) == 1
-
- def test_property_is_soft(self, strategy):
- """PROPERTY constraints are always soft (no keyword matching)."""
- strategy.constraint_ranking = [
- make_constraint(ConstraintType.PROPERTY, "female character"),
- ]
- strategy._classify_constraints()
- assert len(strategy.soft_constraints) == 1
- assert len(strategy.hard_constraints) == 0
-
- def test_property_without_keyword_is_soft(self, strategy):
- strategy.constraint_ranking = [
- make_constraint(ConstraintType.PROPERTY, "has blue eyes"),
- ]
- strategy._classify_constraints()
- assert len(strategy.soft_constraints) == 1
- assert len(strategy.hard_constraints) == 0
-
- def test_mixed_types_hard_and_soft(self, strategy):
- """TEMPORAL → hard, PROPERTY → soft."""
- strategy.constraint_ranking = [
- make_constraint(ConstraintType.TEMPORAL, "in 2020"),
- make_constraint(ConstraintType.PROPERTY, "has blue eyes"),
- ]
- strategy._classify_constraints()
- assert len(strategy.hard_constraints) == 1
- assert len(strategy.soft_constraints) == 1
-
-
-# --- _build_query ---
-
-
-class TestBuildQuery:
- def test_single_constraint(self, strategy):
- strategy.entity_type = None
- c = make_constraint(ConstraintType.PROPERTY, "blue eyes")
- result = strategy._build_query([c])
- assert '"blue eyes"' in result
-
- def test_multi_word_quoted(self, strategy):
- strategy.entity_type = None
- c = make_constraint(ConstraintType.PROPERTY, "has blue eyes")
- result = strategy._build_query([c])
- assert '"has blue eyes"' in result
-
- def test_single_word_not_quoted(self, strategy):
- strategy.entity_type = None
- c = make_constraint(ConstraintType.PROPERTY, "Colorado")
- result = strategy._build_query([c])
- assert result == "Colorado"
-
- def test_and_joining(self, strategy):
- strategy.entity_type = None
- c1 = make_constraint(ConstraintType.PROPERTY, "Colorado")
- c2 = make_constraint(ConstraintType.PROPERTY, "mountain")
- result = strategy._build_query([c1, c2])
- assert " AND " in result
-
- def test_entity_type_prefix(self, strategy):
- strategy.entity_type = "TV show"
- c = make_constraint(ConstraintType.PROPERTY, "comedy")
- result = strategy._build_query([c])
- assert '"TV show"' in result
- assert "comedy" in result
-
- def test_entity_type_unknown_skipped(self, strategy):
- strategy.entity_type = "unknown entity"
- c = make_constraint(ConstraintType.PROPERTY, "comedy")
- result = strategy._build_query([c])
- assert "unknown" not in result
-
-
-# --- _generate_query_variations ---
-
-
-class TestGenerateQueryVariations:
- def test_statistic_variations(self, strategy):
- c = make_constraint(ConstraintType.STATISTIC, "84.5x ratio")
- variations = strategy._generate_query_variations(c)
- assert "84.5x ratio" in variations
- assert any("list" in v for v in variations)
- assert any("complete" in v for v in variations)
- assert len(variations) <= 3
-
- def test_property_variations(self, strategy):
- c = make_constraint(ConstraintType.PROPERTY, "blue eyes")
- variations = strategy._generate_query_variations(c)
- assert any("with" in v for v in variations)
- assert any("featuring" in v for v in variations)
- assert len(variations) <= 3
-
- def test_other_type_base_only(self, strategy):
- c = make_constraint(ConstraintType.TEMPORAL, "in 2020")
- variations = strategy._generate_query_variations(c)
- assert variations == ["in 2020"]
-
- def test_limit_to_three(self, strategy):
- c = make_constraint(ConstraintType.STATISTIC, "test stat")
- variations = strategy._generate_query_variations(c)
- assert len(variations) <= 3
-
-
-# --- _create_strict_combinations ---
-
-
-class TestCreateStrictCombinations:
- def test_top_two_combination(self, strategy):
- strategy.entity_type = None
- strategy.constraint_ranking = [
- make_constraint(ConstraintType.PROPERTY, "A"),
- make_constraint(ConstraintType.PROPERTY, "B"),
- ]
- combos = strategy._create_strict_combinations()
- assert len(combos) >= 1
- assert len(combos[0].constraints) == 2
-
- def test_temporal_property_combination(self, strategy):
- strategy.entity_type = None
- strategy.constraint_ranking = [
- make_constraint(ConstraintType.EVENT, "fall in 2014"),
- make_constraint(ConstraintType.PROPERTY, "scenic view"),
- ]
- combos = strategy._create_strict_combinations()
- assert any(len(c.constraints) == 2 for c in combos)
-
- def test_limit_five(self, strategy):
- strategy.entity_type = None
- strategy.constraint_ranking = [
- make_constraint(ConstraintType.PROPERTY, f"prop{i}")
- for i in range(10)
- ]
- combos = strategy._create_strict_combinations()
- assert len(combos) <= 5
-
- def test_single_constraint_no_crash(self, strategy):
- strategy.entity_type = None
- strategy.constraint_ranking = [
- make_constraint(ConstraintType.PROPERTY, "solo"),
- ]
- combos = strategy._create_strict_combinations()
- assert isinstance(combos, list)
-
-
-# --- _create_relaxed_combinations ---
-
-
-class TestCreateRelaxedCombinations:
- def test_single_constraints_from_top_three(self, strategy):
- strategy.entity_type = None
- strategy.constraint_ranking = [
- make_constraint(ConstraintType.PROPERTY, f"c{i}") for i in range(5)
- ]
- combos = strategy._create_relaxed_combinations()
- single_combos = [c for c in combos if len(c.constraints) == 1]
- assert len(single_combos) == 3
-
- def test_weaker_group_included(self, strategy):
- strategy.entity_type = None
- strategy.constraint_ranking = [
- make_constraint(ConstraintType.PROPERTY, f"c{i}") for i in range(6)
- ]
- combos = strategy._create_relaxed_combinations()
- multi = [c for c in combos if len(c.constraints) > 1]
- assert len(multi) >= 1
-
-
-# --- _create_individual_combinations ---
-
-
-class TestCreateIndividualCombinations:
- def test_two_variations_per_constraint(self, strategy):
- strategy.constraint_ranking = [
- make_constraint(ConstraintType.STATISTIC, "stat1"),
- ]
- combos = strategy._create_individual_combinations()
- assert len(combos) == 2
-
- def test_max_five_constraints(self, strategy):
- strategy.constraint_ranking = [
- make_constraint(ConstraintType.PROPERTY, f"c{i}") for i in range(10)
- ]
- combos = strategy._create_individual_combinations()
- # 5 constraints * 2 variations = 10 max (but PROPERTY only gives 1 base)
- # Actually PROPERTY gives: base + with + featuring + known for = 4 -> [:2] = 2
- assert len(combos) <= 10
diff --git a/tests/advanced_search_system/strategies/test_parallel_strategies.py b/tests/advanced_search_system/strategies/test_parallel_strategies.py
deleted file mode 100644
index 44fa05afb8..0000000000
--- a/tests/advanced_search_system/strategies/test_parallel_strategies.py
+++ /dev/null
@@ -1,444 +0,0 @@
-"""
-Tests for parallel search strategies.
-
-Combined tests for:
-- ParallelSearchStrategy
-- ParallelConstrainedStrategy
-- ConstraintParallelStrategy
-- ConcurrentDualConfidenceStrategy
-
-Tests cover:
-- Initialization and configuration
-- Parallel execution patterns
-- Result aggregation
-- Thread safety
-- Error handling
-"""
-
-from unittest.mock import Mock, patch
-
-
-class TestParallelSearchStrategyInit:
- """Tests for ParallelSearchStrategy initialization."""
-
- def test_init_with_required_params(self):
- """Initialize with required parameters."""
- from local_deep_research.advanced_search_system.strategies.parallel_search_strategy import (
- ParallelSearchStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = ParallelSearchStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- assert strategy.model is mock_model
- assert strategy.search is mock_search
-
- def test_init_inherits_base_strategy(self):
- """Initialize inherits from base strategy."""
- from local_deep_research.advanced_search_system.strategies.parallel_search_strategy import (
- ParallelSearchStrategy,
- )
- from local_deep_research.advanced_search_system.strategies.base_strategy import (
- BaseSearchStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = ParallelSearchStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- assert isinstance(strategy, BaseSearchStrategy)
-
-
-class TestParallelConstrainedStrategyInit:
- """Tests for ParallelConstrainedStrategy initialization."""
-
- def test_init_with_required_params(self):
- """Initialize with required parameters."""
- from local_deep_research.advanced_search_system.strategies.parallel_constrained_strategy import (
- ParallelConstrainedStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = ParallelConstrainedStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- assert strategy.model is mock_model
- assert strategy.search is mock_search
-
-
-class TestConstraintParallelStrategyInit:
- """Tests for ConstraintParallelStrategy initialization."""
-
- def test_init_with_required_params(self):
- """Initialize with required parameters."""
- from local_deep_research.advanced_search_system.strategies.constraint_parallel_strategy import (
- ConstraintParallelStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = ConstraintParallelStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- assert strategy.model is mock_model
- assert strategy.search is mock_search
-
- def test_init_creates_executor(self):
- """Initialize may create thread executor."""
- from local_deep_research.advanced_search_system.strategies.constraint_parallel_strategy import (
- ConstraintParallelStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = ConstraintParallelStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- # Strategy should be capable of parallel execution
- assert hasattr(strategy, "model")
-
-
-class TestConcurrentDualConfidenceStrategyInit:
- """Tests for ConcurrentDualConfidenceStrategy initialization."""
-
- def test_init_with_required_params(self):
- """Initialize with required parameters."""
- from local_deep_research.advanced_search_system.strategies.concurrent_dual_confidence_strategy import (
- ConcurrentDualConfidenceStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = ConcurrentDualConfidenceStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- assert strategy.model is mock_model
- assert strategy.search is mock_search
-
-
-class TestParallelSearchAnalyze:
- """Tests for parallel search analyze_topic method."""
-
- def test_analyze_topic_returns_dict(self):
- """Analyze topic returns result dictionary."""
- from local_deep_research.advanced_search_system.strategies.parallel_search_strategy import (
- ParallelSearchStrategy,
- )
-
- mock_search = Mock()
- mock_search.run.return_value = []
- mock_model = Mock()
- mock_model.invoke.return_value = Mock(content="Test response")
-
- # ParallelSearchStrategy requires settings with iterations
- settings = {"search.iterations": {"value": 1}}
-
- strategy = ParallelSearchStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- settings_snapshot=settings,
- )
-
- # Mock required components
- with patch.object(strategy, "question_generator", Mock()):
- strategy.question_generator.generate_questions = Mock(
- return_value=[]
- )
- result = strategy.analyze_topic("test query")
-
- assert isinstance(result, dict)
-
-
-class TestParallelConstrainedAnalyze:
- """Tests for parallel constrained analyze_topic method."""
-
- def test_analyze_topic_with_constraints(self):
- """Analyze topic processes constraints in parallel."""
- from local_deep_research.advanced_search_system.strategies.parallel_constrained_strategy import (
- ParallelConstrainedStrategy,
- )
-
- mock_search = Mock()
- mock_search.run.return_value = []
- mock_model = Mock()
- mock_model.invoke.return_value = Mock(content="Response")
-
- strategy = ParallelConstrainedStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- # Mock constraint analyzer
- with patch.object(
- strategy.constraint_analyzer, "extract_constraints", return_value=[]
- ):
- result = strategy.analyze_topic("test query")
-
- assert isinstance(result, dict)
-
-
-class TestConstraintParallelAnalyze:
- """Tests for constraint parallel analyze_topic method."""
-
- def test_analyze_topic_parallel_constraints(self):
- """Analyze topic processes constraint groups in parallel."""
- from local_deep_research.advanced_search_system.strategies.constraint_parallel_strategy import (
- ConstraintParallelStrategy,
- )
-
- mock_search = Mock()
- mock_search.run.return_value = []
- mock_model = Mock()
- mock_model.invoke.return_value = Mock(content="Response")
-
- strategy = ConstraintParallelStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- # Mock required components
- with patch.object(
- strategy.constraint_analyzer, "extract_constraints", return_value=[]
- ):
- result = strategy.analyze_topic("test query")
-
- assert isinstance(result, dict)
-
-
-class TestConcurrentDualConfidenceAnalyze:
- """Tests for concurrent dual confidence analyze_topic method."""
-
- def test_analyze_topic_concurrent_scoring(self):
- """Analyze topic performs concurrent confidence scoring."""
- from local_deep_research.advanced_search_system.strategies.concurrent_dual_confidence_strategy import (
- ConcurrentDualConfidenceStrategy,
- )
-
- mock_search = Mock()
- mock_search.run.return_value = []
- mock_model = Mock()
- mock_model.invoke.return_value = Mock(
- content="POSITIVE: 0.5\nNEGATIVE: 0.3\nUNCERTAINTY: 0.2"
- )
-
- strategy = ConcurrentDualConfidenceStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- # Mock required components
- with patch.object(
- strategy.constraint_analyzer, "extract_constraints", return_value=[]
- ):
- result = strategy.analyze_topic("test query")
-
- assert isinstance(result, dict)
-
-
-class TestProgressCallback:
- """Tests for progress callback support."""
-
- def test_parallel_search_progress_callback(self):
- """Parallel search calls progress callback."""
- from local_deep_research.advanced_search_system.strategies.parallel_search_strategy import (
- ParallelSearchStrategy,
- )
-
- mock_search = Mock()
- mock_search.run.return_value = []
- mock_model = Mock()
- mock_model.invoke.return_value = Mock(content="Response")
-
- settings = {"search.iterations": {"value": 1}}
-
- strategy = ParallelSearchStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- settings_snapshot=settings,
- )
-
- callback = Mock()
- strategy.set_progress_callback(callback)
-
- with patch.object(strategy, "question_generator", Mock()):
- strategy.question_generator.generate_questions = Mock(
- return_value=[]
- )
- strategy.analyze_topic("test query")
-
- # May or may not call callback depending on implementation
- assert callback.call_count >= 0
-
-
-class TestResultAggregation:
- """Tests for result aggregation from parallel searches."""
-
- def test_aggregate_results_structure(self):
- """Aggregated results have expected structure."""
- from local_deep_research.advanced_search_system.strategies.parallel_search_strategy import (
- ParallelSearchStrategy,
- )
-
- mock_search = Mock()
- mock_search.run.return_value = [
- {"title": "Result 1", "snippet": "Content 1"},
- {"title": "Result 2", "snippet": "Content 2"},
- ]
- mock_model = Mock()
- mock_model.invoke.return_value = Mock(content="Synthesis")
-
- settings = {"search.iterations": {"value": 1}}
-
- strategy = ParallelSearchStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- settings_snapshot=settings,
- )
-
- with patch.object(strategy, "question_generator", Mock()):
- strategy.question_generator.generate_questions = Mock(
- return_value=["Q1", "Q2"]
- )
- result = strategy.analyze_topic("test query")
-
- assert "findings" in result or "current_knowledge" in result
-
-
-class TestErrorHandling:
- """Tests for error handling in parallel strategies."""
-
- def test_parallel_search_handles_search_error(self):
- """Parallel search handles search errors gracefully."""
- from local_deep_research.advanced_search_system.strategies.parallel_search_strategy import (
- ParallelSearchStrategy,
- )
-
- mock_search = Mock()
- mock_search.run.side_effect = Exception("Search error")
- mock_model = Mock()
- mock_model.invoke.return_value = Mock(content="Response")
-
- strategy = ParallelSearchStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- # Should not raise, should handle error gracefully
- with patch.object(strategy, "question_generator", Mock()):
- strategy.question_generator.generate_questions = Mock(
- return_value=[]
- )
- try:
- result = strategy.analyze_topic("test query")
- assert isinstance(result, dict)
- except Exception:
- # Some implementations may raise
- pass
-
-
-class TestThreadSafety:
- """Tests for thread safety in parallel strategies."""
-
- def test_parallel_does_not_corrupt_state(self):
- """Parallel execution doesn't corrupt shared state."""
- from local_deep_research.advanced_search_system.strategies.parallel_search_strategy import (
- ParallelSearchStrategy,
- )
-
- mock_search = Mock()
- mock_search.run.return_value = []
- mock_model = Mock()
- mock_model.invoke.return_value = Mock(content="Response")
-
- settings = {"search.iterations": {"value": 1}}
-
- strategy = ParallelSearchStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- settings_snapshot=settings,
- )
-
- with patch.object(strategy, "question_generator", Mock()):
- strategy.question_generator.generate_questions = Mock(
- return_value=[]
- )
- strategy.analyze_topic("test query")
-
- # State should be updated but not corrupted
- assert isinstance(strategy.all_links_of_system, list)
-
-
-class TestInheritance:
- """Tests for inheritance relationships."""
-
- def test_parallel_constrained_inheritance(self):
- """ParallelConstrainedStrategy inherits correctly."""
- from local_deep_research.advanced_search_system.strategies.parallel_constrained_strategy import (
- ParallelConstrainedStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = ParallelConstrainedStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- # Should have constraint analyzer from inheritance
- assert hasattr(strategy, "constraint_analyzer")
-
- def test_concurrent_dual_confidence_inheritance(self):
- """ConcurrentDualConfidenceStrategy inherits correctly."""
- from local_deep_research.advanced_search_system.strategies.concurrent_dual_confidence_strategy import (
- ConcurrentDualConfidenceStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- strategy = ConcurrentDualConfidenceStrategy(
- model=mock_model,
- search=mock_search,
- all_links_of_system=[],
- )
-
- # Should have dual confidence attributes
- assert hasattr(strategy, "model")
diff --git a/tests/advanced_search_system/strategies/test_recursive_decomposition_high_value.py b/tests/advanced_search_system/strategies/test_recursive_decomposition_high_value.py
deleted file mode 100644
index 5696785070..0000000000
--- a/tests/advanced_search_system/strategies/test_recursive_decomposition_high_value.py
+++ /dev/null
@@ -1,668 +0,0 @@
-"""
-High-value tests for RecursiveDecompositionStrategy.
-
-Covers pure logic paths:
-- _decide_decomposition: DECOMPOSE/SEARCH_DIRECTLY response parsing, subtask extraction
-- _aggregate_subtask_results: link deduplication (dict vs string), questions format conversion
-- Max recursion depth guard
-- analyze_topic initialization and routing
-"""
-
-from unittest.mock import MagicMock, Mock, patch
-
-
-from local_deep_research.advanced_search_system.strategies.recursive_decomposition_strategy import (
- RecursiveDecompositionStrategy,
-)
-
-
-# ---------------------------------------------------------------------------
-# Helpers
-# ---------------------------------------------------------------------------
-
-MODULE = "local_deep_research.advanced_search_system.strategies.recursive_decomposition_strategy"
-
-
-def _make_strategy(**kwargs):
- """Create a RecursiveDecompositionStrategy with mocked dependencies."""
- model = MagicMock()
- search = MagicMock()
- defaults = dict(
- model=model,
- search=search,
- all_links_of_system=[],
- max_recursion_depth=5,
- )
- defaults.update(kwargs)
- return RecursiveDecompositionStrategy(**defaults)
-
-
-def _model_response(text):
- resp = Mock()
- resp.content = text
- return resp
-
-
-# ---------------------------------------------------------------------------
-# _decide_decomposition
-# ---------------------------------------------------------------------------
-
-
-class TestDecideDecomposition:
- """Tests for LLM response parsing to DECOMPOSE or SEARCH_DIRECTLY."""
-
- def test_parses_decompose_decision(self):
- strategy = _make_strategy()
- strategy.original_query = None
- strategy.model.invoke.return_value = _model_response(
- "DECISION: DECOMPOSE\n"
- "REASONING: Complex multi-part question\n"
- "SUBTASKS:\n"
- "1. Find the population of city X\n"
- "2. Find the GDP of country Y\n"
- "DEPENDENCIES: Subtask 2 depends on subtask 1"
- )
- result = strategy._decide_decomposition("complex query")
-
- assert result["should_decompose"] is True
- assert result["reasoning"] == "Complex multi-part question"
- assert len(result["subtasks"]) == 2
- assert "population of city X" in result["subtasks"][0]
- assert "GDP of country Y" in result["subtasks"][1]
- assert len(result["dependencies"]) == 1
-
- def test_parses_search_directly_decision(self):
- strategy = _make_strategy()
- strategy.original_query = None
- strategy.model.invoke.return_value = _model_response(
- "DECISION: SEARCH_DIRECTLY\nREASONING: Simple factual question"
- )
- result = strategy._decide_decomposition("simple query")
-
- assert result["should_decompose"] is False
- assert result["reasoning"] == "Simple factual question"
- assert result["subtasks"] == []
-
- def test_unknown_decision_defaults_to_search_directly(self):
- """Non-DECOMPOSE value defaults to search directly."""
- strategy = _make_strategy()
- strategy.original_query = None
- strategy.model.invoke.return_value = _model_response(
- "DECISION: MAYBE\nREASONING: unclear"
- )
- result = strategy._decide_decomposition("query")
- assert result["should_decompose"] is False
-
- def test_no_decision_line_defaults_to_search_directly(self):
- strategy = _make_strategy()
- strategy.original_query = None
- strategy.model.invoke.return_value = _model_response(
- "I think we should search for this directly."
- )
- result = strategy._decide_decomposition("query")
- assert result["should_decompose"] is False
-
- def test_subtasks_with_dash_format(self):
- """Supports dash-prefixed subtask lines."""
- strategy = _make_strategy()
- strategy.original_query = None
- strategy.model.invoke.return_value = _model_response(
- "DECISION: DECOMPOSE\n"
- "REASONING: Has parts\n"
- "SUBTASKS:\n"
- "- First subtask\n"
- "- Second subtask\n"
- "DEPENDENCIES: None"
- )
- result = strategy._decide_decomposition("query")
- assert result["should_decompose"] is True
- assert len(result["subtasks"]) == 2
- assert result["subtasks"][0] == "First subtask"
-
- def test_empty_subtasks_with_decompose(self):
- """DECOMPOSE with no subtask lines still returns should_decompose=True."""
- strategy = _make_strategy()
- strategy.original_query = None
- strategy.model.invoke.return_value = _model_response(
- "DECISION: DECOMPOSE\n"
- "REASONING: Should split\n"
- "SUBTASKS:\n"
- "DEPENDENCIES: None"
- )
- result = strategy._decide_decomposition("query")
- assert result["should_decompose"] is True
- assert result["subtasks"] == []
-
- def test_handles_think_tags(self):
- """Think tags in LLM output are stripped."""
- strategy = _make_strategy()
- strategy.original_query = None
- strategy.model.invoke.return_value = _model_response(
- "<think>Hmm let me think...</think>\n"
- "DECISION: SEARCH_DIRECTLY\n"
- "REASONING: Simple"
- )
- result = strategy._decide_decomposition("query")
- assert result["should_decompose"] is False
-
- def test_includes_original_query_context(self):
- """When original_query differs from current query, context is included in prompt."""
- strategy = _make_strategy()
- strategy.original_query = "Master research topic"
- strategy.model.invoke.return_value = _model_response(
- "DECISION: SEARCH_DIRECTLY\nREASONING: sub-query"
- )
- strategy._decide_decomposition("sub-question about aspect")
- # Verify the prompt included the original query context
- prompt_arg = strategy.model.invoke.call_args[0][0]
- assert "Master research topic" in prompt_arg
-
- def test_no_context_when_same_query(self):
- """No context line when original_query matches current query."""
- strategy = _make_strategy()
- strategy.original_query = "same query"
- strategy.model.invoke.return_value = _model_response(
- "DECISION: SEARCH_DIRECTLY\nREASONING: direct"
- )
- strategy._decide_decomposition("same query")
- prompt_arg = strategy.model.invoke.call_args[0][0]
- assert "Original research topic" not in prompt_arg
-
- def test_colon_in_reasoning_preserved(self):
- strategy = _make_strategy()
- strategy.original_query = None
- strategy.model.invoke.return_value = _model_response(
- "DECISION: DECOMPOSE\n"
- "REASONING: Has parts: A, B, and C\n"
- "SUBTASKS:\n"
- "1. Part A\n"
- "DEPENDENCIES: none"
- )
- result = strategy._decide_decomposition("query")
- assert result["reasoning"] == "Has parts: A, B, and C"
-
-
-# ---------------------------------------------------------------------------
-# _aggregate_subtask_results
-# ---------------------------------------------------------------------------
-
-
-class TestAggregateSubtaskResults:
- """Tests for result aggregation with link dedup and question format conversion."""
-
- def _setup_strategy(self):
- strategy = _make_strategy()
- strategy.findings = []
- strategy.questions_by_iteration = []
- strategy.original_query = "original topic"
- strategy.model.invoke.return_value = _model_response(
- "Synthesized answer text"
- )
- return strategy
-
- def test_synthesizes_subtask_results(self):
- strategy = self._setup_strategy()
- subtask_results = [
- {
- "subtask": "Sub 1",
- "result": {
- "current_knowledge": "Knowledge from sub 1",
- "all_links_of_system": [],
- "findings": [],
- "questions_by_iteration": [],
- },
- "depth": 1,
- "index": 1,
- }
- ]
-
- with patch(f"{MODULE}.format_findings", return_value="formatted"):
- result = strategy._aggregate_subtask_results(
- "original query", subtask_results, 0
- )
-
- assert result["current_knowledge"] == "Synthesized answer text"
- assert result["strategy"] == "recursive_decomposition"
-
- def test_deduplicates_string_links(self):
- strategy = self._setup_strategy()
- subtask_results = [
- {
- "subtask": "Sub 1",
- "result": {
- "current_knowledge": "K1",
- "all_links_of_system": ["http://a.com", "http://b.com"],
- "findings": [],
- "questions_by_iteration": [],
- },
- "depth": 1,
- "index": 1,
- },
- {
- "subtask": "Sub 2",
- "result": {
- "current_knowledge": "K2",
- "all_links_of_system": ["http://b.com", "http://c.com"],
- "findings": [],
- "questions_by_iteration": [],
- },
- "depth": 1,
- "index": 2,
- },
- ]
-
- with patch(f"{MODULE}.format_findings", return_value="formatted"):
- result = strategy._aggregate_subtask_results(
- "query", subtask_results, 0
- )
-
- links = result["all_links_of_system"]
- link_strs = [str(link) for link in links]
- assert len(link_strs) == 3 # a, b, c (b deduplicated)
-
- def test_deduplicates_dict_links_by_url(self):
- strategy = self._setup_strategy()
- subtask_results = [
- {
- "subtask": "Sub 1",
- "result": {
- "current_knowledge": "K1",
- "all_links_of_system": [
- {"link": "http://example.com", "title": "Example"},
- ],
- "findings": [],
- "questions_by_iteration": [],
- },
- "depth": 1,
- "index": 1,
- },
- {
- "subtask": "Sub 2",
- "result": {
- "current_knowledge": "K2",
- "all_links_of_system": [
- {"link": "http://example.com", "title": "Example Dup"},
- ],
- "findings": [],
- "questions_by_iteration": [],
- },
- "depth": 1,
- "index": 2,
- },
- ]
-
- with patch(f"{MODULE}.format_findings", return_value="formatted"):
- result = strategy._aggregate_subtask_results(
- "query", subtask_results, 0
- )
-
- assert len(result["all_links_of_system"]) == 1
-
- def test_dict_links_with_url_key(self):
- """Dict links use 'url' key when 'link' is missing."""
- strategy = self._setup_strategy()
- subtask_results = [
- {
- "subtask": "Sub 1",
- "result": {
- "current_knowledge": "K",
- "all_links_of_system": [
- {"url": "http://a.com"},
- {"url": "http://a.com"},
- ],
- "findings": [],
- "questions_by_iteration": [],
- },
- "depth": 1,
- "index": 1,
- },
- ]
-
- with patch(f"{MODULE}.format_findings", return_value="formatted"):
- result = strategy._aggregate_subtask_results(
- "q", subtask_results, 0
- )
-
- assert len(result["all_links_of_system"]) == 1
-
- def test_questions_list_format_conversion(self):
- """List-type questions are converted to dict format."""
- strategy = self._setup_strategy()
- subtask_results = [
- {
- "subtask": "Sub 1",
- "result": {
- "current_knowledge": "K",
- "all_links_of_system": [],
- "findings": [],
- "questions_by_iteration": [
- ["Q1", "Q2"],
- ["Q3"],
- ],
- },
- "depth": 1,
- "index": 1,
- },
- ]
-
- with patch(f"{MODULE}.format_findings", return_value="formatted"):
- result = strategy._aggregate_subtask_results(
- "q", subtask_results, 0
- )
-
- qdict = result["questions_by_iteration"]
- assert isinstance(qdict, dict)
- assert 1 in qdict
- assert qdict[1] == ["Q1", "Q2"]
- assert 2 in qdict
-
- def test_questions_dict_format_merged(self):
- """Dict-type questions are merged directly."""
- strategy = self._setup_strategy()
- subtask_results = [
- {
- "subtask": "Sub 1",
- "result": {
- "current_knowledge": "K",
- "all_links_of_system": [],
- "findings": [],
- "questions_by_iteration": [
- {10: ["Q from dict"]},
- ],
- },
- "depth": 1,
- "index": 1,
- },
- ]
-
- with patch(f"{MODULE}.format_findings", return_value="formatted"):
- result = strategy._aggregate_subtask_results(
- "q", subtask_results, 0
- )
-
- qdict = result["questions_by_iteration"]
- assert 10 in qdict
-
- def test_none_questions_skipped(self):
- """None values in questions list are skipped."""
- strategy = self._setup_strategy()
- subtask_results = [
- {
- "subtask": "Sub 1",
- "result": {
- "current_knowledge": "K",
- "all_links_of_system": [],
- "findings": [],
- "questions_by_iteration": [None, ["Q1"]],
- },
- "depth": 1,
- "index": 1,
- },
- ]
-
- with patch(f"{MODULE}.format_findings", return_value="formatted"):
- result = strategy._aggregate_subtask_results(
- "q", subtask_results, 0
- )
-
- # None should be converted as a single-item list via str()
- # Actually looking at the code: None is not iterable for isinstance checks
- # but the 'if questions is not None' guard skips it for the total count
- assert isinstance(result["questions"], dict)
-
- def test_result_has_expected_keys(self):
- strategy = self._setup_strategy()
- subtask_results = [
- {
- "subtask": "S",
- "result": {
- "current_knowledge": "K",
- "all_links_of_system": [],
- "findings": [],
- "questions_by_iteration": [],
- },
- "depth": 1,
- "index": 1,
- },
- ]
-
- with patch(f"{MODULE}.format_findings", return_value="formatted"):
- result = strategy._aggregate_subtask_results(
- "q", subtask_results, 0
- )
-
- expected_keys = {
- "current_knowledge",
- "formatted_findings",
- "findings",
- "iterations",
- "questions_by_iteration",
- "all_links_of_system",
- "sources",
- "subtask_results",
- "strategy",
- "recursion_depth",
- "questions",
- }
- assert expected_keys.issubset(result.keys())
-
- def test_progress_callback_called_during_synthesis(self):
- strategy = self._setup_strategy()
- callback = Mock()
- strategy.progress_callback = callback
- subtask_results = [
- {
- "subtask": "S",
- "result": {
- "current_knowledge": "K",
- "all_links_of_system": [],
- "findings": [],
- "questions_by_iteration": [],
- },
- "depth": 1,
- "index": 1,
- },
- ]
-
- with patch(f"{MODULE}.format_findings", return_value="formatted"):
- strategy._aggregate_subtask_results("q", subtask_results, 0)
-
- callback.assert_called()
- # Check synthesis phase callback
- synthesis_calls = [
- c for c in callback.call_args_list if "Synthesizing" in str(c)
- ]
- assert len(synthesis_calls) >= 1
-
-
-# ---------------------------------------------------------------------------
-# Max recursion depth guard
-# ---------------------------------------------------------------------------
-
-
-class TestMaxRecursionDepth:
- """Tests for recursion depth protection."""
-
- def test_at_max_depth_falls_back_to_source_strategy(self):
- """When recursion_depth >= max, uses source-based strategy."""
- strategy = _make_strategy(max_recursion_depth=3)
- strategy.all_links_of_system = []
- strategy.questions_by_iteration = []
- strategy.findings = []
-
- with patch.object(
- strategy,
- "_use_source_based_strategy",
- return_value={"current_knowledge": "direct", "findings": []},
- ) as mock_source:
- result = strategy.analyze_topic("query", recursion_depth=3)
-
- mock_source.assert_called_once_with("query")
- assert result["current_knowledge"] == "direct"
-
- def test_below_max_depth_proceeds_normally(self):
- """Below max depth, proceeds with decomposition decision."""
- strategy = _make_strategy(max_recursion_depth=5)
- strategy.model.invoke.return_value = _model_response(
- "DECISION: SEARCH_DIRECTLY\nREASONING: simple"
- )
-
- with patch.object(
- strategy,
- "_use_source_based_strategy",
- return_value={"current_knowledge": "found", "findings": []},
- ):
- result = strategy.analyze_topic("query", recursion_depth=0)
-
- assert result["current_knowledge"] == "found"
-
- def test_exactly_at_max_triggers_guard(self):
- strategy = _make_strategy(max_recursion_depth=2)
- strategy.all_links_of_system = []
- strategy.questions_by_iteration = []
- strategy.findings = []
-
- with patch.object(
- strategy,
- "_use_source_based_strategy",
- return_value={"current_knowledge": "fallback", "findings": []},
- ):
- result = strategy.analyze_topic("query", recursion_depth=2)
-
- assert result["current_knowledge"] == "fallback"
-
- def test_above_max_also_triggers_guard(self):
- strategy = _make_strategy(max_recursion_depth=2)
- strategy.all_links_of_system = []
- strategy.questions_by_iteration = []
- strategy.findings = []
-
- with patch.object(
- strategy,
- "_use_source_based_strategy",
- return_value={"current_knowledge": "fallback", "findings": []},
- ):
- result = strategy.analyze_topic("query", recursion_depth=10)
-
- assert result["current_knowledge"] == "fallback"
-
-
-# ---------------------------------------------------------------------------
-# analyze_topic initialization
-# ---------------------------------------------------------------------------
-
-
-class TestAnalyzeTopicInit:
- """Tests for top-level initialization in analyze_topic."""
-
- def test_clears_links_at_depth_zero(self):
- strategy = _make_strategy()
- strategy.all_links_of_system = ["old_link"]
- strategy.model.invoke.return_value = _model_response(
- "DECISION: SEARCH_DIRECTLY\nREASONING: direct"
- )
-
- with patch.object(
- strategy,
- "_use_source_based_strategy",
- return_value={"findings": [], "current_knowledge": "k"},
- ):
- strategy.analyze_topic("query", recursion_depth=0)
-
- # Links should have been cleared at depth 0
- # (may have new ones added by source strategy, but old one gone)
- assert "old_link" not in strategy.all_links_of_system
-
- def test_stores_original_query_at_depth_zero(self):
- strategy = _make_strategy()
- strategy.model.invoke.return_value = _model_response(
- "DECISION: SEARCH_DIRECTLY\nREASONING: direct"
- )
-
- with patch.object(
- strategy,
- "_use_source_based_strategy",
- return_value={"findings": [], "current_knowledge": "k"},
- ):
- strategy.analyze_topic("my research topic", recursion_depth=0)
-
- assert strategy.original_query == "my research topic"
-
- def test_initializes_findings_list_at_depth_zero(self):
- strategy = _make_strategy()
- strategy.findings = [{"old": True}]
- strategy.model.invoke.return_value = _model_response(
- "DECISION: SEARCH_DIRECTLY\nREASONING: direct"
- )
-
- with patch.object(
- strategy,
- "_use_source_based_strategy",
- return_value={"findings": [], "current_knowledge": "k"},
- ):
- strategy.analyze_topic("query", recursion_depth=0)
-
- # Old findings should be cleared, new ones may be added
- assert {"old": True} not in strategy.findings
-
- def test_progress_callback_at_depth_zero(self):
- strategy = _make_strategy()
- callback = Mock()
- strategy.set_progress_callback(callback)
- strategy.model.invoke.return_value = _model_response(
- "DECISION: SEARCH_DIRECTLY\nREASONING: direct"
- )
-
- with patch.object(
- strategy,
- "_use_source_based_strategy",
- return_value={"findings": [], "current_knowledge": "k"},
- ):
- strategy.analyze_topic("query", recursion_depth=0)
-
- # Should have been called with init phase
- init_calls = [
- c for c in callback.call_args_list if c[0][2].get("phase") == "init"
- ]
- assert len(init_calls) >= 1
-
- def test_adds_search_decision_to_findings(self):
- """When SEARCH_DIRECTLY, adds decision to findings."""
- strategy = _make_strategy()
- strategy.model.invoke.return_value = _model_response(
- "DECISION: SEARCH_DIRECTLY\nREASONING: simple enough"
- )
-
- with patch.object(
- strategy,
- "_use_source_based_strategy",
- return_value={"findings": [], "current_knowledge": "k"},
- ):
- strategy.analyze_topic("query", recursion_depth=0)
-
- # Should have a finding about the search decision
- phases = [f.get("phase", "") for f in strategy.findings]
- assert any("Direct Search Decision" in p for p in phases)
-
- def test_adds_decomposition_decision_to_findings(self):
- """When DECOMPOSE, adds decomposition decision to findings."""
- strategy = _make_strategy()
- strategy.model.invoke.return_value = _model_response(
- "DECISION: DECOMPOSE\n"
- "REASONING: multi-part\n"
- "SUBTASKS:\n"
- "1. Part A\n"
- "2. Part B\n"
- "DEPENDENCIES: none"
- )
-
- # Mock _handle_decomposition to avoid full recursion
- with patch.object(
- strategy,
- "_handle_decomposition",
- return_value={"findings": [], "current_knowledge": "k"},
- ):
- strategy.analyze_topic("complex query", recursion_depth=0)
-
- phases = [f.get("phase", "") for f in strategy.findings]
- assert any("Decomposition Decision" in p for p in phases)
diff --git a/tests/advanced_search_system/strategies/test_smart_decomp_pure_logic.py b/tests/advanced_search_system/strategies/test_smart_decomp_pure_logic.py
deleted file mode 100644
index d33633fbe1..0000000000
--- a/tests/advanced_search_system/strategies/test_smart_decomp_pure_logic.py
+++ /dev/null
@@ -1,53 +0,0 @@
-"""
-Pure-logic tests for SmartDecompositionStrategy._is_browsecomp_style.
-
-Tests indicator-phrase counting with the >= 3 threshold,
-requiring no LLM or search calls.
-"""
-
-from unittest.mock import Mock
-
-from local_deep_research.advanced_search_system.strategies.smart_decomposition_strategy import (
- SmartDecompositionStrategy,
-)
-
-
-class TestIsBrowsecompStyle:
- """Verify BrowseComp-style detection based on indicator phrase counting."""
-
- def _call(self, query):
- return SmartDecompositionStrategy._is_browsecomp_style(Mock(), query)
-
- def test_zero_indicators(self):
- """Query with no indicator phrases -> False."""
- assert self._call("What is the capital of France?") is False
-
- def test_one_indicator(self):
- """Query with one indicator -> False."""
- assert self._call("What is the name of the president?") is False
-
- def test_two_indicators(self):
- """Query with two indicators -> False (need >= 3)."""
- assert (
- self._call("What is the name of something between two cities?")
- is False
- )
-
- def test_three_indicators(self):
- """Query with exactly three indicators -> True."""
- query = "What is the name of the specific scenic location where search and rescue operates?"
- assert self._call(query) is True
-
- def test_many_indicators(self):
- """Query with many indicators -> True."""
- query = (
- "What is the name of the specific scenic location with a viewpoint "
- "where someone fell from during search and rescue SAR incidents "
- "involving a body part since the last ice age?"
- )
- assert self._call(query) is True
-
- def test_case_insensitive(self):
- """Indicator matching should be case-insensitive."""
- query = "WHAT IS THE NAME of a SPECIFIC SCENIC LOCATION with SEARCH AND RESCUE"
- assert self._call(query) is True
diff --git a/tests/advanced_search_system/strategies/test_smart_decomposition_high_value.py b/tests/advanced_search_system/strategies/test_smart_decomposition_high_value.py
deleted file mode 100644
index 8649aca03c..0000000000
--- a/tests/advanced_search_system/strategies/test_smart_decomposition_high_value.py
+++ /dev/null
@@ -1,634 +0,0 @@
-"""
-High-value tests for SmartDecompositionStrategy and QueryType.
-
-Covers pure logic paths:
-- QueryType enum completeness and values
-- _is_browsecomp_style indicator counting (threshold of 3)
-- _classify_query LLM response parsing (by name, by value, default fallback)
-- analyze_topic delegation to the correct sub-strategy
-- Progress callback invocation with query_type metadata
-"""
-
-from unittest.mock import MagicMock, Mock, patch
-
-import pytest
-
-from local_deep_research.advanced_search_system.strategies.smart_decomposition_strategy import (
- QueryType,
- SmartDecompositionStrategy,
-)
-
-# ---------------------------------------------------------------------------
-# Helpers
-# ---------------------------------------------------------------------------
-
-MODULE = "local_deep_research.advanced_search_system.strategies.smart_decomposition_strategy"
-
-
-def _make_strategy(progress_callback=None):
- """Create a SmartDecompositionStrategy with mocked model and search."""
- model = MagicMock()
- search = MagicMock()
- strategy = SmartDecompositionStrategy(
- model=model,
- search=search,
- all_links_of_system=[],
- settings_snapshot={},
- )
- if progress_callback is not None:
- strategy.set_progress_callback(progress_callback)
- return strategy
-
-
-def _model_response(text: str):
- """Return a mock LLM response object whose .content is *text*."""
- resp = Mock()
- resp.content = text
- return resp
-
-
-# ---------------------------------------------------------------------------
-# QueryType enum
-# ---------------------------------------------------------------------------
-
-
-class TestQueryType:
- """Tests for the QueryType enum."""
-
- def test_all_expected_members_exist(self):
- assert QueryType.PUZZLE_LIKE.value == "puzzle_like"
- assert QueryType.HIERARCHICAL.value == "hierarchical"
- assert QueryType.EXPLORATORY.value == "exploratory"
- assert QueryType.COMPARATIVE.value == "comparative"
- assert QueryType.FACTUAL.value == "factual"
- assert QueryType.CONSTRAINT_BASED.value == "constraint_based"
-
- def test_member_count(self):
- assert len(QueryType) == 6
-
- def test_members_are_unique(self):
- values = [qt.value for qt in QueryType]
- assert len(values) == len(set(values))
-
- def test_lookup_by_name(self):
- assert QueryType["PUZZLE_LIKE"] is QueryType.PUZZLE_LIKE
-
- def test_lookup_by_name_invalid_raises(self):
- with pytest.raises(KeyError):
- QueryType["NONEXISTENT"]
-
-
-# ---------------------------------------------------------------------------
-# _is_browsecomp_style
-# ---------------------------------------------------------------------------
-
-
-class TestIsBrowsecompStyle:
- """Tests for the browsecomp indicator detection heuristic."""
-
- def test_returns_true_with_three_indicators(self):
- strategy = _make_strategy()
- query = "At a specific scenic location, a body part fell from the viewpoint."
- assert strategy._is_browsecomp_style(query) is True
-
- def test_returns_true_with_many_indicators(self):
- strategy = _make_strategy()
- query = (
- "At a specific scenic location a body part fell from a viewpoint "
- "during search and rescue operations involving SAR incidents "
- "requiring an exact answer from multiple clues."
- )
- assert strategy._is_browsecomp_style(query) is True
-
- def test_returns_false_with_two_indicators(self):
- strategy = _make_strategy()
- query = "A body part fell from a height."
- assert strategy._is_browsecomp_style(query) is False
-
- def test_returns_false_with_zero_indicators(self):
- strategy = _make_strategy()
- query = "What is the capital of France?"
- assert strategy._is_browsecomp_style(query) is False
-
- def test_case_insensitive_matching(self):
- strategy = _make_strategy()
- query = (
- "SPECIFIC SCENIC LOCATION with BODY PART and FELL FROM the cliff."
- )
- assert strategy._is_browsecomp_style(query) is True
-
- def test_mixed_case_matching(self):
- strategy = _make_strategy()
- query = "Specific Scenic Location Body Part Fell From nowhere."
- assert strategy._is_browsecomp_style(query) is True
-
- def test_exact_threshold_boundary_two_indicators(self):
- """Exactly 2 indicators should return False (below threshold)."""
- strategy = _make_strategy()
- query = "search and rescue at a viewpoint"
- assert strategy._is_browsecomp_style(query) is False
-
- def test_exact_threshold_boundary_three_indicators(self):
- """Exactly 3 indicators should return True (at threshold)."""
- strategy = _make_strategy()
- query = "search and rescue at a viewpoint with a body part"
- assert strategy._is_browsecomp_style(query) is True
-
- def test_empty_query(self):
- strategy = _make_strategy()
- assert strategy._is_browsecomp_style("") is False
-
- def test_between_and_times_more_and_what_is_the_name(self):
- """Indicators 'between', 'times more', 'what is the name' count."""
- strategy = _make_strategy()
- query = "What is the name of the thing between A and B that is 5 times more?"
- assert strategy._is_browsecomp_style(query) is True
-
- def test_last_ice_age_indicator(self):
- """'last ice age' is one of the recognised indicators."""
- strategy = _make_strategy()
- query = "Since the last ice age, search and rescue at a viewpoint"
- assert strategy._is_browsecomp_style(query) is True
-
-
-# ---------------------------------------------------------------------------
-# _classify_query
-# ---------------------------------------------------------------------------
-
-
-class TestClassifyQuery:
- """Tests for LLM-based query classification and response parsing."""
-
- def test_parses_query_type_by_enum_name(self):
- """Exact enum member name on the QUERY_TYPE: line is parsed."""
- strategy = _make_strategy()
- strategy.model.invoke.return_value = _model_response(
- "QUERY_TYPE: PUZZLE_LIKE\nREASONING: has clues\nKEY_CHARACTERISTICS: clues"
- )
- result = strategy._classify_query("some puzzle query")
- assert result is QueryType.PUZZLE_LIKE
-
- def test_parses_hierarchical(self):
- strategy = _make_strategy()
- strategy.model.invoke.return_value = _model_response(
- "QUERY_TYPE: HIERARCHICAL\nREASONING: multi-part"
- )
- assert (
- strategy._classify_query("multi-part question")
- is QueryType.HIERARCHICAL
- )
-
- def test_parses_comparative(self):
- strategy = _make_strategy()
- strategy.model.invoke.return_value = _model_response(
- "QUERY_TYPE: COMPARATIVE\nREASONING: comparison"
- )
- assert (
- strategy._classify_query("compare X and Y") is QueryType.COMPARATIVE
- )
-
- def test_parses_factual(self):
- strategy = _make_strategy()
- strategy.model.invoke.return_value = _model_response(
- "QUERY_TYPE: FACTUAL\nREASONING: simple fact"
- )
- assert strategy._classify_query("what year was X?") is QueryType.FACTUAL
-
- def test_parses_constraint_based(self):
- strategy = _make_strategy()
- strategy.model.invoke.return_value = _model_response(
- "QUERY_TYPE: CONSTRAINT_BASED\nREASONING: constraints"
- )
- assert (
- strategy._classify_query("find the thing with these constraints")
- is QueryType.CONSTRAINT_BASED
- )
-
- def test_parses_exploratory(self):
- strategy = _make_strategy()
- strategy.model.invoke.return_value = _model_response(
- "QUERY_TYPE: EXPLORATORY\nREASONING: open-ended"
- )
- assert (
- strategy._classify_query("tell me about X") is QueryType.EXPLORATORY
- )
-
- def test_falls_back_to_value_match_when_key_fails(self):
- """When the type string is not a valid enum name, try matching by value."""
- strategy = _make_strategy()
- # 'puzzle_like' is the *value*, not the enum *name* (PUZZLE_LIKE).
- strategy.model.invoke.return_value = _model_response(
- "QUERY_TYPE: puzzle_like\nREASONING: has clues"
- )
- result = strategy._classify_query("puzzle query")
- assert result is QueryType.PUZZLE_LIKE
-
- def test_falls_back_to_value_match_constraint_based(self):
- strategy = _make_strategy()
- strategy.model.invoke.return_value = _model_response(
- "QUERY_TYPE: constraint_based\nREASONING: constraints"
- )
- assert (
- strategy._classify_query("constrained query")
- is QueryType.CONSTRAINT_BASED
- )
-
- def test_defaults_to_exploratory_on_unparseable_response(self):
- """When the response has no QUERY_TYPE: line, default to EXPLORATORY."""
- strategy = _make_strategy()
- strategy.model.invoke.return_value = _model_response(
- "I think this is a factual question."
- )
- result = strategy._classify_query("any query")
- assert result is QueryType.EXPLORATORY
-
- def test_defaults_to_exploratory_on_unknown_type(self):
- """Unknown type string that matches no name or value defaults to EXPLORATORY."""
- strategy = _make_strategy()
- strategy.model.invoke.return_value = _model_response(
- "QUERY_TYPE: COMPLETELY_UNKNOWN\nREASONING: no idea"
- )
- result = strategy._classify_query("weird query")
- assert result is QueryType.EXPLORATORY
-
- def test_handles_think_tags_in_response(self):
- """Think tags in the LLM output are stripped before parsing."""
- strategy = _make_strategy()
- strategy.model.invoke.return_value = _model_response(
- "<think>Let me think about this...</think>\n"
- "QUERY_TYPE: FACTUAL\nREASONING: simple"
- )
- result = strategy._classify_query("simple fact")
- assert result is QueryType.FACTUAL
-
- def test_multiline_response_finds_query_type_line(self):
- """QUERY_TYPE line buried among other lines is still found."""
- strategy = _make_strategy()
- strategy.model.invoke.return_value = _model_response(
- "Some preamble text.\n"
- "More discussion.\n"
- "QUERY_TYPE: COMPARATIVE\n"
- "REASONING: needs comparison\n"
- "KEY_CHARACTERISTICS: two entities"
- )
- assert (
- strategy._classify_query("compare A vs B") is QueryType.COMPARATIVE
- )
-
- def test_empty_response_defaults_to_exploratory(self):
- strategy = _make_strategy()
- strategy.model.invoke.return_value = _model_response("")
- assert strategy._classify_query("anything") is QueryType.EXPLORATORY
-
- def test_value_match_is_case_insensitive(self):
- """Value matching uses .lower() so mixed-case values still match."""
- strategy = _make_strategy()
- strategy.model.invoke.return_value = _model_response(
- "QUERY_TYPE: Puzzle_Like\nREASONING: clues"
- )
- result = strategy._classify_query("puzzle")
- assert result is QueryType.PUZZLE_LIKE
-
-
-# ---------------------------------------------------------------------------
-# analyze_topic delegation
-# ---------------------------------------------------------------------------
-
-
-class TestAnalyzeTopicDelegation:
- """Tests that analyze_topic routes to the correct sub-strategy."""
-
- def _patch_classify(self, strategy, query_type):
- """Patch _classify_query to return a fixed QueryType."""
- strategy._classify_query = Mock(return_value=query_type)
-
- def _patch_browsecomp_check(self, strategy, result):
- """Patch _is_browsecomp_style to return a fixed boolean."""
- strategy._is_browsecomp_style = Mock(return_value=result)
-
- # -- PUZZLE_LIKE + browsecomp -> browsecomp strategy -------------------
-
- @patch(f"{MODULE}.BrowseCompOptimizedStrategy")
- def test_puzzle_like_browsecomp_uses_browsecomp_strategy(self, MockBrowse):
- strategy = _make_strategy()
- self._patch_classify(strategy, QueryType.PUZZLE_LIKE)
- self._patch_browsecomp_check(strategy, True)
-
- mock_sub = MockBrowse.return_value
- mock_sub.analyze_topic.return_value = {"result": "browsecomp"}
-
- result = strategy.analyze_topic("browsecomp puzzle query")
-
- MockBrowse.assert_called_once_with(
- model=strategy.model,
- search=strategy.search,
- all_links_of_system=strategy.all_links_of_system,
- )
- mock_sub.analyze_topic.assert_called_once_with(
- "browsecomp puzzle query"
- )
- assert result == {"result": "browsecomp"}
-
- # -- PUZZLE_LIKE + not browsecomp -> evidence strategy ------------------
-
- @patch(f"{MODULE}.EvidenceBasedStrategy")
- def test_puzzle_like_non_browsecomp_uses_evidence_strategy(
- self, MockEvidence
- ):
- strategy = _make_strategy()
- self._patch_classify(strategy, QueryType.PUZZLE_LIKE)
- self._patch_browsecomp_check(strategy, False)
-
- mock_sub = MockEvidence.return_value
- mock_sub.analyze_topic.return_value = {"result": "evidence"}
-
- result = strategy.analyze_topic("non-browsecomp puzzle")
-
- MockEvidence.assert_called_once()
- mock_sub.analyze_topic.assert_called_once_with("non-browsecomp puzzle")
- assert result == {"result": "evidence"}
-
- # -- CONSTRAINT_BASED -> evidence strategy ------------------------------
-
- @patch(f"{MODULE}.EvidenceBasedStrategy")
- def test_constraint_based_uses_evidence_strategy(self, MockEvidence):
- strategy = _make_strategy()
- self._patch_classify(strategy, QueryType.CONSTRAINT_BASED)
-
- mock_sub = MockEvidence.return_value
- mock_sub.analyze_topic.return_value = {"result": "evidence_constraint"}
-
- result = strategy.analyze_topic("constrained query")
-
- MockEvidence.assert_called_once()
- mock_sub.analyze_topic.assert_called_once_with("constrained query")
- assert result == {"result": "evidence_constraint"}
-
- # -- HIERARCHICAL -> recursive strategy ---------------------------------
-
- @patch(f"{MODULE}.RecursiveDecompositionStrategy")
- def test_hierarchical_uses_recursive_strategy(self, MockRecursive):
- strategy = _make_strategy()
- self._patch_classify(strategy, QueryType.HIERARCHICAL)
-
- mock_sub = MockRecursive.return_value
- mock_sub.analyze_topic.return_value = {"result": "recursive"}
-
- result = strategy.analyze_topic("multi-part hierarchical query")
-
- MockRecursive.assert_called_once()
- mock_sub.analyze_topic.assert_called_once_with(
- "multi-part hierarchical query"
- )
- assert result == {"result": "recursive"}
-
- # -- COMPARATIVE -> recursive strategy ----------------------------------
-
- @patch(f"{MODULE}.RecursiveDecompositionStrategy")
- def test_comparative_uses_recursive_strategy(self, MockRecursive):
- strategy = _make_strategy()
- self._patch_classify(strategy, QueryType.COMPARATIVE)
-
- mock_sub = MockRecursive.return_value
- mock_sub.analyze_topic.return_value = {"result": "recursive_comp"}
-
- result = strategy.analyze_topic("compare X and Y")
-
- MockRecursive.assert_called_once()
- mock_sub.analyze_topic.assert_called_once_with("compare X and Y")
- assert result == {"result": "recursive_comp"}
-
- # -- EXPLORATORY -> recursive strategy ----------------------------------
-
- @patch(f"{MODULE}.RecursiveDecompositionStrategy")
- def test_exploratory_uses_recursive_strategy(self, MockRecursive):
- strategy = _make_strategy()
- self._patch_classify(strategy, QueryType.EXPLORATORY)
-
- mock_sub = MockRecursive.return_value
- mock_sub.analyze_topic.return_value = {"result": "recursive_exp"}
-
- result = strategy.analyze_topic("open-ended research question")
-
- MockRecursive.assert_called_once()
- mock_sub.analyze_topic.assert_called_once_with(
- "open-ended research question"
- )
- assert result == {"result": "recursive_exp"}
-
- # -- FACTUAL -> adaptive strategy ---------------------------------------
-
- @patch(f"{MODULE}.AdaptiveDecompositionStrategy")
- def test_factual_uses_adaptive_strategy(self, MockAdaptive):
- strategy = _make_strategy()
- self._patch_classify(strategy, QueryType.FACTUAL)
-
- mock_sub = MockAdaptive.return_value
- mock_sub.analyze_topic.return_value = {"result": "adaptive"}
-
- result = strategy.analyze_topic("what year was X founded?")
-
- MockAdaptive.assert_called_once()
- mock_sub.analyze_topic.assert_called_once_with(
- "what year was X founded?"
- )
- assert result == {"result": "adaptive"}
-
-
-# ---------------------------------------------------------------------------
-# Progress callback
-# ---------------------------------------------------------------------------
-
-
-class TestProgressCallback:
- """Tests that the progress callback is invoked correctly."""
-
- @patch(f"{MODULE}.AdaptiveDecompositionStrategy")
- def test_progress_callback_called_with_query_type(self, MockAdaptive):
- callback = Mock()
- strategy = _make_strategy(progress_callback=callback)
- strategy._classify_query = Mock(return_value=QueryType.FACTUAL)
-
- mock_sub = MockAdaptive.return_value
- mock_sub.analyze_topic.return_value = {}
-
- strategy.analyze_topic("test query")
-
- callback.assert_called_once_with(
- "Analyzing query type: factual",
- 5,
- {
- "phase": "query_classification",
- "query_type": "factual",
- },
- )
-
- @patch(f"{MODULE}.RecursiveDecompositionStrategy")
- def test_progress_callback_reports_correct_query_type_value(
- self, MockRecursive
- ):
- callback = Mock()
- strategy = _make_strategy(progress_callback=callback)
- strategy._classify_query = Mock(return_value=QueryType.HIERARCHICAL)
-
- mock_sub = MockRecursive.return_value
- mock_sub.analyze_topic.return_value = {}
-
- strategy.analyze_topic("hierarchical query")
-
- callback.assert_called_once()
- call_args = callback.call_args
- assert call_args[0][0] == "Analyzing query type: hierarchical"
- assert call_args[0][2]["query_type"] == "hierarchical"
-
- @patch(f"{MODULE}.AdaptiveDecompositionStrategy")
- def test_no_progress_callback_does_not_raise(self, MockAdaptive):
- """When no callback is set, analyze_topic completes without error."""
- strategy = _make_strategy() # no callback
- strategy._classify_query = Mock(return_value=QueryType.FACTUAL)
-
- mock_sub = MockAdaptive.return_value
- mock_sub.analyze_topic.return_value = {}
-
- # Should not raise
- strategy.analyze_topic("test query")
-
- @patch(f"{MODULE}.BrowseCompOptimizedStrategy")
- def test_progress_callback_propagated_to_sub_strategy(self, MockBrowse):
- """The callback is forwarded to the sub-strategy via set_progress_callback."""
- callback = Mock()
- strategy = _make_strategy(progress_callback=callback)
- strategy._classify_query = Mock(return_value=QueryType.PUZZLE_LIKE)
- strategy._is_browsecomp_style = Mock(return_value=True)
-
- mock_sub = MockBrowse.return_value
- mock_sub.analyze_topic.return_value = {}
-
- strategy.analyze_topic("puzzle query")
-
- mock_sub.set_progress_callback.assert_called_once_with(callback)
-
-
-# ---------------------------------------------------------------------------
-# Sub-strategy kwargs propagation
-# ---------------------------------------------------------------------------
-
-
-class TestKwargsPassthrough:
- """Verify that extra kwargs are forwarded to sub-strategies."""
-
- @patch(f"{MODULE}.RecursiveDecompositionStrategy")
- def test_strategy_params_forwarded(self, MockRecursive):
- model = MagicMock()
- search = MagicMock()
- strategy = SmartDecompositionStrategy(
- model=model,
- search=search,
- all_links_of_system=[],
- settings_snapshot={},
- max_iterations=5,
- custom_param="hello",
- )
- strategy._classify_query = Mock(return_value=QueryType.HIERARCHICAL)
-
- mock_sub = MockRecursive.return_value
- mock_sub.analyze_topic.return_value = {}
-
- strategy.analyze_topic("hierarchical query")
-
- MockRecursive.assert_called_once_with(
- model=model,
- search=search,
- all_links_of_system=[],
- max_iterations=5,
- custom_param="hello",
- )
-
- @patch(f"{MODULE}.EvidenceBasedStrategy")
- def test_strategy_params_forwarded_to_evidence(self, MockEvidence):
- model = MagicMock()
- search = MagicMock()
- strategy = SmartDecompositionStrategy(
- model=model,
- search=search,
- all_links_of_system=["link1"],
- settings_snapshot={},
- depth=3,
- )
- strategy._classify_query = Mock(return_value=QueryType.CONSTRAINT_BASED)
-
- mock_sub = MockEvidence.return_value
- mock_sub.analyze_topic.return_value = {}
-
- strategy.analyze_topic("constraint query")
-
- MockEvidence.assert_called_once_with(
- model=model,
- search=search,
- all_links_of_system=["link1"],
- depth=3,
- )
-
-
-# ---------------------------------------------------------------------------
-# Edge cases
-# ---------------------------------------------------------------------------
-
-
-class TestEdgeCases:
- """Edge-case tests for robustness."""
-
- def test_classify_query_with_extra_whitespace_in_type(self):
- """Extra whitespace around the type string is stripped."""
- strategy = _make_strategy()
- strategy.model.invoke.return_value = _model_response(
- "QUERY_TYPE: FACTUAL \nREASONING: simple"
- )
- assert strategy._classify_query("fact query") is QueryType.FACTUAL
-
- def test_classify_query_with_colon_in_reasoning(self):
- """Colons in subsequent parts of the line don't break parsing."""
- strategy = _make_strategy()
- strategy.model.invoke.return_value = _model_response(
- "QUERY_TYPE: HIERARCHICAL\nREASONING: has parts: a, b, c"
- )
- assert strategy._classify_query("parts query") is QueryType.HIERARCHICAL
-
- def test_classify_query_first_query_type_line_wins(self):
- """If multiple QUERY_TYPE lines exist, the last one wins (loop iterates all)."""
- strategy = _make_strategy()
- strategy.model.invoke.return_value = _model_response(
- "QUERY_TYPE: FACTUAL\nQUERY_TYPE: COMPARATIVE\nREASONING: mixed"
- )
- # The loop iterates all lines, so the last QUERY_TYPE line wins
- assert (
- strategy._classify_query("ambiguous query") is QueryType.COMPARATIVE
- )
-
- @patch(f"{MODULE}.AdaptiveDecompositionStrategy")
- def test_analyze_topic_returns_sub_strategy_result_unchanged(
- self, MockAdaptive
- ):
- """The dict returned by the sub-strategy is returned as-is."""
- strategy = _make_strategy()
- strategy._classify_query = Mock(return_value=QueryType.FACTUAL)
-
- expected = {
- "findings": [{"text": "found it"}],
- "iterations": 2,
- "questions": {"1": ["q1"]},
- "formatted_findings": "formatted",
- "current_knowledge": "knowledge",
- }
- MockAdaptive.return_value.analyze_topic.return_value = expected
-
- result = strategy.analyze_topic("query")
- assert result is expected
-
- def test_browsecomp_partial_indicator_no_match(self):
- """Substring match: 'body' alone does not match 'body part'."""
- strategy = _make_strategy()
- query = "body, fell, viewpoint fragment"
- # 'body' != 'body part'; 'fell' != 'fell from'; 'viewpoint' does match
- # Only 1 indicator matches ('viewpoint'), so should be False
- assert strategy._is_browsecomp_style(query) is False
diff --git a/tests/advanced_search_system/strategies/test_smart_query_high_value.py b/tests/advanced_search_system/strategies/test_smart_query_high_value.py
deleted file mode 100644
index 66a2e09ffd..0000000000
--- a/tests/advanced_search_system/strategies/test_smart_query_high_value.py
+++ /dev/null
@@ -1,264 +0,0 @@
-"""
-High-value pure logic tests for SmartQueryStrategy.
-
-Tests focus on _build_standard_query() and _should_use_entity_seeding()
-without requiring LLM calls or external dependencies.
-"""
-
-from unittest.mock import patch
-
-
-from local_deep_research.advanced_search_system.constraints.base_constraint import (
- Constraint,
- ConstraintType,
-)
-from local_deep_research.advanced_search_system.strategies.smart_query_strategy import (
- SmartQueryStrategy,
-)
-
-
-def _make_strategy(**attrs):
- """Create a SmartQueryStrategy with __init__ bypassed and attributes set."""
- with patch.object(
- SmartQueryStrategy, "__init__", lambda self, *a, **kw: None
- ):
- strategy = SmartQueryStrategy()
- strategy.searched_queries = set()
- strategy.query_variations = set()
- strategy.entity_type = "unknown entity"
- for key, val in attrs.items():
- setattr(strategy, key, val)
- return strategy
-
-
-def _make_constraint(
- value, weight=1.0, ctype=ConstraintType.PROPERTY, cid=None
-):
- """Helper to build a Constraint with sensible defaults."""
- return Constraint(
- id=cid or f"c_{value[:8]}",
- type=ctype,
- description=f"desc for {value}",
- value=value,
- weight=weight,
- )
-
-
-class TestBuildStandardQueryQuoting:
- """Tests for multi-word quoting behaviour in _build_standard_query."""
-
- def test_multi_word_term_gets_quoted(self):
- strategy = _make_strategy()
- constraints = [_make_constraint("blue eyes", weight=0.9)]
- result = strategy._build_standard_query(constraints)
- assert '"blue eyes"' in result
-
- def test_single_word_term_not_quoted(self):
- strategy = _make_strategy()
- constraints = [_make_constraint("tall", weight=0.9)]
- result = strategy._build_standard_query(constraints)
- assert '"tall"' not in result
- assert "tall" in result
-
- def test_already_quoted_term_stays_quoted(self):
- strategy = _make_strategy()
- constraints = [_make_constraint('"ice age"', weight=0.9)]
- result = strategy._build_standard_query(constraints)
- # Should not get double-quoted
- assert '""ice age""' not in result
- assert '"ice age"' in result
-
- def test_term_with_internal_space_but_already_quoted(self):
- strategy = _make_strategy()
- constraints = [_make_constraint('"dark knight"', weight=0.5)]
- result = strategy._build_standard_query(constraints)
- assert '"dark knight"' in result
- assert '""' not in result
-
-
-class TestBuildStandardQueryWeightSplitting:
- """Tests for critical vs supplementary term splitting based on weight."""
-
- def test_high_weight_treated_as_critical(self):
- strategy = _make_strategy()
- constraints = [_make_constraint("stretchy", weight=0.9)]
- result = strategy._build_standard_query(constraints)
- assert "stretchy" in result
-
- def test_low_weight_treated_as_supplementary(self):
- strategy = _make_strategy()
- constraints = [_make_constraint("optional trait", weight=0.3)]
- result = strategy._build_standard_query(constraints)
- assert '"optional trait"' in result
-
- def test_weight_exactly_0_7_is_supplementary(self):
- """Weight must be strictly > 0.7 to be critical."""
- strategy = _make_strategy()
- critical = _make_constraint("important", weight=0.8)
- borderline = _make_constraint("borderline", weight=0.7)
- # Both should appear, but order reflects critical first then supplementary
- result = strategy._build_standard_query([critical, borderline])
- idx_important = result.index("important")
- idx_borderline = result.index("borderline")
- assert idx_important < idx_borderline
-
- def test_weight_0_71_is_critical(self):
- strategy = _make_strategy()
- constraints = [_make_constraint("just above", weight=0.71)]
- result = strategy._build_standard_query(constraints)
- assert '"just above"' in result
-
- def test_only_first_two_supplementary_terms_included(self):
- strategy = _make_strategy()
- constraints = [
- _make_constraint("supp1", weight=0.3),
- _make_constraint("supp2", weight=0.4),
- _make_constraint("supp3", weight=0.5),
- ]
- result = strategy._build_standard_query(constraints)
- assert "supp1" in result
- assert "supp2" in result
- assert "supp3" not in result
-
- def test_many_supplementary_only_two_included(self):
- strategy = _make_strategy()
- constraints = [
- _make_constraint(f"supp{i}", weight=0.2) for i in range(5)
- ]
- result = strategy._build_standard_query(constraints)
- parts = result.split()
- # Only supp0 and supp1 should appear
- assert "supp0" in parts
- assert "supp1" in parts
- assert "supp2" not in parts
-
- def test_critical_and_supplementary_mixed(self):
- strategy = _make_strategy()
- constraints = [
- _make_constraint("crit1", weight=0.9),
- _make_constraint("crit2", weight=0.8),
- _make_constraint("sup1", weight=0.5),
- _make_constraint("sup2", weight=0.3),
- _make_constraint("sup3", weight=0.1),
- ]
- result = strategy._build_standard_query(constraints)
- assert "crit1" in result
- assert "crit2" in result
- assert "sup1" in result
- assert "sup2" in result
- assert "sup3" not in result
-
-
-class TestBuildStandardQueryEntityType:
- """Tests for entity_type inclusion in _build_standard_query."""
-
- def test_entity_type_added_when_known(self):
- strategy = _make_strategy(entity_type="superhero")
- constraints = [_make_constraint("stretchy", weight=0.9)]
- result = strategy._build_standard_query(constraints)
- assert result.startswith("superhero")
-
- def test_entity_type_not_added_when_unknown(self):
- strategy = _make_strategy(entity_type="unknown entity")
- constraints = [_make_constraint("stretchy", weight=0.9)]
- result = strategy._build_standard_query(constraints)
- assert "unknown entity" not in result
-
- def test_entity_type_not_added_when_none(self):
- strategy = _make_strategy(entity_type=None)
- constraints = [_make_constraint("stretchy", weight=0.9)]
- result = strategy._build_standard_query(constraints)
- assert result == "stretchy"
-
- def test_entity_type_not_added_when_missing(self):
- strategy = _make_strategy()
- # Remove entity_type entirely
- if hasattr(strategy, "entity_type"):
- delattr(strategy, "entity_type")
- constraints = [_make_constraint("stretchy", weight=0.9)]
- result = strategy._build_standard_query(constraints)
- assert result == "stretchy"
-
- def test_entity_type_appears_before_constraint_terms(self):
- strategy = _make_strategy(entity_type="anime character")
- constraints = [_make_constraint("fire powers", weight=0.9)]
- result = strategy._build_standard_query(constraints)
- assert result.startswith("anime character")
-
-
-class TestBuildStandardQueryEdgeCases:
- """Edge cases for _build_standard_query."""
-
- def test_empty_constraints(self):
- strategy = _make_strategy()
- result = strategy._build_standard_query([])
- assert result == ""
-
- def test_single_constraint(self):
- strategy = _make_strategy()
- constraints = [_make_constraint("elastic body", weight=0.9)]
- result = strategy._build_standard_query(constraints)
- assert '"elastic body"' in result
-
- def test_all_parts_joined_with_spaces(self):
- strategy = _make_strategy(entity_type="person")
- constraints = [
- _make_constraint("tall", weight=0.9),
- _make_constraint("brown hair", weight=0.5),
- ]
- result = strategy._build_standard_query(constraints)
- # Should be space-joined, no double spaces
- assert " " not in result
- parts = result.split(" ")
- assert parts[0] == "person"
- assert "tall" in parts
-
-
-class TestShouldUseEntitySeeding:
- """Tests for _should_use_entity_seeding logic."""
-
- def test_character_returns_true(self):
- strategy = _make_strategy(entity_type="anime character")
- assert strategy._should_use_entity_seeding() is True
-
- def test_person_returns_true(self):
- strategy = _make_strategy(entity_type="famous person")
- assert strategy._should_use_entity_seeding() is True
-
- def test_hero_returns_true(self):
- strategy = _make_strategy(entity_type="superhero")
- assert strategy._should_use_entity_seeding() is True
-
- def test_case_insensitive_character(self):
- strategy = _make_strategy(entity_type="VIDEO GAME CHARACTER")
- assert strategy._should_use_entity_seeding() is True
-
- def test_case_insensitive_person(self):
- strategy = _make_strategy(entity_type="PERSON")
- assert strategy._should_use_entity_seeding() is True
-
- def test_case_insensitive_hero(self):
- strategy = _make_strategy(entity_type="HERO")
- assert strategy._should_use_entity_seeding() is True
-
- def test_location_returns_false(self):
- strategy = _make_strategy(entity_type="location")
- assert strategy._should_use_entity_seeding() is False
-
- def test_unknown_returns_false(self):
- strategy = _make_strategy(entity_type="unknown entity")
- assert strategy._should_use_entity_seeding() is False
-
- def test_empty_string_returns_false(self):
- strategy = _make_strategy(entity_type="")
- assert strategy._should_use_entity_seeding() is False
-
- def test_event_returns_false(self):
- strategy = _make_strategy(entity_type="historical event")
- assert strategy._should_use_entity_seeding() is False
-
- def test_no_entity_type_attr_returns_false(self):
- strategy = _make_strategy()
- if hasattr(strategy, "entity_type"):
- delattr(strategy, "entity_type")
- assert strategy._should_use_entity_seeding() is False
diff --git a/tests/advanced_search_system/strategies/test_standard_strategy.py b/tests/advanced_search_system/strategies/test_standard_strategy.py
deleted file mode 100644
index c0f23e5aee..0000000000
--- a/tests/advanced_search_system/strategies/test_standard_strategy.py
+++ /dev/null
@@ -1,498 +0,0 @@
-"""
-Tests for StandardSearchStrategy.
-
-Tests cover:
-- Initialization with dependencies
-- Settings access
-- Analyze topic flow
-- Error handling for missing search engine
-- Question generation integration
-"""
-
-from unittest.mock import Mock, patch
-
-
-class TestStandardSearchStrategyInit:
- """Tests for StandardSearchStrategy initialization."""
-
- def test_init_with_required_params(self):
- """Initialize with required parameters."""
- from local_deep_research.advanced_search_system.strategies.standard_strategy import (
- StandardSearchStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- settings_snapshot = {
- "search.iterations": {"value": 3},
- "search.questions_per_iteration": {"value": 5},
- "general.knowledge_accumulation_context_limit": {"value": 10000},
- }
-
- strategy = StandardSearchStrategy(
- search=mock_search,
- model=mock_model,
- settings_snapshot=settings_snapshot,
- )
-
- assert strategy.search is mock_search
- assert strategy.model is mock_model
- assert strategy.max_iterations == 3
- assert strategy.questions_per_iteration == 5
- assert strategy.context_limit == 10000
-
- def test_init_creates_components(self):
- """Initialize creates required components."""
- from local_deep_research.advanced_search_system.strategies.standard_strategy import (
- StandardSearchStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- settings_snapshot = {
- "search.iterations": {"value": 2},
- "search.questions_per_iteration": {"value": 3},
- "general.knowledge_accumulation_context_limit": {"value": 5000},
- }
-
- strategy = StandardSearchStrategy(
- search=mock_search,
- model=mock_model,
- settings_snapshot=settings_snapshot,
- )
-
- assert strategy.question_generator is not None
- assert strategy.knowledge_generator is not None
- assert strategy.findings_repository is not None
- assert strategy.citation_handler is not None
-
- def test_init_with_custom_citation_handler(self):
- """Initialize with custom citation handler."""
- from local_deep_research.advanced_search_system.strategies.standard_strategy import (
- StandardSearchStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
- mock_citation_handler = Mock()
-
- settings_snapshot = {
- "search.iterations": {"value": 2},
- "search.questions_per_iteration": {"value": 3},
- "general.knowledge_accumulation_context_limit": {"value": 5000},
- }
-
- strategy = StandardSearchStrategy(
- search=mock_search,
- model=mock_model,
- citation_handler=mock_citation_handler,
- settings_snapshot=settings_snapshot,
- )
-
- assert strategy.citation_handler is mock_citation_handler
-
- def test_init_inherits_base_attributes(self):
- """Initialize inherits base strategy attributes."""
- from local_deep_research.advanced_search_system.strategies.standard_strategy import (
- StandardSearchStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
- links = [{"url": "https://example.com"}]
-
- settings_snapshot = {
- "search.iterations": {"value": 1},
- "search.questions_per_iteration": {"value": 2},
- "general.knowledge_accumulation_context_limit": {"value": 5000},
- }
-
- strategy = StandardSearchStrategy(
- search=mock_search,
- model=mock_model,
- all_links_of_system=links,
- settings_snapshot=settings_snapshot,
- )
-
- assert strategy.all_links_of_system is links
- assert strategy.questions_by_iteration == {}
-
-
-class TestAnalyzeTopic:
- """Tests for analyze_topic method."""
-
- def test_analyze_topic_no_search_engine(self):
- """Analyze topic returns error when no search engine."""
- from local_deep_research.advanced_search_system.strategies.standard_strategy import (
- StandardSearchStrategy,
- )
-
- mock_model = Mock()
-
- settings_snapshot = {
- "search.iterations": {"value": 1},
- "search.questions_per_iteration": {"value": 2},
- "general.knowledge_accumulation_context_limit": {"value": 5000},
- }
-
- strategy = StandardSearchStrategy(
- search=None, # No search engine
- model=mock_model,
- settings_snapshot=settings_snapshot,
- )
-
- result = strategy.analyze_topic("test query")
-
- assert result["findings"] == []
- assert result["iterations"] == 0
- assert "error" in result
- assert "No search engine available" in result["error"]
-
- def test_analyze_topic_calls_progress_callback(self):
- """Analyze topic calls progress callback."""
- from local_deep_research.advanced_search_system.strategies.standard_strategy import (
- StandardSearchStrategy,
- )
-
- mock_search = Mock()
- mock_search.run.return_value = []
- mock_model = Mock()
- mock_model.invoke.return_value = Mock(content="No questions")
-
- settings_snapshot = {
- "search.iterations": {"value": 1},
- "search.questions_per_iteration": {"value": 2},
- "general.knowledge_accumulation_context_limit": {"value": 5000},
- "general.knowledge_accumulation": {"value": "ITERATION"},
- }
-
- strategy = StandardSearchStrategy(
- search=mock_search,
- model=mock_model,
- settings_snapshot=settings_snapshot,
- )
-
- callback = Mock()
- strategy.set_progress_callback(callback)
-
- with patch.object(
- strategy.question_generator, "generate_questions", return_value=[]
- ):
- strategy.analyze_topic("test query")
-
- # Progress callback should be called multiple times
- assert callback.call_count >= 1
-
- def test_analyze_topic_generates_questions(self):
- """Analyze topic generates questions and stores them."""
- from local_deep_research.advanced_search_system.strategies.standard_strategy import (
- StandardSearchStrategy,
- )
-
- mock_search = Mock()
- mock_search.run.return_value = [] # No search results
- mock_model = Mock()
- # Return proper string content from model invokes
- mock_model.invoke.return_value = Mock(content="Synthesized result text")
-
- settings_snapshot = {
- "search.iterations": {"value": 1},
- "search.questions_per_iteration": {"value": 2},
- "general.knowledge_accumulation_context_limit": {"value": 5000},
- "general.knowledge_accumulation": {"value": "ITERATION"},
- }
-
- strategy = StandardSearchStrategy(
- search=mock_search,
- model=mock_model,
- settings_snapshot=settings_snapshot,
- )
-
- # Mock question generator to return specific questions
- with patch.object(
- strategy.question_generator,
- "generate_questions",
- return_value=["Q1", "Q2"],
- ):
- result = strategy.analyze_topic("test query")
-
- # Questions should be stored
- assert 0 in strategy.questions_by_iteration
- assert strategy.questions_by_iteration[0] == ["Q1", "Q2"]
- # Result should have questions dictionary
- assert "questions" in result
-
-
-class TestUpdateProgress:
- """Tests for _update_progress method in StandardSearchStrategy."""
-
- def test_update_progress_with_callback(self):
- """Update progress calls callback."""
- from local_deep_research.advanced_search_system.strategies.standard_strategy import (
- StandardSearchStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- settings_snapshot = {
- "search.iterations": {"value": 1},
- "search.questions_per_iteration": {"value": 2},
- "general.knowledge_accumulation_context_limit": {"value": 5000},
- }
-
- strategy = StandardSearchStrategy(
- search=mock_search,
- model=mock_model,
- settings_snapshot=settings_snapshot,
- )
-
- callback = Mock()
- strategy.progress_callback = callback
-
- strategy._update_progress("Test message", 50, {"key": "value"})
-
- callback.assert_called_once_with("Test message", 50, {"key": "value"})
-
- def test_update_progress_without_callback(self):
- """Update progress does nothing without callback."""
- from local_deep_research.advanced_search_system.strategies.standard_strategy import (
- StandardSearchStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- settings_snapshot = {
- "search.iterations": {"value": 1},
- "search.questions_per_iteration": {"value": 2},
- "general.knowledge_accumulation_context_limit": {"value": 5000},
- }
-
- strategy = StandardSearchStrategy(
- search=mock_search,
- model=mock_model,
- settings_snapshot=settings_snapshot,
- )
-
- # Should not raise
- strategy._update_progress("Test message", 50)
-
-
-class TestSettingsIntegration:
- """Tests for settings integration."""
-
- def test_uses_settings_for_iterations(self):
- """Uses settings snapshot for max_iterations."""
- from local_deep_research.advanced_search_system.strategies.standard_strategy import (
- StandardSearchStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- settings_snapshot = {
- "search.iterations": {"value": 5},
- "search.questions_per_iteration": {"value": 3},
- "general.knowledge_accumulation_context_limit": {"value": 8000},
- }
-
- strategy = StandardSearchStrategy(
- search=mock_search,
- model=mock_model,
- settings_snapshot=settings_snapshot,
- )
-
- assert strategy.max_iterations == 5
- assert strategy.questions_per_iteration == 3
- assert strategy.context_limit == 8000
-
- def test_settings_value_extraction(self):
- """Extracts values from settings with 'value' key."""
- from local_deep_research.advanced_search_system.strategies.standard_strategy import (
- StandardSearchStrategy,
- )
-
- mock_search = Mock()
- mock_model = Mock()
-
- # Settings with nested 'value' key
- settings_snapshot = {
- "search.iterations": {"value": 4, "ui_element": "number"},
- "search.questions_per_iteration": {
- "value": 6,
- "ui_element": "number",
- },
- "general.knowledge_accumulation_context_limit": {
- "value": 15000,
- "ui_element": "number",
- },
- }
-
- strategy = StandardSearchStrategy(
- search=mock_search,
- model=mock_model,
- settings_snapshot=settings_snapshot,
- )
-
- assert strategy.max_iterations == 4
- assert strategy.questions_per_iteration == 6
- assert strategy.context_limit == 15000
-
-
-class TestErrorHandling:
- """Tests for error handling in StandardSearchStrategy."""
-
- def test_handles_empty_search_results_gracefully(self):
- """Handles empty search results gracefully."""
- from local_deep_research.advanced_search_system.strategies.standard_strategy import (
- StandardSearchStrategy,
- )
-
- mock_search = Mock()
- mock_search.run.return_value = [] # Empty results
- mock_model = Mock()
- mock_model.invoke.return_value = Mock(content="Synthesized result")
-
- settings_snapshot = {
- "search.iterations": {"value": 1},
- "search.questions_per_iteration": {"value": 2},
- "general.knowledge_accumulation_context_limit": {"value": 5000},
- "general.knowledge_accumulation": {"value": "ITERATION"},
- }
-
- strategy = StandardSearchStrategy(
- search=mock_search,
- model=mock_model,
- settings_snapshot=settings_snapshot,
- )
-
- with patch.object(
- strategy.question_generator,
- "generate_questions",
- return_value=["Q1", "Q2"],
- ):
- result = strategy.analyze_topic("test query")
-
- # Should return a result even with empty search results
- assert isinstance(result, dict)
- assert "findings" in result
-
- def test_handles_none_search_results_gracefully(self):
- """Handles None search results gracefully."""
- from local_deep_research.advanced_search_system.strategies.standard_strategy import (
- StandardSearchStrategy,
- )
-
- mock_search = Mock()
- mock_search.run.return_value = None # None results
- mock_model = Mock()
- mock_model.invoke.return_value = Mock(content="Synthesized result")
-
- settings_snapshot = {
- "search.iterations": {"value": 1},
- "search.questions_per_iteration": {"value": 2},
- "general.knowledge_accumulation_context_limit": {"value": 5000},
- "general.knowledge_accumulation": {"value": "ITERATION"},
- }
-
- strategy = StandardSearchStrategy(
- search=mock_search,
- model=mock_model,
- settings_snapshot=settings_snapshot,
- )
-
- with patch.object(
- strategy.question_generator,
- "generate_questions",
- return_value=["Q1"],
- ):
- result = strategy.analyze_topic("test query")
-
- # Should return a result even with None search results
- assert isinstance(result, dict)
-
-
-class TestComponentIntegration:
- """Tests for component integration."""
-
- def test_question_generator_receives_correct_params(self):
- """Question generator receives correct parameters."""
- from local_deep_research.advanced_search_system.strategies.standard_strategy import (
- StandardSearchStrategy,
- )
-
- mock_search = Mock()
- mock_search.run.return_value = []
- mock_model = Mock()
- mock_model.invoke.return_value = Mock(content="Synthesized result")
-
- settings_snapshot = {
- "search.iterations": {"value": 1},
- "search.questions_per_iteration": {"value": 3},
- "general.knowledge_accumulation_context_limit": {"value": 5000},
- "general.knowledge_accumulation": {"value": "ITERATION"},
- }
-
- strategy = StandardSearchStrategy(
- search=mock_search,
- model=mock_model,
- settings_snapshot=settings_snapshot,
- )
-
- with patch.object(
- strategy.question_generator, "generate_questions", return_value=[]
- ) as mock_gen:
- with patch.object(
- strategy.knowledge_generator,
- "compress_knowledge",
- return_value="Compressed",
- ):
- strategy.analyze_topic("research query")
-
- # Should be called with correct parameters
- mock_gen.assert_called_once()
- call_kwargs = mock_gen.call_args[1]
- assert call_kwargs["query"] == "research query"
- assert call_kwargs["questions_per_iteration"] == 3
-
- def test_search_called_for_each_question(self):
- """Search is called for each generated question."""
- from local_deep_research.advanced_search_system.strategies.standard_strategy import (
- StandardSearchStrategy,
- )
-
- mock_search = Mock()
- mock_search.run.return_value = []
- mock_model = Mock()
- mock_model.invoke.return_value = Mock(content="Analysis result text")
-
- settings_snapshot = {
- "search.iterations": {"value": 1},
- "search.questions_per_iteration": {"value": 2},
- "general.knowledge_accumulation_context_limit": {"value": 5000},
- "general.knowledge_accumulation": {"value": "ITERATION"},
- }
-
- strategy = StandardSearchStrategy(
- search=mock_search,
- model=mock_model,
- settings_snapshot=settings_snapshot,
- )
-
- with patch.object(
- strategy.question_generator,
- "generate_questions",
- return_value=["Q1", "Q2"],
- ):
- with patch.object(
- strategy.knowledge_generator,
- "compress_knowledge",
- return_value="Compressed knowledge",
- ):
- strategy.analyze_topic("test query")
-
- # Search should be called for each question
- assert mock_search.run.call_count == 2
diff --git a/tests/advanced_search_system/strategies/test_strategy_helpers_pure_logic.py b/tests/advanced_search_system/strategies/test_strategy_helpers_pure_logic.py
deleted file mode 100644
index 2d3f518f1f..0000000000
--- a/tests/advanced_search_system/strategies/test_strategy_helpers_pure_logic.py
+++ /dev/null
@@ -1,597 +0,0 @@
-"""
-Tests for pure logic helper methods across strategy files.
-
-These methods have zero existing test coverage on their actual class
-implementations. Existing tests either test the regex pattern inline
-(not the full method) or test a different class's implementation.
-
-Tested methods:
-- EarlyStopConstrainedStrategy._extract_confidence_from_response()
-- EarlyStopConstrainedStrategy._evaluate_evidence()
-- SmartDecompositionStrategy._is_browsecomp_style()
-- ParallelConstrainedStrategy._generate_query_variations()
-"""
-
-from unittest.mock import Mock
-
-import pytest
-
-from local_deep_research.advanced_search_system.constraints.base_constraint import (
- Constraint,
- ConstraintType,
-)
-
-
-# ---------------------------------------------------------------------------
-# Helpers: construct strategy instances with mocked dependencies
-# ---------------------------------------------------------------------------
-
-
-def _make_early_stop_strategy():
- """Create an EarlyStopConstrainedStrategy with mocked model/search."""
- from local_deep_research.advanced_search_system.strategies.early_stop_constrained_strategy import (
- EarlyStopConstrainedStrategy,
- )
-
- model = Mock()
- search = Mock()
- return EarlyStopConstrainedStrategy(
- model=model, search=search, all_links_of_system=[]
- )
-
-
-def _make_smart_decomposition_strategy():
- """Create a SmartDecompositionStrategy with mocked model/search."""
- from local_deep_research.advanced_search_system.strategies.smart_decomposition_strategy import (
- SmartDecompositionStrategy,
- )
-
- model = Mock()
- search = Mock()
- return SmartDecompositionStrategy(
- model=model, search=search, all_links_of_system=[]
- )
-
-
-def _make_parallel_constrained_strategy():
- """Create a ParallelConstrainedStrategy with mocked model/search."""
- from local_deep_research.advanced_search_system.strategies.parallel_constrained_strategy import (
- ParallelConstrainedStrategy,
- )
-
- model = Mock()
- search = Mock()
- return ParallelConstrainedStrategy(
- model=model, search=search, all_links_of_system=[]
- )
-
-
-def _make_constraint(ctype=ConstraintType.PROPERTY, value="test constraint"):
- """Create a Constraint for testing."""
- return Constraint(id="c1", type=ctype, description="Test", value=value)
-
-
-# ---------------------------------------------------------------------------
-# _extract_confidence_from_response (early_stop_constrained_strategy.py)
-# ---------------------------------------------------------------------------
-
-
-class TestExtractConfidenceFromResponse:
- """Tests for EarlyStopConstrainedStrategy._extract_confidence_from_response().
-
- This method:
- 1. Uses regex to find decimal numbers between 0 and 1
- 2. Returns the LAST match found
- 3. Falls back to keyword-based confidence if no numeric match
- 4. Returns 0.5 as ultimate default
- """
-
- def test_extracts_simple_decimal(self):
- """Extracts a simple decimal confidence value."""
- strategy = _make_early_stop_strategy()
- assert (
- strategy._extract_confidence_from_response("confidence: 0.85")
- == 0.85
- )
-
- def test_extracts_last_number_when_multiple(self):
- """Returns the last number found, not the first."""
- strategy = _make_early_stop_strategy()
- result = strategy._extract_confidence_from_response(
- "Initial score 0.3, revised to 0.7"
- )
- assert result == 0.7
-
- def test_extracts_1_0(self):
- """Extracts 1.0 as perfect confidence."""
- strategy = _make_early_stop_strategy()
- assert strategy._extract_confidence_from_response("score: 1.0") == 1.0
-
- def test_extracts_integer_1(self):
- """Extracts integer 1 as confidence."""
- strategy = _make_early_stop_strategy()
- assert (
- strategy._extract_confidence_from_response("confidence: 1") == 1.0
- )
-
- def test_extracts_zero_decimal(self):
- """Extracts 0.0-like values (e.g. 0.1)."""
- strategy = _make_early_stop_strategy()
- assert (
- strategy._extract_confidence_from_response("very low: 0.1") == 0.1
- )
-
- def test_keyword_definitely_returns_0_9(self):
- """'definitely' keyword returns 0.9 confidence."""
- strategy = _make_early_stop_strategy()
- assert (
- strategy._extract_confidence_from_response(
- "This is definitely the answer"
- )
- == 0.9
- )
-
- def test_keyword_certainly_returns_0_9(self):
- """'certainly' keyword returns 0.9 confidence."""
- strategy = _make_early_stop_strategy()
- assert (
- strategy._extract_confidence_from_response(
- "This is certainly correct"
- )
- == 0.9
- )
-
- def test_keyword_absolutely_returns_0_9(self):
- """'absolutely' keyword returns 0.9 confidence."""
- strategy = _make_early_stop_strategy()
- assert (
- strategy._extract_confidence_from_response(
- "Absolutely the right match"
- )
- == 0.9
- )
-
- def test_keyword_likely_returns_0_7(self):
- """'likely' keyword returns 0.7 confidence."""
- strategy = _make_early_stop_strategy()
- assert (
- strategy._extract_confidence_from_response(
- "This is likely the answer"
- )
- == 0.7
- )
-
- def test_keyword_probably_returns_0_7(self):
- """'probably' keyword returns 0.7 confidence."""
- strategy = _make_early_stop_strategy()
- assert (
- strategy._extract_confidence_from_response(
- "This is probably correct"
- )
- == 0.7
- )
-
- def test_keyword_appears_returns_0_7(self):
- """'appears' keyword returns 0.7 confidence."""
- strategy = _make_early_stop_strategy()
- assert (
- strategy._extract_confidence_from_response("It appears to match")
- == 0.7
- )
-
- def test_keyword_possibly_returns_0_5(self):
- """'possibly' keyword returns 0.5 confidence."""
- strategy = _make_early_stop_strategy()
- assert (
- strategy._extract_confidence_from_response(
- "This is possibly the answer"
- )
- == 0.5
- )
-
- def test_keyword_maybe_returns_0_5(self):
- """'maybe' keyword returns 0.5 confidence."""
- strategy = _make_early_stop_strategy()
- assert (
- strategy._extract_confidence_from_response("Maybe this is correct")
- == 0.5
- )
-
- def test_keyword_might_returns_0_5(self):
- """'might' keyword returns 0.5 confidence."""
- strategy = _make_early_stop_strategy()
- assert (
- strategy._extract_confidence_from_response(
- "It might be the right one"
- )
- == 0.5
- )
-
- def test_keyword_unlikely_matches_likely_first(self):
- """'unlikely' contains 'likely' which matches the higher-priority tier."""
- strategy = _make_early_stop_strategy()
- # "unlikely" contains "likely", and the code checks "likely" tier first
- assert (
- strategy._extract_confidence_from_response(
- "This is unlikely the answer"
- )
- == 0.7
- )
-
- def test_keyword_doubtful_returns_0_3(self):
- """'doubtful' keyword returns 0.3 confidence."""
- strategy = _make_early_stop_strategy()
- assert (
- strategy._extract_confidence_from_response(
- "It is doubtful this matches"
- )
- == 0.3
- )
-
- def test_keyword_not_returns_0_3(self):
- """'not' keyword returns 0.3 confidence."""
- strategy = _make_early_stop_strategy()
- assert (
- strategy._extract_confidence_from_response(
- "This is not the correct answer"
- )
- == 0.3
- )
-
- def test_no_match_returns_default_0_5(self):
- """No numeric or keyword match returns default 0.5."""
- strategy = _make_early_stop_strategy()
- assert (
- strategy._extract_confidence_from_response("Indeterminate result")
- == 0.5
- )
-
- def test_empty_string_returns_default(self):
- """Empty string returns default 0.5."""
- strategy = _make_early_stop_strategy()
- assert strategy._extract_confidence_from_response("") == 0.5
-
- def test_numeric_takes_priority_over_keywords(self):
- """Numeric match takes priority over keyword match."""
- strategy = _make_early_stop_strategy()
- result = strategy._extract_confidence_from_response(
- "This is definitely the answer with confidence 0.6"
- )
- assert result == 0.6
-
- def test_keyword_case_insensitive(self):
- """Keyword matching is case-insensitive."""
- strategy = _make_early_stop_strategy()
- assert (
- strategy._extract_confidence_from_response("DEFINITELY the answer")
- == 0.9
- )
-
- def test_keyword_priority_high_over_low(self):
- """First matching keyword tier wins (definitely > unlikely)."""
- strategy = _make_early_stop_strategy()
- # "definitely" is checked before "not", so 0.9 should win
- result = strategy._extract_confidence_from_response(
- "This is definitely not wrong"
- )
- assert result == 0.9
-
-
-# ---------------------------------------------------------------------------
-# _evaluate_evidence (early_stop_constrained_strategy.py)
-# ---------------------------------------------------------------------------
-
-
-class TestEvaluateEvidence:
- """Tests for EarlyStopConstrainedStrategy._evaluate_evidence().
-
- This method averages confidence scores from evidence items.
- Empty evidence returns 0.0.
- """
-
- def test_empty_evidence_returns_zero(self):
- """Empty evidence list returns 0.0."""
- strategy = _make_early_stop_strategy()
- constraint = _make_constraint()
- assert strategy._evaluate_evidence([], constraint) == 0.0
-
- def test_single_evidence_item(self):
- """Single evidence item returns its confidence."""
- strategy = _make_early_stop_strategy()
- constraint = _make_constraint()
- evidence = [{"confidence": 0.8, "text": "evidence text"}]
- assert strategy._evaluate_evidence(
- evidence, constraint
- ) == pytest.approx(0.8)
-
- def test_multiple_evidence_averaged(self):
- """Multiple evidence items are averaged."""
- strategy = _make_early_stop_strategy()
- constraint = _make_constraint()
- evidence = [
- {"confidence": 0.6},
- {"confidence": 0.8},
- {"confidence": 1.0},
- ]
- # (0.6 + 0.8 + 1.0) / 3 = 0.8
- assert strategy._evaluate_evidence(
- evidence, constraint
- ) == pytest.approx(0.8)
-
- def test_missing_confidence_defaults_to_0_5(self):
- """Evidence items without 'confidence' key default to 0.5."""
- strategy = _make_early_stop_strategy()
- constraint = _make_constraint()
- evidence = [{"text": "no confidence key"}]
- assert strategy._evaluate_evidence(
- evidence, constraint
- ) == pytest.approx(0.5)
-
- def test_mixed_present_and_missing_confidence(self):
- """Averages mix of explicit and default confidence values."""
- strategy = _make_early_stop_strategy()
- constraint = _make_constraint()
- evidence = [
- {"confidence": 0.9},
- {"text": "no confidence"}, # defaults to 0.5
- ]
- # (0.9 + 0.5) / 2 = 0.7
- assert strategy._evaluate_evidence(
- evidence, constraint
- ) == pytest.approx(0.7)
-
- def test_all_zero_confidence(self):
- """All zero confidence returns 0.0."""
- strategy = _make_early_stop_strategy()
- constraint = _make_constraint()
- evidence = [{"confidence": 0.0}, {"confidence": 0.0}]
- assert strategy._evaluate_evidence(evidence, constraint) == 0.0
-
- def test_all_perfect_confidence(self):
- """All perfect confidence returns 1.0."""
- strategy = _make_early_stop_strategy()
- constraint = _make_constraint()
- evidence = [{"confidence": 1.0}, {"confidence": 1.0}]
- assert strategy._evaluate_evidence(
- evidence, constraint
- ) == pytest.approx(1.0)
-
- def test_ignores_constraint_details(self):
- """Result depends only on evidence, not constraint type."""
- strategy = _make_early_stop_strategy()
- constraint_a = _make_constraint(ctype=ConstraintType.PROPERTY)
- constraint_b = _make_constraint(ctype=ConstraintType.TEMPORAL)
- evidence = [{"confidence": 0.75}]
- assert strategy._evaluate_evidence(
- evidence, constraint_a
- ) == strategy._evaluate_evidence(evidence, constraint_b)
-
-
-# ---------------------------------------------------------------------------
-# _is_browsecomp_style (smart_decomposition_strategy.py)
-# ---------------------------------------------------------------------------
-
-
-class TestIsBrowsecompStyle:
- """Tests for SmartDecompositionStrategy._is_browsecomp_style().
-
- Returns True when 3+ BrowseComp indicator phrases are found in the query.
- The indicators include things like "specific scenic location", "body part",
- "fell from", "search and rescue", etc.
- """
-
- def test_no_indicators_returns_false(self):
- """Query with no indicators returns False."""
- strategy = _make_smart_decomposition_strategy()
- assert (
- strategy._is_browsecomp_style("What is machine learning?") is False
- )
-
- def test_one_indicator_returns_false(self):
- """Single indicator is not enough."""
- strategy = _make_smart_decomposition_strategy()
- assert (
- strategy._is_browsecomp_style("What is the name of the capital?")
- is False
- )
-
- def test_two_indicators_returns_false(self):
- """Two indicators is still below threshold."""
- strategy = _make_smart_decomposition_strategy()
- assert (
- strategy._is_browsecomp_style(
- "What is the name of a specific scenic location?"
- )
- is False
- )
-
- def test_three_indicators_returns_true(self):
- """Three indicators meets the threshold."""
- strategy = _make_smart_decomposition_strategy()
- # Indicators: "what is the name", "body part", "fell from"
- result = strategy._is_browsecomp_style(
- "What is the name of the trail where someone fell from a body part shaped rock?"
- )
- assert result is True
-
- def test_four_indicators_returns_true(self):
- """Four indicators clearly returns True."""
- strategy = _make_smart_decomposition_strategy()
- # Indicators: "what is the name", "search and rescue", "fell from", "viewpoint"
- result = strategy._is_browsecomp_style(
- "What is the name of the viewpoint where hikers fell from "
- "and required search and rescue?"
- )
- assert result is True
-
- def test_case_insensitive_matching(self):
- """Indicator matching is case-insensitive."""
- strategy = _make_smart_decomposition_strategy()
- # Indicators: "WHAT IS THE NAME", "BODY PART", "FELL FROM"
- result = strategy._is_browsecomp_style(
- "WHAT IS THE NAME OF THE PLACE WHERE SOMEONE FELL FROM A BODY PART CLIFF?"
- )
- assert result is True
-
- def test_many_indicators(self):
- """Query with many indicators returns True."""
- strategy = _make_smart_decomposition_strategy()
- query = (
- "What is the name of the specific scenic location with a viewpoint "
- "where someone fell from a cliff and SAR incidents were reported "
- "since the last ice age?"
- )
- # Indicators: "what is the name", "specific scenic location", "viewpoint",
- # "fell from", "SAR incidents", "last ice age"
- assert strategy._is_browsecomp_style(query) is True
-
- def test_partial_indicator_not_counted(self):
- """Partial indicator phrase doesn't count."""
- strategy = _make_smart_decomposition_strategy()
- # "scenic" alone is not "specific scenic location"
- # "search" alone is not "search and rescue"
- assert (
- strategy._is_browsecomp_style("scenic search between mountains")
- is False
- )
-
- def test_between_indicator(self):
- """'between' counts as an indicator."""
- strategy = _make_smart_decomposition_strategy()
- # Indicators: "between", "what is the name", "times more"
- result = strategy._is_browsecomp_style(
- "What is the name of something between two peaks that is times more popular?"
- )
- assert result is True
-
- def test_empty_query_returns_false(self):
- """Empty query returns False."""
- strategy = _make_smart_decomposition_strategy()
- assert strategy._is_browsecomp_style("") is False
-
- def test_exact_answer_indicator(self):
- """'exact answer' counts as an indicator."""
- strategy = _make_smart_decomposition_strategy()
- # Indicators: "exact answer", "multiple clues", "what is the name"
- result = strategy._is_browsecomp_style(
- "What is the name? I need the exact answer using multiple clues."
- )
- assert result is True
-
-
-# ---------------------------------------------------------------------------
-# _generate_query_variations (parallel_constrained_strategy.py)
-# ---------------------------------------------------------------------------
-
-
-class TestGenerateQueryVariations:
- """Tests for ParallelConstrainedStrategy._generate_query_variations().
-
- Generates search query variations based on constraint type:
- - STATISTIC: "list <base>", "complete <base>", "all <base>"
- - PROPERTY: "with <base>", "featuring <base>", "known for <base>"
- - Other types: just the base value
- Always limited to 3 variations max.
- """
-
- def test_statistic_constraint_variations(self):
- """STATISTIC constraint adds 'list', 'complete' prefixes (capped at 3)."""
- strategy = _make_parallel_constrained_strategy()
- constraint = _make_constraint(
- ctype=ConstraintType.STATISTIC, value="84.5x ratio"
- )
- variations = strategy._generate_query_variations(constraint)
- assert variations[0] == "84.5x ratio"
- assert "list 84.5x ratio" in variations
- assert "complete 84.5x ratio" in variations
- # "all 84.5x ratio" is the 4th item, cut by [:3] cap
- assert len(variations) == 3
-
- def test_property_constraint_variations(self):
- """PROPERTY constraint adds 'with', 'featuring' prefixes (capped at 3)."""
- strategy = _make_parallel_constrained_strategy()
- constraint = _make_constraint(
- ctype=ConstraintType.PROPERTY, value="formed during ice age"
- )
- variations = strategy._generate_query_variations(constraint)
- assert variations[0] == "formed during ice age"
- assert "with formed during ice age" in variations
- assert "featuring formed during ice age" in variations
- # "known for formed during ice age" is the 4th item, cut by [:3] cap
- assert len(variations) == 3
-
- def test_event_constraint_no_extra_variations(self):
- """EVENT constraint returns only the base value."""
- strategy = _make_parallel_constrained_strategy()
- constraint = _make_constraint(
- ctype=ConstraintType.EVENT, value="fall between 2000-2021"
- )
- variations = strategy._generate_query_variations(constraint)
- assert variations == ["fall between 2000-2021"]
-
- def test_temporal_constraint_no_extra_variations(self):
- """TEMPORAL constraint returns only the base value."""
- strategy = _make_parallel_constrained_strategy()
- constraint = _make_constraint(
- ctype=ConstraintType.TEMPORAL, value="in 2014"
- )
- variations = strategy._generate_query_variations(constraint)
- assert variations == ["in 2014"]
-
- def test_location_constraint_no_extra_variations(self):
- """LOCATION constraint returns only the base value."""
- strategy = _make_parallel_constrained_strategy()
- constraint = _make_constraint(
- ctype=ConstraintType.LOCATION, value="in Colorado"
- )
- variations = strategy._generate_query_variations(constraint)
- assert variations == ["in Colorado"]
-
- def test_max_three_variations(self):
- """Variations list is capped at 3."""
- strategy = _make_parallel_constrained_strategy()
- constraint = _make_constraint(
- ctype=ConstraintType.STATISTIC, value="test stat"
- )
- variations = strategy._generate_query_variations(constraint)
- # base + 3 type-specific = 4 total, but capped at 3
- assert len(variations) <= 3
-
- def test_base_value_always_first(self):
- """Base constraint value is always the first variation."""
- strategy = _make_parallel_constrained_strategy()
- for ctype in [
- ConstraintType.STATISTIC,
- ConstraintType.PROPERTY,
- ConstraintType.EVENT,
- ]:
- constraint = _make_constraint(ctype=ctype, value="base value")
- variations = strategy._generate_query_variations(constraint)
- assert variations[0] == "base value"
-
- def test_name_pattern_no_extra_variations(self):
- """NAME_PATTERN constraint returns only the base value."""
- strategy = _make_parallel_constrained_strategy()
- constraint = _make_constraint(
- ctype=ConstraintType.NAME_PATTERN, value="contains body part"
- )
- variations = strategy._generate_query_variations(constraint)
- assert variations == ["contains body part"]
-
- def test_statistic_returns_exactly_three(self):
- """STATISTIC type: base + 3 prefixed = 4, capped to 3."""
- strategy = _make_parallel_constrained_strategy()
- constraint = _make_constraint(
- ctype=ConstraintType.STATISTIC, value="stat"
- )
- variations = strategy._generate_query_variations(constraint)
- assert len(variations) == 3
-
- def test_property_returns_exactly_three(self):
- """PROPERTY type: base + 3 prefixed = 4, capped to 3."""
- strategy = _make_parallel_constrained_strategy()
- constraint = _make_constraint(
- ctype=ConstraintType.PROPERTY, value="prop"
- )
- variations = strategy._generate_query_variations(constraint)
- assert len(variations) == 3
diff --git a/tests/advanced_search_system/strategies/test_strategy_pure_logic.py b/tests/advanced_search_system/strategies/test_strategy_pure_logic.py
index 9f5a3e65eb..2805a3fbc7 100644
--- a/tests/advanced_search_system/strategies/test_strategy_pure_logic.py
+++ b/tests/advanced_search_system/strategies/test_strategy_pure_logic.py
@@ -5,8 +5,6 @@ These functions have zero existing test coverage despite being
testable without mocking LLMs or search engines:
- SourceBasedSearchStrategy._format_search_results_as_context()
-- AdaptiveDecompositionStrategy._calculate_confidence()
-- AdaptiveDecompositionStrategy StepType enum and StepResult dataclass
- NewsAggregationStrategy._format_news_summary()
- NewsAggregationStrategy._fallback_news_extraction()
- BaseSearchStrategy.check_termination()
@@ -14,192 +12,6 @@ testable without mocking LLMs or search engines:
from unittest.mock import Mock
-import pytest
-
-
-# ---------------------------------------------------------------------------
-# StepType and StepResult (adaptive_decomposition_strategy.py)
-# ---------------------------------------------------------------------------
-
-
-class TestStepType:
- """Tests for StepType enum values."""
-
- def test_all_step_types_exist(self):
- """All expected step types exist."""
- from local_deep_research.advanced_search_system.strategies.adaptive_decomposition_strategy import (
- StepType,
- )
-
- assert StepType.CONSTRAINT_EXTRACTION.value == "constraint_extraction"
- assert StepType.INITIAL_SEARCH.value == "initial_search"
- assert StepType.VERIFICATION.value == "verification"
- assert StepType.REFINEMENT.value == "refinement"
- assert StepType.SYNTHESIS.value == "synthesis"
-
- def test_step_type_count(self):
- """Exactly 5 step types defined."""
- from local_deep_research.advanced_search_system.strategies.adaptive_decomposition_strategy import (
- StepType,
- )
-
- assert len(StepType) == 5
-
- def test_step_type_comparison(self):
- """Step types support equality comparison."""
- from local_deep_research.advanced_search_system.strategies.adaptive_decomposition_strategy import (
- StepType,
- )
-
- assert StepType.VERIFICATION == StepType.VERIFICATION
- assert StepType.VERIFICATION != StepType.REFINEMENT
-
-
-class TestStepResult:
- """Tests for StepResult dataclass."""
-
- def test_create_with_required_fields(self):
- """Create StepResult with required fields."""
- from local_deep_research.advanced_search_system.strategies.adaptive_decomposition_strategy import (
- StepResult,
- StepType,
- )
-
- result = StepResult(
- step_type=StepType.INITIAL_SEARCH,
- description="Initial search",
- findings={"data": [1, 2, 3]},
- )
-
- assert result.step_type == StepType.INITIAL_SEARCH
- assert result.description == "Initial search"
- assert result.findings == {"data": [1, 2, 3]}
-
- def test_default_values(self):
- """Default values for optional fields."""
- from local_deep_research.advanced_search_system.strategies.adaptive_decomposition_strategy import (
- StepResult,
- StepType,
- )
-
- result = StepResult(
- step_type=StepType.SYNTHESIS,
- description="Synthesize",
- findings={},
- )
-
- assert result.next_action is None
- assert result.confidence == 0.0
-
- def test_create_with_all_fields(self):
- """Create StepResult with all fields."""
- from local_deep_research.advanced_search_system.strategies.adaptive_decomposition_strategy import (
- StepResult,
- StepType,
- )
-
- result = StepResult(
- step_type=StepType.VERIFICATION,
- description="Verify facts",
- findings={"verified": True},
- next_action="refine",
- confidence=0.85,
- )
-
- assert result.next_action == "refine"
- assert result.confidence == 0.85
-
-
-# ---------------------------------------------------------------------------
-# _calculate_confidence (adaptive_decomposition_strategy.py)
-# ---------------------------------------------------------------------------
-
-
-class TestCalculateConfidence:
- """Tests for AdaptiveDecompositionStrategy._calculate_confidence()."""
-
- def _make_strategy(self, constraints, verified_facts, candidates=None):
- """Create a strategy with specific working_knowledge state."""
- from local_deep_research.advanced_search_system.strategies.adaptive_decomposition_strategy import (
- AdaptiveDecompositionStrategy,
- )
-
- model = Mock()
- search = Mock()
- strategy = AdaptiveDecompositionStrategy(
- model=model, search=search, all_links_of_system=[]
- )
- strategy.working_knowledge = {
- "original_query": "test",
- "constraints": constraints,
- "candidates": candidates or [],
- "verified_facts": verified_facts,
- "uncertainties": [],
- }
- return strategy
-
- def test_no_constraints_returns_zero(self):
- """Zero constraints returns 0.0 confidence."""
- strategy = self._make_strategy(constraints=[], verified_facts=["fact1"])
- assert strategy._calculate_confidence() == 0.0
-
- def test_all_constraints_verified(self):
- """All constraints verified gives high confidence."""
- strategy = self._make_strategy(
- constraints=["c1", "c2"],
- verified_facts=["f1", "f2"],
- )
- confidence = strategy._calculate_confidence()
- assert confidence == pytest.approx(0.95) # Capped at 0.95
-
- def test_half_constraints_verified(self):
- """Half constraints verified gives 0.5."""
- strategy = self._make_strategy(
- constraints=["c1", "c2"],
- verified_facts=["f1"],
- )
- confidence = strategy._calculate_confidence()
- assert confidence == pytest.approx(0.5)
-
- def test_candidates_boost(self):
- """Having candidates adds 0.1 to confidence."""
- strategy = self._make_strategy(
- constraints=["c1", "c2"],
- verified_facts=["f1"],
- candidates=["candidate_a"],
- )
- confidence = strategy._calculate_confidence()
- assert confidence == pytest.approx(0.6) # 0.5 + 0.1
-
- def test_confidence_capped_at_095(self):
- """Confidence capped at 0.95 even with candidates boost."""
- strategy = self._make_strategy(
- constraints=["c1"],
- verified_facts=["f1"],
- candidates=["c_a"],
- )
- confidence = strategy._calculate_confidence()
- # 1.0 + 0.1 = 1.1, capped to 0.95
- assert confidence == pytest.approx(0.95)
-
- def test_no_verified_facts(self):
- """No verified facts gives 0.0 confidence."""
- strategy = self._make_strategy(
- constraints=["c1", "c2", "c3"],
- verified_facts=[],
- )
- assert strategy._calculate_confidence() == pytest.approx(0.0)
-
- def test_more_verified_than_constraints(self):
- """More verified facts than constraints still capped at 0.95."""
- strategy = self._make_strategy(
- constraints=["c1"],
- verified_facts=["f1", "f2", "f3"],
- )
- confidence = strategy._calculate_confidence()
- # 3/1 = 3.0, capped to 0.95
- assert confidence == pytest.approx(0.95)
-
# ---------------------------------------------------------------------------
# _format_search_results_as_context (source_based_strategy.py)
diff --git a/tests/advanced_search_system/strategies/test_wrapper_citation_handler_property.py b/tests/advanced_search_system/strategies/test_wrapper_citation_handler_property.py
deleted file mode 100644
index fee4c9a2a4..0000000000
--- a/tests/advanced_search_system/strategies/test_wrapper_citation_handler_property.py
+++ /dev/null
@@ -1,110 +0,0 @@
-"""Tests for the citation_handler property on strategy wrappers.
-
-Both ``EnhancedContextualFollowUpStrategy`` and
-``IterativeRefinementStrategy`` wrap another strategy as a delegate but
-don't own a citation handler of their own. Chat-mode streaming hookup at
-``research_service.py`` reaches the handler via
-``strategy.citation_handler.set_stream_callback(...)``. Without the
-property forwarding to the delegate, the streaming attachment is silently
-skipped for follow-up research and the chat UI receives no LLM chunks.
-
-These tests use the same ``__new__()`` + ``patch.object(__init__, ...)``
-pattern as ``test_enhanced_followup_high_value.py`` to avoid paying
-the wrapper's heavy ``__init__`` cost (which instantiates the relevance
-filter, context manager, and question generator with the LLM).
-"""
-
-from unittest.mock import MagicMock, patch
-
-from local_deep_research.advanced_search_system.strategies.followup.enhanced_contextual_followup import (
- EnhancedContextualFollowUpStrategy,
-)
-from local_deep_research.advanced_search_system.strategies.iterative_refinement_strategy import (
- IterativeRefinementStrategy,
-)
-
-
-def _make_followup_wrapper(delegate):
- """Build an EnhancedContextualFollowUpStrategy with __init__ bypassed."""
- with patch.object(
- EnhancedContextualFollowUpStrategy,
- "__init__",
- lambda self, *a, **kw: None,
- ):
- wrapper = EnhancedContextualFollowUpStrategy.__new__(
- EnhancedContextualFollowUpStrategy
- )
- wrapper.delegate_strategy = delegate
- return wrapper
-
-
-def _make_iterative_wrapper(initial):
- """Build an IterativeRefinementStrategy with __init__ bypassed."""
- with patch.object(
- IterativeRefinementStrategy,
- "__init__",
- lambda self, *a, **kw: None,
- ):
- wrapper = IterativeRefinementStrategy.__new__(
- IterativeRefinementStrategy
- )
- wrapper.initial_strategy = initial
- return wrapper
-
-
-def test_followup_wrapper_exposes_delegate_citation_handler():
- """``wrapper.citation_handler`` is the delegate's citation_handler."""
- sentinel = MagicMock(name="real_citation_handler")
- delegate = MagicMock()
- delegate.citation_handler = sentinel
-
- wrapper = _make_followup_wrapper(delegate)
-
- # The property returns the delegate's handler — the streaming hookup
- # at research_service.py can now reach it via the wrapper.
- assert wrapper.citation_handler is sentinel
-
- # And calls land on the real handler.
- cb = MagicMock()
- wrapper.citation_handler.set_stream_callback(cb)
- sentinel.set_stream_callback.assert_called_once_with(cb)
-
-
-def test_iterative_refinement_exposes_initial_citation_handler():
- """Same forwarding behavior for the iterative-refinement wrapper."""
- sentinel = MagicMock(name="real_citation_handler")
- initial = MagicMock()
- initial.citation_handler = sentinel
-
- wrapper = _make_iterative_wrapper(initial)
-
- assert wrapper.citation_handler is sentinel
-
- cb = MagicMock()
- wrapper.citation_handler.set_stream_callback(cb)
- sentinel.set_stream_callback.assert_called_once_with(cb)
-
-
-def test_property_returns_none_when_wrapped_strategy_is_none():
- """Defensive: partial construction yields ``None`` so the call-site
- ``hasattr`` check at ``research_service.py`` short-circuits."""
- followup = _make_followup_wrapper(None)
- iterative = _make_iterative_wrapper(None)
-
- assert followup.citation_handler is None
- assert iterative.citation_handler is None
-
-
-def test_property_returns_none_when_delegate_lacks_citation_handler():
- """Defensive: a delegate that never set ``citation_handler`` should
- yield ``None`` from the property (not AttributeError)."""
-
- # A bare object with no attribute named "citation_handler".
- class _Bare:
- pass
-
- followup = _make_followup_wrapper(_Bare())
- iterative = _make_iterative_wrapper(_Bare())
-
- assert followup.citation_handler is None
- assert iterative.citation_handler is None
diff --git a/tests/advanced_search_system/test_base_class_coverage.py b/tests/advanced_search_system/test_base_class_coverage.py
index 4d802785c7..f59630aeef 100644
--- a/tests/advanced_search_system/test_base_class_coverage.py
+++ b/tests/advanced_search_system/test_base_class_coverage.py
@@ -7,16 +7,6 @@ implements abstract methods as no-ops, then exercises the concrete helper method
from unittest.mock import Mock
-from local_deep_research.advanced_search_system.candidates.base_candidate import (
- Candidate,
-)
-from local_deep_research.advanced_search_system.constraint_checking.base_constraint_checker import (
- BaseConstraintChecker,
-)
-from local_deep_research.advanced_search_system.constraints.base_constraint import (
- Constraint,
- ConstraintType,
-)
from local_deep_research.advanced_search_system.findings.base_findings import (
BaseFindingsRepository,
)
@@ -57,14 +47,6 @@ class ConcreteKnowledgeGenerator(BaseKnowledgeGenerator):
return ""
-class ConcreteConstraintChecker(BaseConstraintChecker):
- def check_candidate(self, candidate, constraints):
- return None
-
- def should_reject_candidate(self, candidate, constraint, evidence_data):
- return (False, "")
-
-
class ConcreteQuestionGenerator(BaseQuestionGenerator):
def generate_questions(
self,
@@ -143,80 +125,6 @@ class TestBaseKnowledgeGenerator:
assert result == ["single"]
-class TestBaseConstraintChecker:
- def _make_candidate(self, name="TestCandidate"):
- return Candidate(name=name)
-
- def _make_constraint(self, value="must be blue", weight=1.0):
- return Constraint(
- id="c1",
- type=ConstraintType.PROPERTY,
- description="test",
- value=value,
- weight=weight,
- )
-
- def test_gather_evidence_with_gatherer(self):
- gatherer = Mock(return_value=[{"text": "evidence"}])
- checker = ConcreteConstraintChecker(
- model=Mock(), evidence_gatherer=gatherer
- )
- candidate = self._make_candidate()
- constraint = self._make_constraint()
-
- result = checker._gather_evidence_for_constraint(candidate, constraint)
-
- gatherer.assert_called_once_with(candidate, constraint)
- assert result == [{"text": "evidence"}]
-
- def test_gather_evidence_without_gatherer(self):
- checker = ConcreteConstraintChecker(
- model=Mock(), evidence_gatherer=None
- )
- result = checker._gather_evidence_for_constraint(
- self._make_candidate(), self._make_constraint()
- )
- assert result == []
-
- def test_log_constraint_result_high_score(self):
- checker = ConcreteConstraintChecker(model=Mock())
- checker._log_constraint_result(
- self._make_candidate(), self._make_constraint(), 0.9, {}
- )
-
- def test_log_constraint_result_medium_score(self):
- checker = ConcreteConstraintChecker(model=Mock())
- checker._log_constraint_result(
- self._make_candidate(), self._make_constraint(), 0.6, {}
- )
-
- def test_log_constraint_result_low_score(self):
- checker = ConcreteConstraintChecker(model=Mock())
- checker._log_constraint_result(
- self._make_candidate(), self._make_constraint(), 0.3, {}
- )
-
- def test_calculate_weighted_score(self):
- checker = ConcreteConstraintChecker(model=Mock())
- scores = [0.8, 0.6]
- weights = [2.0, 1.0]
- result = checker._calculate_weighted_score(scores, weights)
- expected = (0.8 * 2.0 + 0.6 * 1.0) / (2.0 + 1.0)
- assert abs(result - expected) < 1e-9
-
- def test_calculate_weighted_score_empty(self):
- checker = ConcreteConstraintChecker(model=Mock())
- assert checker._calculate_weighted_score([], []) == 0.0
-
- def test_calculate_weighted_score_empty_scores(self):
- checker = ConcreteConstraintChecker(model=Mock())
- assert checker._calculate_weighted_score([], [1.0]) == 0.0
-
- def test_calculate_weighted_score_empty_weights(self):
- checker = ConcreteConstraintChecker(model=Mock())
- assert checker._calculate_weighted_score([0.5], []) == 0.0
-
-
class TestBaseQuestionGenerator:
def setup_method(self):
self.gen = ConcreteQuestionGenerator(model=Mock())
diff --git a/tests/advanced_search_system/test_constraint_checking.py b/tests/advanced_search_system/test_constraint_checking.py
deleted file mode 100644
index af32c9aa84..0000000000
--- a/tests/advanced_search_system/test_constraint_checking.py
+++ /dev/null
@@ -1,302 +0,0 @@
-"""
-Tests for constraint checking system.
-
-Tests cover:
-- ConstraintChecker initialization and behavior
-- RejectionEngine rejection logic
-- EvidenceAnalyzer score extraction
-"""
-
-from unittest.mock import Mock
-
-
-class TestConstraintChecker:
- """Tests for the ConstraintChecker class."""
-
- def test_constraint_checker_initialization(self):
- """Verify ConstraintChecker initializes correctly with all parameters."""
- from local_deep_research.advanced_search_system.constraint_checking.constraint_checker import (
- ConstraintChecker,
- )
-
- mock_model = Mock()
- mock_evidence_gatherer = Mock()
-
- checker = ConstraintChecker(
- model=mock_model,
- evidence_gatherer=mock_evidence_gatherer,
- negative_threshold=0.3,
- positive_threshold=0.5,
- uncertainty_penalty=0.15,
- negative_weight=0.6,
- )
-
- assert checker.model == mock_model
- assert checker.evidence_gatherer == mock_evidence_gatherer
- assert checker.rejection_engine.negative_threshold == 0.3
- assert checker.rejection_engine.positive_threshold == 0.5
- assert checker.uncertainty_penalty == 0.15
- assert checker.negative_weight == 0.6
-
- def test_constraint_checker_no_evidence_gatherer(self):
- """Test that check_candidate works when evidence_gatherer is None."""
- from local_deep_research.advanced_search_system.constraint_checking.constraint_checker import (
- ConstraintChecker,
- )
- from local_deep_research.advanced_search_system.candidates.base_candidate import (
- Candidate,
- )
- from local_deep_research.advanced_search_system.constraints.base_constraint import (
- Constraint,
- ConstraintType,
- )
-
- mock_model = Mock()
-
- checker = ConstraintChecker(
- model=mock_model,
- evidence_gatherer=None,
- )
-
- candidate = Candidate(name="Test Candidate")
- constraint = Constraint(
- id="c1",
- type=ConstraintType.PROPERTY,
- description="Test constraint",
- value="test constraint",
- weight=1.0,
- )
-
- result = checker.check_candidate(candidate, [constraint])
-
- # Without evidence gatherer, no evidence is found
- assert result.candidate == candidate
- assert len(result.detailed_results) == 1
- assert result.detailed_results[0]["uncertainty"] == 1.0
-
- def test_check_candidate_with_mock_evidence(self):
- """Check candidate against constraints with mocked evidence.
-
- Note: This test verifies the checker correctly processes evidence
- through the EvidenceAnalyzer when an evidence gatherer is provided.
- The actual check_candidate method uses constraints as dict keys, which
- requires hashable constraints. Since Constraint is a dataclass without
- frozen=True, we use a mock that returns constraint IDs.
- """
- from local_deep_research.advanced_search_system.constraint_checking.evidence_analyzer import (
- ConstraintEvidence,
- EvidenceAnalyzer,
- )
-
- mock_model = Mock()
- mock_model.invoke.return_value = Mock(
- content="POSITIVE: 0.7\nNEGATIVE: 0.1\nUNCERTAINTY: 0.2"
- )
-
- # Test EvidenceAnalyzer directly instead of full checker
- analyzer = EvidenceAnalyzer(mock_model)
-
- # Create a mock constraint that can be used with the analyzer
- mock_constraint = Mock()
- mock_constraint.value = "test constraint"
- mock_constraint.id = "c1"
-
- evidence = {"text": "Test evidence", "source": "test"}
- result = analyzer.analyze_evidence_dual_confidence(
- evidence, mock_constraint
- )
-
- # Verify the evidence was analyzed
- assert isinstance(result, ConstraintEvidence)
- assert result.evidence_text == "Test evidence"
- assert result.source == "test"
- # Scores should be parsed from the mock response
- assert result.positive_confidence > 0
-
-
-class TestRejectionEngine:
- """Tests for the RejectionEngine class."""
-
- def test_rejection_engine_high_negative_evidence(self):
- """Test rejection when avg_negative > threshold."""
- from local_deep_research.advanced_search_system.constraint_checking.rejection_engine import (
- RejectionEngine,
- )
- from local_deep_research.advanced_search_system.constraint_checking.evidence_analyzer import (
- ConstraintEvidence,
- )
- from local_deep_research.advanced_search_system.candidates.base_candidate import (
- Candidate,
- )
- from local_deep_research.advanced_search_system.constraints.base_constraint import (
- Constraint,
- ConstraintType,
- )
-
- engine = RejectionEngine(
- negative_threshold=0.25, positive_threshold=0.4
- )
-
- candidate = Candidate(name="Test")
- constraint = Constraint(
- id="c1",
- type=ConstraintType.PROPERTY,
- description="Test constraint",
- value="test",
- weight=1.0,
- )
-
- # High negative evidence
- evidence_list = [
- ConstraintEvidence(
- positive_confidence=0.2,
- negative_confidence=0.6,
- uncertainty=0.2,
- evidence_text="test",
- source="test",
- )
- ]
-
- result = engine.should_reject_candidate(
- candidate, constraint, evidence_list
- )
-
- assert result.should_reject is True
- assert "negative evidence" in result.reason.lower()
-
- def test_rejection_engine_low_positive_evidence(self):
- """Test rejection when avg_positive < threshold."""
- from local_deep_research.advanced_search_system.constraint_checking.rejection_engine import (
- RejectionEngine,
- )
- from local_deep_research.advanced_search_system.constraint_checking.evidence_analyzer import (
- ConstraintEvidence,
- )
- from local_deep_research.advanced_search_system.candidates.base_candidate import (
- Candidate,
- )
- from local_deep_research.advanced_search_system.constraints.base_constraint import (
- Constraint,
- ConstraintType,
- )
-
- engine = RejectionEngine(
- negative_threshold=0.25, positive_threshold=0.4
- )
-
- candidate = Candidate(name="Test")
- constraint = Constraint(
- id="c1",
- type=ConstraintType.PROPERTY,
- description="Test constraint",
- value="test",
- weight=1.0,
- )
-
- # Low positive evidence (but not high negative)
- evidence_list = [
- ConstraintEvidence(
- positive_confidence=0.2,
- negative_confidence=0.1,
- uncertainty=0.7,
- evidence_text="test",
- source="test",
- )
- ]
-
- result = engine.should_reject_candidate(
- candidate, constraint, evidence_list
- )
-
- assert result.should_reject is True
- assert "insufficient positive" in result.reason.lower()
-
- def test_rejection_engine_no_evidence(self):
- """Test that no evidence returns should_reject=False."""
- from local_deep_research.advanced_search_system.constraint_checking.rejection_engine import (
- RejectionEngine,
- )
- from local_deep_research.advanced_search_system.candidates.base_candidate import (
- Candidate,
- )
- from local_deep_research.advanced_search_system.constraints.base_constraint import (
- Constraint,
- ConstraintType,
- )
-
- engine = RejectionEngine(
- negative_threshold=0.25, positive_threshold=0.4
- )
-
- candidate = Candidate(name="Test")
- constraint = Constraint(
- id="c1",
- type=ConstraintType.PROPERTY,
- description="Test constraint",
- value="test",
- weight=1.0,
- )
-
- result = engine.should_reject_candidate(candidate, constraint, [])
-
- assert result.should_reject is False
- assert "no evidence" in result.reason.lower()
-
-
-class TestEvidenceAnalyzer:
- """Tests for the EvidenceAnalyzer class."""
-
- def test_evidence_analyzer_extract_score(self):
- """Test _extract_score regex parsing."""
- from local_deep_research.advanced_search_system.constraint_checking.evidence_analyzer import (
- EvidenceAnalyzer,
- )
-
- mock_model = Mock()
- analyzer = EvidenceAnalyzer(mock_model)
-
- # Test various formats
- assert analyzer._extract_score("POSITIVE: 0.75", "POSITIVE") == 0.75
- assert analyzer._extract_score("POSITIVE: [0.8]", "POSITIVE") == 0.8
- assert analyzer._extract_score("positive: 0.5", "POSITIVE") == 0.5
- assert analyzer._extract_score("NEGATIVE: 0.25", "NEGATIVE") == 0.25
-
- # Test when not found - should return default
- assert analyzer._extract_score("no match here", "POSITIVE") == 0.1
-
- def test_evidence_analyzer_normalize_scores(self):
- """Test score normalization edge cases."""
- from local_deep_research.advanced_search_system.constraint_checking.evidence_analyzer import (
- EvidenceAnalyzer,
- )
- from local_deep_research.advanced_search_system.constraints.base_constraint import (
- Constraint,
- ConstraintType,
- )
-
- mock_model = Mock()
- # Return scores that sum to more than 1
- mock_model.invoke.return_value = Mock(
- content="POSITIVE: 0.5\nNEGATIVE: 0.5\nUNCERTAINTY: 0.5"
- )
-
- analyzer = EvidenceAnalyzer(mock_model)
-
- constraint = Constraint(
- id="c1",
- type=ConstraintType.PROPERTY,
- description="Test constraint",
- value="test",
- weight=1.0,
- )
-
- evidence = {"text": "test evidence", "source": "test"}
- result = analyzer.analyze_evidence_dual_confidence(evidence, constraint)
-
- # Scores should be normalized to sum to ~1.0
- total = (
- result.positive_confidence
- + result.negative_confidence
- + result.uncertainty
- )
- assert abs(total - 1.0) < 0.01
diff --git a/tests/advanced_search_system/test_constraints/__init__.py b/tests/advanced_search_system/test_constraints/__init__.py
deleted file mode 100644
index e69de29bb2..0000000000
diff --git a/tests/advanced_search_system/test_constraints/test_constraint_classes.py b/tests/advanced_search_system/test_constraints/test_constraint_classes.py
deleted file mode 100644
index cef9f1d98a..0000000000
--- a/tests/advanced_search_system/test_constraints/test_constraint_classes.py
+++ /dev/null
@@ -1,241 +0,0 @@
-"""
-Test constraint and constraint checking classes.
-"""
-
-from loguru import logger
-
-# Import all modules at the top level - these are verified to work
-from local_deep_research.advanced_search_system.constraints.base_constraint import (
- Constraint,
- ConstraintType,
-)
-from local_deep_research.advanced_search_system.constraints.constraint_analyzer import (
- ConstraintAnalyzer,
-)
-from local_deep_research.advanced_search_system.constraint_checking.base_constraint_checker import (
- BaseConstraintChecker,
-)
-from local_deep_research.advanced_search_system.constraint_checking.constraint_checker import (
- ConstraintChecker,
-)
-from local_deep_research.advanced_search_system.constraint_checking.dual_confidence_checker import (
- DualConfidenceChecker,
-)
-from local_deep_research.advanced_search_system.constraint_checking.strict_checker import (
- StrictChecker,
-)
-from local_deep_research.advanced_search_system.constraint_checking.threshold_checker import (
- ThresholdChecker,
-)
-from local_deep_research.advanced_search_system.constraint_checking.rejection_engine import (
- RejectionEngine,
-)
-from local_deep_research.advanced_search_system.constraint_checking.evidence_analyzer import (
- EvidenceAnalyzer,
-)
-from local_deep_research.advanced_search_system.candidates.base_candidate import (
- Candidate,
-)
-
-
-class TestConstraintImports:
- """Test that constraint-related classes can be imported."""
-
- def test_base_constraint_import(self):
- """Test base constraint classes import."""
- assert Constraint is not None
- assert ConstraintType is not None
- logger.info("Base constraint classes imported successfully")
-
- def test_constraint_analyzer_import(self):
- """Test ConstraintAnalyzer import."""
- assert ConstraintAnalyzer is not None
-
-
-class TestConstraintCheckingImports:
- """Test constraint checking module imports."""
-
- def test_base_constraint_checker_import(self):
- """Test base constraint checker import."""
- assert BaseConstraintChecker is not None
-
- def test_constraint_checker_import(self):
- """Test ConstraintChecker import."""
- assert ConstraintChecker is not None
-
- def test_dual_confidence_checker_import(self):
- """Test DualConfidenceChecker import."""
- assert DualConfidenceChecker is not None
-
- def test_strict_checker_import(self):
- """Test StrictChecker import."""
- assert StrictChecker is not None
-
- def test_threshold_checker_import(self):
- """Test ThresholdChecker import."""
- assert ThresholdChecker is not None
-
- def test_rejection_engine_import(self):
- """Test RejectionEngine import."""
- assert RejectionEngine is not None
-
- def test_evidence_analyzer_import(self):
- """Test EvidenceAnalyzer import."""
- assert EvidenceAnalyzer is not None
-
-
-class TestConstraintAnalyzer:
- """Test ConstraintAnalyzer functionality."""
-
- def test_instantiation(self, mock_llm):
- """Test that analyzer can be instantiated."""
- analyzer = ConstraintAnalyzer(mock_llm)
- assert analyzer is not None
- logger.info("ConstraintAnalyzer instantiated successfully")
-
-
-class TestConstraintChecker:
- """Test ConstraintChecker functionality."""
-
- def test_instantiation(self, mock_llm):
- """Test that checker can be instantiated."""
- checker = ConstraintChecker(mock_llm)
- assert checker is not None
- logger.info("ConstraintChecker instantiated successfully")
-
-
-class TestDualConfidenceChecker:
- """Test DualConfidenceChecker functionality."""
-
- def test_instantiation(self, mock_llm):
- """Test that checker can be instantiated."""
- checker = DualConfidenceChecker(mock_llm)
- assert checker is not None
- logger.info("DualConfidenceChecker instantiated successfully")
-
-
-class TestConstraintCheckerFunctionality:
- """Test ConstraintChecker with actual functionality."""
-
- def test_constraint_checker_with_custom_thresholds(self, mock_llm):
- """Test ConstraintChecker with custom thresholds."""
- checker = ConstraintChecker(
- model=mock_llm,
- negative_threshold=0.3,
- positive_threshold=0.5,
- uncertainty_penalty=0.15,
- negative_weight=0.6,
- )
-
- assert checker.rejection_engine is not None
- assert checker.evidence_analyzer is not None
- logger.info("ConstraintChecker with custom thresholds created")
-
- def test_constraint_checker_without_evidence_gatherer(self, mock_llm):
- """Test checker behavior without evidence gatherer."""
- checker = ConstraintChecker(model=mock_llm)
-
- # Create test candidate and constraint
- candidate = Candidate(name="Test Candidate")
- constraint = Constraint(
- id="recency_constraint",
- type=ConstraintType.TEMPORAL,
- description="Must be recent",
- value="recent",
- weight=1.0,
- )
-
- # Should handle gracefully without evidence gatherer
- result = checker.check_candidate(candidate, [constraint])
-
- assert result is not None
- assert result.candidate == candidate
- logger.info(f"Checker returned score: {result.total_score}")
-
-
-class TestEvidenceAnalyzer:
- """Test EvidenceAnalyzer functionality."""
-
- def test_instantiation(self, mock_llm):
- """Test that analyzer can be instantiated."""
- analyzer = EvidenceAnalyzer(mock_llm)
- assert analyzer is not None
- assert analyzer.model == mock_llm
- logger.info("EvidenceAnalyzer instantiated successfully")
-
-
-class TestRejectionEngine:
- """Test RejectionEngine functionality."""
-
- def test_instantiation_default_thresholds(self):
- """Test RejectionEngine with default thresholds."""
- engine = RejectionEngine()
- assert engine is not None
- logger.info("RejectionEngine instantiated with defaults")
-
- def test_instantiation_custom_thresholds(self):
- """Test RejectionEngine with custom thresholds."""
- engine = RejectionEngine(
- negative_threshold=0.3,
- positive_threshold=0.5,
- )
-
- assert engine.negative_threshold == 0.3
- assert engine.positive_threshold == 0.5
- logger.info("RejectionEngine with custom thresholds created")
-
-
-class TestConstraintDataClasses:
- """Test constraint-related data classes."""
-
- def test_constraint_creation(self):
- """Test Constraint dataclass creation."""
- constraint = Constraint(
- id="test_constraint",
- type=ConstraintType.TEMPORAL,
- description="Must be from 2023",
- value="2023",
- weight=1.5,
- )
-
- assert constraint.value == "2023"
- assert constraint.type == ConstraintType.TEMPORAL
- assert constraint.weight == 1.5
- assert constraint.id == "test_constraint"
- assert constraint.description == "Must be from 2023"
- logger.info("Constraint created successfully")
-
- def test_constraint_types(self):
- """Test all ConstraintType enum values exist."""
- # Check common constraint types exist
- assert hasattr(ConstraintType, "TEMPORAL")
- assert hasattr(ConstraintType, "LOCATION")
-
- # Get all types
- all_types = list(ConstraintType)
- logger.info(
- f"ConstraintType has {len(all_types)} types: {[t.value for t in all_types]}"
- )
-
-
-class TestCandidateClass:
- """Test Candidate class."""
-
- def test_candidate_creation(self):
- """Test Candidate class creation."""
- candidate = Candidate(name="Test Entity")
- assert candidate.name == "Test Entity"
- logger.info("Candidate created successfully")
-
- def test_candidate_with_additional_fields(self):
- """Test Candidate with additional fields if supported."""
- # Try to create with additional fields
- candidate = Candidate(
- name="Test Entity",
- )
-
- assert candidate.name == "Test Entity"
-
- # Check what attributes are available
- attrs = [a for a in dir(candidate) if not a.startswith("_")]
- logger.info(f"Candidate attributes: {attrs}")
diff --git a/tests/benchmarks/optimization/test_optuna_optimizer_branches_coverage.py b/tests/benchmarks/optimization/test_optuna_optimizer_branches_coverage.py
index e67b2c2f68..8779297e60 100644
--- a/tests/benchmarks/optimization/test_optuna_optimizer_branches_coverage.py
+++ b/tests/benchmarks/optimization/test_optuna_optimizer_branches_coverage.py
@@ -69,7 +69,7 @@ class TestGetDefaultParamSpace:
choices = space["search_strategy"]["choices"]
assert isinstance(choices, list)
assert len(choices) > 0
- assert "iterdrag" in choices
+ assert "source-based" in choices
@patch(f"{MODULE}.CompositeBenchmarkEvaluator")
def test_get_default_param_space_max_results_step(self, mock_evaluator):
diff --git a/tests/benchmarks/optimization/test_optuna_optimizer_extra_coverage.py b/tests/benchmarks/optimization/test_optuna_optimizer_extra_coverage.py
index 86bc0631e4..ba4da2eba1 100644
--- a/tests/benchmarks/optimization/test_optuna_optimizer_extra_coverage.py
+++ b/tests/benchmarks/optimization/test_optuna_optimizer_extra_coverage.py
@@ -59,8 +59,8 @@ class TestGetDefaultParamSpace:
optimizer = _make_optimizer()
space = optimizer._get_default_param_space()
assert space["search_strategy"]["type"] == "categorical"
- assert "iterdrag" in space["search_strategy"]["choices"]
- assert "source_based" in space["search_strategy"]["choices"]
+ assert "source-based" in space["search_strategy"]["choices"]
+ assert "focused-iteration" in space["search_strategy"]["choices"]
# ---------------------------------------------------------------------------
diff --git a/tests/benchmarks/test_optimization_api.py b/tests/benchmarks/test_optimization_api.py
index 8083503c3b..b671f7b189 100644
--- a/tests/benchmarks/test_optimization_api.py
+++ b/tests/benchmarks/test_optimization_api.py
@@ -145,8 +145,8 @@ class TestOptimizeForSpeed:
param_space = mock_optimizer.optimize.call_args[0][0]
strategies = param_space["search_strategy"]["choices"]
# Should include fast strategies
- assert "rapid" in strategies
- assert "parallel" in strategies
+ assert "source-based" in strategies
+ assert "focused-iteration" in strategies
class TestOptimizeForQuality:
diff --git a/tests/benchmarks/test_optuna_optimizer.py b/tests/benchmarks/test_optuna_optimizer.py
index c0436e17b1..5dce9af043 100644
--- a/tests/benchmarks/test_optuna_optimizer.py
+++ b/tests/benchmarks/test_optuna_optimizer.py
@@ -215,7 +215,7 @@ class TestDefaultParamSpace:
strategy = param_space["search_strategy"]
assert strategy["type"] == "categorical"
assert "choices" in strategy
- assert "iterdrag" in strategy["choices"]
+ assert "source-based" in strategy["choices"]
class TestConvenienceFunctions:
diff --git a/tests/benchmarks/test_optuna_optimizer_high_value.py b/tests/benchmarks/test_optuna_optimizer_high_value.py
index 764fa29793..a11f1762d0 100644
--- a/tests/benchmarks/test_optuna_optimizer_high_value.py
+++ b/tests/benchmarks/test_optuna_optimizer_high_value.py
@@ -836,4 +836,4 @@ class TestConvenienceFunctionForwarding:
optimize_call = mock_instance.optimize.call_args
param_space = optimize_call[1].get("param_space") or optimize_call[0][0]
assert param_space["iterations"]["high"] == 3
- assert "rapid" in param_space["search_strategy"]["choices"]
+ assert "focused-iteration" in param_space["search_strategy"]["choices"]
diff --git a/tests/core/test_search_system_factory.py b/tests/core/test_search_system_factory.py
index 1b2e5e2dbf..b72dae9d73 100644
--- a/tests/core/test_search_system_factory.py
+++ b/tests/core/test_search_system_factory.py
@@ -357,31 +357,6 @@ class TestCreateStrategyFocusedIterationStandard:
assert cite_kw[1]["handler_type"] == "standard"
-class TestCreateStrategyIterativeReasoning:
- """Tests for iterative-reasoning strategy."""
-
- PATCH_PATH = (
- f"{_STRAT_BASE}.iterative_reasoning_strategy.IterativeReasoningStrategy"
- )
-
- @pytest.mark.parametrize(
- "name",
- [
- "iterative-reasoning",
- "iterative_reasoning",
- "iterative_reasoning_depth",
- ],
- )
- def test_name_variants(self, name, mock_model, mock_search):
- with patch(self.PATCH_PATH) as cls:
- cls.return_value = Mock()
- result = create_strategy(
- strategy_name=name, model=mock_model, search=mock_search
- )
- cls.assert_called_once()
- assert result == cls.return_value
-
-
class TestCreateStrategyNews:
"""Tests for news strategy."""
@@ -400,350 +375,6 @@ class TestCreateStrategyNews:
assert result == cls.return_value
-class TestCreateStrategyIterDRAG:
- """Tests for iterdrag strategy."""
-
- PATCH_PATH = f"{_STRAT_BASE}.iterdrag_strategy.IterDRAGStrategy"
-
- def test_create_iterdrag(self, mock_model, mock_search):
- with patch(self.PATCH_PATH) as cls:
- cls.return_value = Mock()
- result = create_strategy(
- strategy_name="iterdrag",
- model=mock_model,
- search=mock_search,
- )
- cls.assert_called_once()
- assert result == cls.return_value
-
- def test_settings_snapshot_forwarded(self, mock_model, mock_search):
- snapshot = {"key": "val"}
- with patch(self.PATCH_PATH) as cls:
- cls.return_value = Mock()
- create_strategy(
- strategy_name="iterdrag",
- model=mock_model,
- search=mock_search,
- settings_snapshot=snapshot,
- )
- kw = cls.call_args[1]
- assert kw["settings_snapshot"] is snapshot
-
-
-class TestCreateStrategyParallel:
- """Tests for parallel strategy."""
-
- PATCH_PATH = (
- f"{_STRAT_BASE}.parallel_search_strategy.ParallelSearchStrategy"
- )
-
- def test_create_parallel(self, mock_model, mock_search):
- with patch(self.PATCH_PATH) as cls:
- cls.return_value = Mock()
- result = create_strategy(
- strategy_name="parallel",
- model=mock_model,
- search=mock_search,
- )
- cls.assert_called_once()
- assert result == cls.return_value
-
- def test_kwargs_passed_through(self, mock_model, mock_search):
- with patch(self.PATCH_PATH) as cls:
- cls.return_value = Mock()
- create_strategy(
- strategy_name="parallel",
- model=mock_model,
- search=mock_search,
- include_text_content=False,
- use_cross_engine_filter=False,
- )
- kw = cls.call_args[1]
- assert kw["include_text_content"] is False
- assert kw["use_cross_engine_filter"] is False
-
-
-class TestCreateStrategyRapid:
- """Tests for rapid strategy."""
-
- PATCH_PATH = f"{_STRAT_BASE}.rapid_search_strategy.RapidSearchStrategy"
-
- def test_create_rapid(self, mock_model, mock_search):
- with patch(self.PATCH_PATH) as cls:
- cls.return_value = Mock()
- result = create_strategy(
- strategy_name="rapid",
- model=mock_model,
- search=mock_search,
- )
- cls.assert_called_once()
- assert result == cls.return_value
-
-
-class TestCreateStrategyRecursive:
- """Tests for recursive strategy."""
-
- PATCH_PATH = f"{_STRAT_BASE}.recursive_decomposition_strategy.RecursiveDecompositionStrategy"
-
- @pytest.mark.parametrize("name", ["recursive", "recursive-decomposition"])
- def test_name_variants(self, name, mock_model, mock_search):
- with patch(self.PATCH_PATH) as cls:
- cls.return_value = Mock()
- result = create_strategy(
- strategy_name=name, model=mock_model, search=mock_search
- )
- cls.assert_called_once()
- assert result == cls.return_value
-
-
-class TestCreateStrategyIterative:
- """Tests for 'iterative' strategy (distinct from iterative-reasoning)."""
-
- PATCH_PATH = (
- f"{_STRAT_BASE}.iterative_reasoning_strategy.IterativeReasoningStrategy"
- )
-
- def test_create_iterative(self, mock_model, mock_search):
- with patch(self.PATCH_PATH) as cls:
- cls.return_value = Mock()
- result = create_strategy(
- strategy_name="iterative",
- model=mock_model,
- search=mock_search,
- )
- cls.assert_called_once()
- assert result == cls.return_value
-
- def test_iterative_passes_extra_kwargs(self, mock_model, mock_search):
- with patch(self.PATCH_PATH) as cls:
- cls.return_value = Mock()
- create_strategy(
- strategy_name="iterative",
- model=mock_model,
- search=mock_search,
- max_iterations=10,
- questions_per_iteration=5,
- confidence_threshold=0.8,
- search_iterations_per_round=2,
- )
- kw = cls.call_args[1]
- assert kw["max_iterations"] == 10
- assert kw["questions_per_search"] == 5
- assert kw["confidence_threshold"] == 0.8
- assert kw["search_iterations_per_round"] == 2
-
-
-class TestCreateStrategyAdaptive:
- """Tests for adaptive strategy."""
-
- PATCH_PATH = f"{_STRAT_BASE}.adaptive_decomposition_strategy.AdaptiveDecompositionStrategy"
-
- def test_create_adaptive(self, mock_model, mock_search):
- with patch(self.PATCH_PATH) as cls:
- cls.return_value = Mock()
- result = create_strategy(
- strategy_name="adaptive",
- model=mock_model,
- search=mock_search,
- )
- cls.assert_called_once()
- assert result == cls.return_value
-
- def test_adaptive_default_max_steps_from_max_iterations(
- self, mock_model, mock_search
- ):
- """max_steps falls back to max_iterations kwarg."""
- with patch(self.PATCH_PATH) as cls:
- cls.return_value = Mock()
- create_strategy(
- strategy_name="adaptive",
- model=mock_model,
- search=mock_search,
- max_iterations=12,
- )
- kw = cls.call_args[1]
- assert kw["max_steps"] == 12
-
-
-class TestCreateStrategySmart:
- """Tests for smart strategy."""
-
- PATCH_PATH = (
- f"{_STRAT_BASE}.smart_decomposition_strategy.SmartDecompositionStrategy"
- )
-
- def test_create_smart(self, mock_model, mock_search):
- with patch(self.PATCH_PATH) as cls:
- cls.return_value = Mock()
- result = create_strategy(
- strategy_name="smart",
- model=mock_model,
- search=mock_search,
- )
- cls.assert_called_once()
- assert result == cls.return_value
-
-
-class TestCreateStrategyBrowsecomp:
- """Tests for browsecomp strategy."""
-
- PATCH_PATH = f"{_STRAT_BASE}.browsecomp_optimized_strategy.BrowseCompOptimizedStrategy"
-
- def test_create_browsecomp(self, mock_model, mock_search):
- with patch(self.PATCH_PATH) as cls:
- cls.return_value = Mock()
- result = create_strategy(
- strategy_name="browsecomp",
- model=mock_model,
- search=mock_search,
- )
- cls.assert_called_once()
- assert result == cls.return_value
-
-
-class TestCreateStrategyEvidence:
- """Tests for evidence strategy."""
-
- PATCH_PATH = f"{_STRAT_BASE}.evidence_based_strategy_v2.EnhancedEvidenceBasedStrategy"
-
- def test_create_evidence(self, mock_model, mock_search):
- with patch(self.PATCH_PATH) as cls:
- cls.return_value = Mock()
- result = create_strategy(
- strategy_name="evidence",
- model=mock_model,
- search=mock_search,
- )
- cls.assert_called_once()
- assert result == cls.return_value
-
- def test_evidence_kwargs(self, mock_model, mock_search):
- with patch(self.PATCH_PATH) as cls:
- cls.return_value = Mock()
- create_strategy(
- strategy_name="evidence",
- model=mock_model,
- search=mock_search,
- candidate_limit=50,
- enable_pattern_learning=False,
- )
- kw = cls.call_args[1]
- assert kw["candidate_limit"] == 50
- assert kw["enable_pattern_learning"] is False
-
-
-class TestCreateStrategyConstrained:
- """Tests for constrained strategy."""
-
- PATCH_PATH = (
- f"{_STRAT_BASE}.constrained_search_strategy.ConstrainedSearchStrategy"
- )
-
- def test_create_constrained(self, mock_model, mock_search):
- with patch(self.PATCH_PATH) as cls:
- cls.return_value = Mock()
- result = create_strategy(
- strategy_name="constrained",
- model=mock_model,
- search=mock_search,
- )
- cls.assert_called_once()
- assert result == cls.return_value
-
-
-class TestCreateStrategyStandard:
- """Tests for standard strategy."""
-
- PATCH_PATH = f"{_STRAT_BASE}.standard_strategy.StandardSearchStrategy"
-
- def test_create_standard(self, mock_model, mock_search):
- with patch(self.PATCH_PATH) as cls:
- cls.return_value = Mock()
- result = create_strategy(
- strategy_name="standard",
- model=mock_model,
- search=mock_search,
- )
- cls.assert_called_once()
- assert result == cls.return_value
-
- def test_settings_snapshot_forwarded(self, mock_model, mock_search):
- snapshot = {"foo": "bar"}
- with patch(self.PATCH_PATH) as cls:
- cls.return_value = Mock()
- create_strategy(
- strategy_name="standard",
- model=mock_model,
- search=mock_search,
- settings_snapshot=snapshot,
- )
- kw = cls.call_args[1]
- assert kw["settings_snapshot"] is snapshot
-
-
-class TestCreateStrategyIterativeRefinement:
- """Tests for iterative-refinement strategy (recursive create_strategy)."""
-
- PATCH_PATH = f"{_STRAT_BASE}.iterative_refinement_strategy.IterativeRefinementStrategy"
- SOURCE_PATCH = (
- f"{_STRAT_BASE}.source_based_strategy.SourceBasedSearchStrategy"
- )
-
- @pytest.mark.parametrize(
- "name", ["iterative-refinement", "iterative_refinement"]
- )
- def test_name_variants(self, name, mock_model, mock_search):
- with patch(self.PATCH_PATH) as cls, patch(self.SOURCE_PATCH):
- cls.return_value = Mock()
- result = create_strategy(
- strategy_name=name, model=mock_model, search=mock_search
- )
- cls.assert_called_once()
- assert result == cls.return_value
-
- def test_recursive_call_creates_initial_strategy(
- self, mock_model, mock_search
- ):
- """The factory recursively calls create_strategy for the initial_strategy."""
- with (
- patch(self.PATCH_PATH) as ref_cls,
- patch(self.SOURCE_PATCH) as src_cls,
- ):
- initial_mock = Mock(name="initial_strategy")
- src_cls.return_value = initial_mock
- ref_cls.return_value = Mock(name="refinement_strategy")
-
- create_strategy(
- strategy_name="iterative-refinement",
- model=mock_model,
- search=mock_search,
- )
-
- # Source-based strategy was created for the initial strategy
- src_cls.assert_called_once()
- # The refinement strategy got the initial strategy as a param
- ref_kw = ref_cls.call_args[1]
- assert ref_kw["initial_strategy"] is initial_mock
-
- def test_custom_initial_strategy(self, mock_model, mock_search):
- """Uses a custom initial_strategy name via kwargs."""
- rapid_path = f"{_STRAT_BASE}.rapid_search_strategy.RapidSearchStrategy"
- with patch(self.PATCH_PATH) as ref_cls, patch(rapid_path) as rapid_cls:
- rapid_cls.return_value = Mock(name="rapid_initial")
- ref_cls.return_value = Mock()
-
- create_strategy(
- strategy_name="iterative-refinement",
- model=mock_model,
- search=mock_search,
- initial_strategy="rapid",
- )
-
- rapid_cls.assert_called_once()
- ref_kw = ref_cls.call_args[1]
- assert ref_kw["initial_strategy"] is rapid_cls.return_value
-
-
# ===========================================================================
# Case-insensitivity tests
# ===========================================================================
@@ -752,13 +383,13 @@ class TestCreateStrategyIterativeRefinement:
class TestCaseInsensitivity:
"""Strategy name matching is case-insensitive via .lower()."""
- def test_uppercase_standard(self, mock_model, mock_search):
+ def test_uppercase_topic_organization(self, mock_model, mock_search):
with patch(
- f"{_STRAT_BASE}.standard_strategy.StandardSearchStrategy"
+ f"{_STRAT_BASE}.topic_organization_strategy.TopicOrganizationStrategy"
) as cls:
cls.return_value = Mock()
create_strategy(
- strategy_name="STANDARD",
+ strategy_name="TOPIC-ORGANIZATION",
model=mock_model,
search=mock_search,
)
@@ -877,11 +508,11 @@ class TestAllLinksHandling:
def test_none_becomes_empty_list(self, mock_model, mock_search):
with patch(
- f"{_STRAT_BASE}.standard_strategy.StandardSearchStrategy"
+ f"{_STRAT_BASE}.source_based_strategy.SourceBasedSearchStrategy"
) as cls:
cls.return_value = Mock()
create_strategy(
- strategy_name="standard",
+ strategy_name="source-based",
model=mock_model,
search=mock_search,
all_links_of_system=None,
@@ -892,11 +523,11 @@ class TestAllLinksHandling:
def test_existing_links_passed_through(self, mock_model, mock_search):
links = [{"link": "http://a.com"}, {"link": "http://b.com"}]
with patch(
- f"{_STRAT_BASE}.standard_strategy.StandardSearchStrategy"
+ f"{_STRAT_BASE}.source_based_strategy.SourceBasedSearchStrategy"
) as cls:
cls.return_value = Mock()
create_strategy(
- strategy_name="standard",
+ strategy_name="source-based",
model=mock_model,
search=mock_search,
all_links_of_system=links,
@@ -905,191 +536,6 @@ class TestAllLinksHandling:
assert kw["all_links_of_system"] is links
-# ===========================================================================
-# Additional strategies to confirm correct class is used
-# ===========================================================================
-
-
-class TestCreateStrategyParallelConstrained:
- """Tests for parallel-constrained strategy."""
-
- PATCH_PATH = f"{_STRAT_BASE}.parallel_constrained_strategy.ParallelConstrainedStrategy"
-
- @pytest.mark.parametrize(
- "name", ["parallel-constrained", "parallel_constrained"]
- )
- def test_name_variants(self, name, mock_model, mock_search):
- with patch(self.PATCH_PATH) as cls:
- cls.return_value = Mock()
- result = create_strategy(
- strategy_name=name, model=mock_model, search=mock_search
- )
- cls.assert_called_once()
- assert result == cls.return_value
-
-
-class TestCreateStrategyEarlyStopConstrained:
- """Tests for early-stop-constrained strategy."""
-
- PATCH_PATH = f"{_STRAT_BASE}.early_stop_constrained_strategy.EarlyStopConstrainedStrategy"
-
- @pytest.mark.parametrize(
- "name", ["early-stop-constrained", "early_stop_constrained"]
- )
- def test_name_variants(self, name, mock_model, mock_search):
- with patch(self.PATCH_PATH) as cls:
- cls.return_value = Mock()
- result = create_strategy(
- strategy_name=name, model=mock_model, search=mock_search
- )
- cls.assert_called_once()
- assert result == cls.return_value
-
-
-class TestCreateStrategySmartQuery:
- """Tests for smart-query strategy."""
-
- PATCH_PATH = f"{_STRAT_BASE}.smart_query_strategy.SmartQueryStrategy"
-
- @pytest.mark.parametrize("name", ["smart-query", "smart_query"])
- def test_name_variants(self, name, mock_model, mock_search):
- with patch(self.PATCH_PATH) as cls:
- cls.return_value = Mock()
- result = create_strategy(
- strategy_name=name, model=mock_model, search=mock_search
- )
- cls.assert_called_once()
- assert result == cls.return_value
-
-
-class TestCreateStrategyDualConfidence:
- """Tests for dual-confidence strategy."""
-
- PATCH_PATH = (
- f"{_STRAT_BASE}.dual_confidence_strategy.DualConfidenceStrategy"
- )
-
- @pytest.mark.parametrize("name", ["dual-confidence", "dual_confidence"])
- def test_name_variants(self, name, mock_model, mock_search):
- with patch(self.PATCH_PATH) as cls:
- cls.return_value = Mock()
- result = create_strategy(
- strategy_name=name, model=mock_model, search=mock_search
- )
- cls.assert_called_once()
- assert result == cls.return_value
-
-
-class TestCreateStrategyDualConfidenceWithRejection:
- """Tests for dual-confidence-with-rejection strategy."""
-
- PATCH_PATH = f"{_STRAT_BASE}.dual_confidence_with_rejection.DualConfidenceWithRejectionStrategy"
-
- @pytest.mark.parametrize(
- "name",
- ["dual-confidence-with-rejection", "dual_confidence_with_rejection"],
- )
- def test_name_variants(self, name, mock_model, mock_search):
- with patch(self.PATCH_PATH) as cls:
- cls.return_value = Mock()
- result = create_strategy(
- strategy_name=name, model=mock_model, search=mock_search
- )
- cls.assert_called_once()
- assert result == cls.return_value
-
-
-class TestCreateStrategyConcurrentDualConfidence:
- """Tests for concurrent-dual-confidence strategy."""
-
- PATCH_PATH = f"{_STRAT_BASE}.concurrent_dual_confidence_strategy.ConcurrentDualConfidenceStrategy"
-
- @pytest.mark.parametrize(
- "name",
- ["concurrent-dual-confidence", "concurrent_dual_confidence"],
- )
- def test_name_variants(self, name, mock_model, mock_search):
- with patch(self.PATCH_PATH) as cls:
- cls.return_value = Mock()
- result = create_strategy(
- strategy_name=name, model=mock_model, search=mock_search
- )
- cls.assert_called_once()
- assert result == cls.return_value
-
-
-class TestCreateStrategyConstraintParallel:
- """Tests for constraint-parallel strategy."""
-
- PATCH_PATH = (
- f"{_STRAT_BASE}.constraint_parallel_strategy.ConstraintParallelStrategy"
- )
-
- @pytest.mark.parametrize(
- "name", ["constraint-parallel", "constraint_parallel"]
- )
- def test_name_variants(self, name, mock_model, mock_search):
- with patch(self.PATCH_PATH) as cls:
- cls.return_value = Mock()
- result = create_strategy(
- strategy_name=name, model=mock_model, search=mock_search
- )
- cls.assert_called_once()
- assert result == cls.return_value
-
-
-class TestCreateStrategyModular:
- """Tests for modular strategy."""
-
- PATCH_PATH = f"{_STRAT_BASE}.modular_strategy.ModularStrategy"
-
- @pytest.mark.parametrize("name", ["modular", "modular-strategy"])
- def test_name_variants(self, name, mock_model, mock_search):
- with patch(self.PATCH_PATH) as cls:
- cls.return_value = Mock()
- result = create_strategy(
- strategy_name=name, model=mock_model, search=mock_search
- )
- cls.assert_called_once()
- assert result == cls.return_value
-
-
-class TestCreateStrategyModularParallel:
- """Tests for modular-parallel strategy."""
-
- PATCH_PATH = f"{_STRAT_BASE}.modular_strategy.ModularStrategy"
-
- @pytest.mark.parametrize("name", ["modular-parallel", "modular_parallel"])
- def test_name_variants(self, name, mock_model, mock_search):
- with patch(self.PATCH_PATH) as cls:
- cls.return_value = Mock()
- result = create_strategy(
- strategy_name=name, model=mock_model, search=mock_search
- )
- cls.assert_called_once()
- kw = cls.call_args[1]
- assert kw["exploration_strategy"] == "parallel"
- assert result == cls.return_value
-
-
-class TestCreateStrategyBrowsecompEntity:
- """Tests for browsecomp-entity strategy."""
-
- PATCH_PATH = (
- f"{_STRAT_BASE}.browsecomp_entity_strategy.BrowseCompEntityStrategy"
- )
-
- @pytest.mark.parametrize("name", ["browsecomp-entity", "browsecomp_entity"])
- def test_name_variants(self, name, mock_model, mock_search):
- with patch(self.PATCH_PATH) as cls:
- cls.return_value = Mock()
- result = create_strategy(
- strategy_name=name, model=mock_model, search=mock_search
- )
- cls.assert_called_once()
- assert result == cls.return_value
-
-
class TestCreateStrategyTopicOrganization:
"""Tests for topic-organization strategy."""
diff --git a/tests/core/test_search_system_factory_extended.py b/tests/core/test_search_system_factory_extended.py
index 7b07384bde..aed4f041ed 100644
--- a/tests/core/test_search_system_factory_extended.py
+++ b/tests/core/test_search_system_factory_extended.py
@@ -1,7 +1,7 @@
"""Extended tests for search_system_factory.py - covering _get_setting helper,
strategy creation edge cases, and unknown strategy fallback."""
-from unittest.mock import Mock, patch
+from unittest.mock import Mock
class TestGetSettingHelper:
@@ -104,59 +104,16 @@ class TestCreateStrategyNames:
f"Variant '{variant}' did not create SourceBasedSearchStrategy"
)
- def test_iterdrag_creates_correct_strategy(self):
- """iterdrag name should create IterDRAGStrategy."""
+ def test_topic_organization_creates_correct_strategy(self):
+ """topic-organization name should create TopicOrganizationStrategy."""
from local_deep_research.search_system_factory import create_strategy
strategy = create_strategy(
- strategy_name="iterdrag",
+ strategy_name="topic-organization",
model=Mock(),
search=Mock(),
)
- assert type(strategy).__name__ == "IterDRAGStrategy"
-
- def test_rapid_creates_correct_strategy(self):
- """rapid name should create RapidSearchStrategy."""
- from local_deep_research.search_system_factory import create_strategy
-
- strategy = create_strategy(
- strategy_name="rapid",
- model=Mock(),
- search=Mock(),
- )
- assert type(strategy).__name__ == "RapidSearchStrategy"
-
- def test_parallel_creates_correct_strategy(self):
- """parallel name should create ParallelSearchStrategy."""
- from local_deep_research.search_system_factory import create_strategy
-
- strategy = create_strategy(
- strategy_name="parallel",
- model=Mock(),
- search=Mock(),
- )
- assert type(strategy).__name__ == "ParallelSearchStrategy"
-
- def test_standard_creates_correct_strategy(self):
- """standard name should create StandardSearchStrategy."""
- from local_deep_research.search_system_factory import create_strategy
-
- settings = {
- "search.iterations": {"value": 3},
- "search.questions_per_iteration": {"value": 3},
- "general.knowledge_accumulation_context_limit": {"value": 50000},
- }
-
- with patch(
- "local_deep_research.citation_handlers.standard_citation_handler.StandardCitationHandler"
- ):
- strategy = create_strategy(
- strategy_name="standard",
- model=Mock(),
- search=Mock(),
- settings_snapshot=settings,
- )
- assert type(strategy).__name__ == "StandardSearchStrategy"
+ assert type(strategy).__name__ == "TopicOrganizationStrategy"
class TestCreateStrategyUnknown:
@@ -204,21 +161,19 @@ class TestCreateStrategyKwargsPassthrough:
assert strategy.include_text_content is False
assert strategy.use_cross_engine_filter is False
- def test_iterative_strategy_receives_iteration_settings(self):
- """Iterative strategy should receive iteration settings from kwargs."""
+ def test_focused_iteration_receives_iteration_settings(self):
+ """Focused-iteration strategy should receive iteration settings from kwargs."""
from local_deep_research.search_system_factory import create_strategy
strategy = create_strategy(
- strategy_name="iterative",
+ strategy_name="focused-iteration",
model=Mock(),
search=Mock(),
max_iterations=15,
questions_per_iteration=5,
- confidence_threshold=0.85,
)
assert strategy.max_iterations == 15
- assert strategy.confidence_threshold == 0.85
class TestCreateStrategySettingsSnapshot:
@@ -229,7 +184,7 @@ class TestCreateStrategySettingsSnapshot:
from local_deep_research.search_system_factory import create_strategy
strategy = create_strategy(
- strategy_name="rapid",
+ strategy_name="topic-organization",
model=Mock(),
search=Mock(),
all_links_of_system=None,
@@ -244,7 +199,7 @@ class TestCreateStrategySettingsSnapshot:
existing_links = [{"url": "http://example.com", "title": "Test"}]
strategy = create_strategy(
- strategy_name="rapid",
+ strategy_name="topic-organization",
model=Mock(),
search=Mock(),
all_links_of_system=existing_links,
@@ -333,11 +288,11 @@ class TestCreateStrategyCaseInsensitivity:
# The function calls .lower() on strategy_name
strategy = create_strategy(
- strategy_name="RAPID",
+ strategy_name="TOPIC-ORGANIZATION",
model=Mock(),
search=Mock(),
)
- assert type(strategy).__name__ == "RapidSearchStrategy"
+ assert type(strategy).__name__ == "TopicOrganizationStrategy"
def test_mixed_case_matching(self):
"""Mixed case strategy names should work."""
diff --git a/tests/mcp/test_additional_coverage.py b/tests/mcp/test_additional_coverage.py
index b7dedd91ef..977cb10d2b 100644
--- a/tests/mcp/test_additional_coverage.py
+++ b/tests/mcp/test_additional_coverage.py
@@ -405,7 +405,7 @@ class TestAvailableStrategiesContent:
get_available_strategies,
)
- strategies = get_available_strategies(show_all=True)
+ strategies = get_available_strategies()
names = [s["name"] for s in strategies]
# These are the actual strategies defined in the system
@@ -413,7 +413,6 @@ class TestAvailableStrategiesContent:
"source-based",
"focused-iteration",
"focused-iteration-standard",
- "iterative-refinement",
"topic-organization",
"mcp",
"langgraph-agent",
diff --git a/tests/mcp/test_integration.py b/tests/mcp/test_integration.py
index 54a7958785..3bcbb73d66 100644
--- a/tests/mcp/test_integration.py
+++ b/tests/mcp/test_integration.py
@@ -252,8 +252,8 @@ class TestDiscoveryToolsIntegration:
# Check for key strategies
assert "source-based" in strategy_names
assert "focused-iteration" in strategy_names
- assert "iterative-refinement" in strategy_names
assert "topic-organization" in strategy_names
+ assert "langgraph-agent" in strategy_names
def test_get_configuration_structure(self):
"""Verify get_configuration returns expected structure."""
diff --git a/tests/mcp/test_mcp_protocol.py b/tests/mcp/test_mcp_protocol.py
index 6de271d30f..1b5cdd90a4 100644
--- a/tests/mcp/test_mcp_protocol.py
+++ b/tests/mcp/test_mcp_protocol.py
@@ -198,7 +198,7 @@ class TestAvailableStrategies:
get_available_strategies,
)
- strategies = get_available_strategies(show_all=True)
+ strategies = get_available_strategies()
assert isinstance(strategies, list)
def test_available_strategies_has_entries(self):
@@ -207,8 +207,8 @@ class TestAvailableStrategies:
get_available_strategies,
)
- strategies = get_available_strategies(show_all=True)
- assert len(strategies) >= 10
+ strategies = get_available_strategies()
+ assert len(strategies) >= 6
def test_available_strategies_have_required_fields(self):
"""Verify each strategy has name and description."""
@@ -216,7 +216,7 @@ class TestAvailableStrategies:
get_available_strategies,
)
- strategies = get_available_strategies(show_all=True)
+ strategies = get_available_strategies()
for strategy in strategies:
assert "name" in strategy, f"Strategy missing 'name': {strategy}"
assert "description" in strategy, (
@@ -233,7 +233,7 @@ class TestAvailableStrategies:
get_available_strategies,
)
- strategies = get_available_strategies(show_all=True)
+ strategies = get_available_strategies()
strategy_names = [s["name"] for s in strategies]
assert "source-based" in strategy_names
@@ -243,7 +243,7 @@ class TestAvailableStrategies:
get_available_strategies,
)
- strategies = get_available_strategies(show_all=True)
+ strategies = get_available_strategies()
strategy_names = [s["name"] for s in strategies]
assert "focused-iteration" in strategy_names
diff --git a/tests/mcp/test_validation.py b/tests/mcp/test_validation.py
index 81c2ca186d..3ed461c139 100644
--- a/tests/mcp/test_validation.py
+++ b/tests/mcp/test_validation.py
@@ -425,7 +425,7 @@ class TestGetAvailableStrategies:
)
result = list_strategies()
- expected = get_available_strategies(show_all=True)
+ expected = get_available_strategies()
assert result["status"] == "success"
assert result["strategies"] == expected
diff --git a/tests/news/test_web_blueprint.py b/tests/news/test_web_blueprint.py
index 7f22ee97a4..afecbecdc8 100644
--- a/tests/news/test_web_blueprint.py
+++ b/tests/news/test_web_blueprint.py
@@ -323,8 +323,7 @@ class TestNewSubscriptionPageRoute:
client.get("/news/subscriptions/new")
# get_user_db_session is called once for loading settings
- # and once more by _show_all_strategies()
- assert mock_db.call_count == 2
+ assert mock_db.call_count == 1
def test_new_subscription_page_logged_in_user_calls_load_user_settings(
self, app
@@ -494,8 +493,7 @@ class TestEditSubscriptionPageRoute:
client.get("/news/subscriptions/sub-123/edit")
# get_user_db_session is called for loading settings
- # and by _show_all_strategies()
- assert mock_db.call_count == 2
+ assert mock_db.call_count == 1
def test_edit_subscription_page_logs_subscription_id(self, client):
"""Test that subscription ID is logged."""
diff --git a/tests/news/test_web_routes_comprehensive.py b/tests/news/test_web_routes_comprehensive.py
index c1a1b91a0a..c86a433f1b 100644
--- a/tests/news/test_web_routes_comprehensive.py
+++ b/tests/news/test_web_routes_comprehensive.py
@@ -423,25 +423,15 @@ class TestStrategyList:
"""Tests for strategy list in news page."""
def test_strategies_include_topic_organization(self):
- """Test all strategies includes topic-organization when show_all=True."""
+ """Test the strategies list includes topic-organization."""
from local_deep_research.search_system_factory import (
get_available_strategies,
)
- strategies = get_available_strategies(show_all=True)
+ strategies = get_available_strategies()
strategy_names = [s["name"] for s in strategies]
assert "topic-organization" in strategy_names
- def test_strategies_include_iterative_refinement(self):
- """Test all strategies includes iterative-refinement when show_all=True."""
- from local_deep_research.search_system_factory import (
- get_available_strategies,
- )
-
- strategies = get_available_strategies(show_all=True)
- strategy_names = [s["name"] for s in strategies]
- assert "iterative-refinement" in strategy_names
-
def test_strategies_include_source_based(self):
"""Test strategies list includes source-based."""
from local_deep_research.news.web import create_news_blueprint
diff --git a/tests/performance/strategies/test_search_system_iterative.py b/tests/performance/strategies/test_search_system_iterative.py
deleted file mode 100755
index fdea7742e6..0000000000
--- a/tests/performance/strategies/test_search_system_iterative.py
+++ /dev/null
@@ -1,104 +0,0 @@
-#!/usr/bin/env python3
-"""
-Test that the iterative strategy is properly integrated into the search system.
-"""
-
-import pytest
-
-from local_deep_research.search_system import AdvancedSearchSystem
-
-
-def test_iterative_strategy_integration():
- """Test that iterative strategy can be instantiated through AdvancedSearchSystem."""
-
- # Test query
- query = """I am looking for a hike to a specific scenic location. I know these details about the location:
- It was formed during the last ice age. Part of its name relates to a body part.
- Someone fell from the viewpoint between 2000 and 2021.
- In 2022, the Grand Canyon had 84.5x more Search and Rescue incidents than this hike had in 2014.
- What is the name of this location?"""
-
- print("Testing Iterative Strategy Integration")
- print("=" * 50)
-
- # Create search system with iterative strategy
- search_system = AdvancedSearchSystem(
- strategy_name="iterative", max_iterations=8, questions_per_iteration=15
- )
-
- # Set up progress callback
- def progress_callback(message, progress, data):
- print(f"[{progress:3d}%] {message}")
- if "iteration" in data:
- print(f" Iteration: {data['iteration']}")
-
- search_system.set_progress_callback(progress_callback)
-
- print(f"\nQuery: {query[:100]}...")
- print("\nRunning search...")
-
- # Run the search
- results = search_system.analyze_topic(query)
-
- # Check results
- print("\n" + "=" * 50)
- print("RESULTS")
- print("=" * 50)
-
- print(f"Strategy used: {results.get('strategy', 'unknown')}")
- print(f"Total iterations: {results.get('iterations', 0)}")
-
- if "knowledge_state" in results:
- knowledge = results["knowledge_state"]
- print(f"\nKey facts found: {len(knowledge.get('key_facts', []))}")
- print(f"Confidence: {knowledge.get('confidence', 0):.1%}")
-
- print(
- f"\nAnswer preview: {results.get('current_knowledge', 'No answer')[:200]}..."
- )
-
- # Verify we got the right strategy
- assert results.get("strategy") == "iterative_reasoning", (
- f"Expected 'iterative_reasoning', got {results.get('strategy')}"
- )
- print("\n✅ Iterative strategy successfully integrated!")
-
-
-def test_all_strategies_available():
- """Test that all strategies can be instantiated."""
-
- strategies = [
- "standard",
- "iterdrag",
- "source-based",
- "parallel",
- "rapid",
- "recursive",
- "iterative",
- "adaptive",
- "smart",
- ]
-
- print("\n" + "=" * 50)
- print("Testing All Strategy Types")
- print("=" * 50)
-
- for strategy_name in strategies:
- try:
- search_system = AdvancedSearchSystem(strategy_name=strategy_name)
- actual_strategy = type(search_system.strategy).__name__
- print(f"✅ {strategy_name:<15} -> {actual_strategy}")
- except Exception as e:
- print(f"❌ {strategy_name:<15} -> Error: {e}")
-
- print("\nAll strategies tested!")
-
-
-if __name__ == "__main__":
- # Test the iterative strategy
- test_iterative_strategy_integration()
-
- # Test all available strategies
- test_all_strategies_available()
diff --git a/tests/settings/golden_master_settings.json b/tests/settings/golden_master_settings.json
index e0a8b3da08..f01242900e 100644
--- a/tests/settings/golden_master_settings.json
+++ b/tests/settings/golden_master_settings.json
@@ -7913,7 +7913,7 @@
},
"search.search_strategy": {
"category": "search_parameters",
- "description": "Research methodology. 'source-based': Finds and extracts from sources (good for comprehensive research). 'focused-iteration': Uses entity-based progressive exploration (optimized for factual Q&A, ~95% SimpleQA accuracy, requires larger context windows). 'focused-iteration-standard': Comprehensive variant of focused-iteration with broader exploration. 'iterative-refinement': LLM-guided progressive refinement with gap analysis. 'topic-organization': Organizes research around discovered topic clusters. 'mcp': Agentic ReAct-pattern research using MCP tools.",
+ "description": "Research methodology. 'source-based': Finds and extracts from sources (good for comprehensive research). 'focused-iteration': Uses entity-based progressive exploration (optimized for factual Q&A, ~95% SimpleQA accuracy, requires larger context windows). 'focused-iteration-standard': Comprehensive variant of focused-iteration with broader exploration. 'topic-organization': Organizes research around discovered topic clusters. 'mcp': Agentic ReAct-pattern research using MCP tools. 'langgraph-agent': Autonomous agentic research where the LLM decides what to search and when to synthesize.",
"editable": true,
"max_value": null,
"min_value": null,
@@ -7931,6 +7931,10 @@
"label": "Focused Iteration - Comprehensive (Needs >16,000 context window)",
"value": "focused-iteration-standard"
},
+ {
+ "label": "Topic Organization (Clusters by topic)",
+ "value": "topic-organization"
+ },
{
"label": "MCP ReAct (Agentic research - LLM decides tools)",
"value": "mcp"
@@ -7960,20 +7964,6 @@
"value": 2,
"visible": true
},
- "search.show_all_strategies": {
- "category": "search_parameters",
- "description": "When enabled, all available search strategies (including advanced and experimental ones) are shown in strategy dropdowns. When disabled, only the recommended strategies are shown.",
- "editable": true,
- "max_value": null,
- "min_value": null,
- "name": "Show All Strategies",
- "options": null,
- "step": null,
- "type": "SEARCH",
- "ui_element": "checkbox",
- "value": false,
- "visible": true
- },
"search.skip_relevance_filter": {
"category": "search_parameters",
"description": "When checked, LLM-based relevance filtering is suppressed for general-purpose search engines that do not require it. Keyword-based engines (arXiv, PubMed, Wikipedia, GitHub, etc.) always run the filter regardless of this checkbox; per-engine settings override both.",
diff --git a/tests/settings/test_settings_defaults_integrity.py b/tests/settings/test_settings_defaults_integrity.py
index f12353340a..61121a14c7 100644
--- a/tests/settings/test_settings_defaults_integrity.py
+++ b/tests/settings/test_settings_defaults_integrity.py
@@ -43,6 +43,12 @@ KNOWN_UNUSED = {
"report.export_formats",
"research_library.confirm_deletions",
"search.quality_check_urls",
+ # Only ever consumed by the iterdrag/standard strategies, which were
+ # removed when the experimental strategies were dropped. The setting and
+ # its KnowledgeAccumulationApproach enum are now dead; left in defaults
+ # for the planned Phase 4 settings cleanup.
+ "general.knowledge_accumulation",
+ "general.knowledge_accumulation_context_limit",
}
# ---------------------------------------------------------------------------
diff --git a/tests/strategies/conftest.py b/tests/strategies/conftest.py
index 533025b0ab..5bb1e02926 100644
--- a/tests/strategies/conftest.py
+++ b/tests/strategies/conftest.py
@@ -235,63 +235,19 @@ FACTORY_STRATEGY_NAMES = [
"source-based",
"focused-iteration",
"focused-iteration-standard",
- "iterative-reasoning",
"news",
- "iterdrag",
- "parallel",
- "rapid",
- "recursive",
- "iterative",
- "adaptive",
- "smart",
- "browsecomp",
- "evidence",
- "constrained",
- "parallel-constrained",
- "early-stop-constrained",
- "smart-query",
- "dual-confidence",
- "dual-confidence-with-rejection",
- "concurrent-dual-confidence",
- "constraint-parallel",
- "modular",
- "modular-parallel",
- "browsecomp-entity",
"topic-organization",
- "iterative-refinement",
- "standard",
+ "mcp",
"langgraph-agent",
]
-# Strategy classes that can be imported directly (including those not in factory)
+# Strategy classes that can be imported directly
STRATEGY_IMPORTS = [
("source_based_strategy", "SourceBasedSearchStrategy"),
("focused_iteration_strategy", "FocusedIterationStrategy"),
- ("iterative_reasoning_strategy", "IterativeReasoningStrategy"),
- # NOTE: IterativeReasoningDepthStrategy doesn't exist - factory has broken reference
("news_strategy", "NewsAggregationStrategy"),
- ("iterdrag_strategy", "IterDRAGStrategy"),
- ("parallel_search_strategy", "ParallelSearchStrategy"),
- ("rapid_search_strategy", "RapidSearchStrategy"),
- ("recursive_decomposition_strategy", "RecursiveDecompositionStrategy"),
- ("adaptive_decomposition_strategy", "AdaptiveDecompositionStrategy"),
- ("smart_decomposition_strategy", "SmartDecompositionStrategy"),
- ("browsecomp_optimized_strategy", "BrowseCompOptimizedStrategy"),
- ("evidence_based_strategy_v2", "EnhancedEvidenceBasedStrategy"),
- ("evidence_based_strategy", "EvidenceBasedStrategy"),
- ("constrained_search_strategy", "ConstrainedSearchStrategy"),
- ("parallel_constrained_strategy", "ParallelConstrainedStrategy"),
- ("early_stop_constrained_strategy", "EarlyStopConstrainedStrategy"),
- ("smart_query_strategy", "SmartQueryStrategy"),
- ("dual_confidence_strategy", "DualConfidenceStrategy"),
- ("dual_confidence_with_rejection", "DualConfidenceWithRejectionStrategy"),
- ("concurrent_dual_confidence_strategy", "ConcurrentDualConfidenceStrategy"),
- ("constraint_parallel_strategy", "ConstraintParallelStrategy"),
- ("modular_strategy", "ModularStrategy"),
- ("browsecomp_entity_strategy", "BrowseCompEntityStrategy"),
("topic_organization_strategy", "TopicOrganizationStrategy"),
- ("iterative_refinement_strategy", "IterativeRefinementStrategy"),
- ("standard_strategy", "StandardSearchStrategy"),
+ ("mcp_strategy", "MCPSearchStrategy"),
("langgraph_agent_strategy", "LangGraphAgentStrategy"),
]
diff --git a/tests/strategies/test_bare_except_fixes.py b/tests/strategies/test_bare_except_fixes.py
index 0b6c3217cf..41b6d5671d 100644
--- a/tests/strategies/test_bare_except_fixes.py
+++ b/tests/strategies/test_bare_except_fixes.py
@@ -47,23 +47,3 @@ class TestBareExceptFixes:
assert "logger.debug" in source, (
"_related_terms_query should have logger.debug for exceptions"
)
-
- def test_get_synonyms_captures_exception(self):
- from local_deep_research.advanced_search_system.strategies.evidence_based_strategy_v2 import (
- EnhancedEvidenceBasedStrategy,
- )
-
- source = inspect.getsource(EnhancedEvidenceBasedStrategy._get_synonyms)
- assert "except Exception as e" in source, (
- "_get_synonyms should use 'except Exception as e'"
- )
-
- def test_get_synonyms_logs_error(self):
- from local_deep_research.advanced_search_system.strategies.evidence_based_strategy_v2 import (
- EnhancedEvidenceBasedStrategy,
- )
-
- source = inspect.getsource(EnhancedEvidenceBasedStrategy._get_synonyms)
- assert "logger.debug" in source, (
- "_get_synonyms should have logger.debug for exceptions"
- )
diff --git a/tests/strategies/test_cancellation_checks.py b/tests/strategies/test_cancellation_checks.py
index 135f1af48a..e2d40be280 100644
--- a/tests/strategies/test_cancellation_checks.py
+++ b/tests/strategies/test_cancellation_checks.py
@@ -70,22 +70,6 @@ class TestCheckTerminationMethod:
class TestStrategiesCallCheckTermination:
"""Verify each strategy calls check_termination() in its main loop."""
- def test_iterative_reasoning_calls_check(self):
- from local_deep_research.advanced_search_system.strategies.iterative_reasoning_strategy import (
- IterativeReasoningStrategy,
- )
-
- source = inspect.getsource(IterativeReasoningStrategy.analyze_topic)
- assert "self.check_termination()" in source
-
- def test_iterative_refinement_calls_check(self):
- from local_deep_research.advanced_search_system.strategies.iterative_refinement_strategy import (
- IterativeRefinementStrategy,
- )
-
- source = inspect.getsource(IterativeRefinementStrategy.analyze_topic)
- assert "self.check_termination()" in source
-
def test_source_based_calls_check(self):
from local_deep_research.advanced_search_system.strategies.source_based_strategy import (
SourceBasedSearchStrategy,
diff --git a/tests/strategies/test_strategy_behaviors.py b/tests/strategies/test_strategy_behaviors.py
index 6e1f63ca9a..5b894a3f5b 100644
--- a/tests/strategies/test_strategy_behaviors.py
+++ b/tests/strategies/test_strategy_behaviors.py
@@ -4,7 +4,6 @@ Detailed behavior tests for working strategies.
Tests specific features and behaviors of strategies beyond basic functionality.
"""
-import pytest
from loguru import logger
@@ -84,115 +83,6 @@ class TestSourceBasedStrategy:
assert "formatted_findings" in result or "findings" in result
-class TestRapidStrategy:
- """Detailed tests for RapidSearchStrategy."""
-
- def test_completes_in_single_iteration(
- self,
- strategy_mock_llm,
- strategy_mock_search,
- strategy_settings_snapshot,
- ):
- """Test that rapid strategy completes quickly (single iteration)."""
- from local_deep_research.search_system_factory import (
- create_strategy,
- )
-
- strategy = create_strategy(
- strategy_name="rapid",
- model=strategy_mock_llm,
- search=strategy_mock_search,
- settings_snapshot=strategy_settings_snapshot,
- )
-
- result = strategy.analyze_topic("Quick test query")
-
- # Rapid should complete in 1 iteration
- iterations = result.get("iterations", 1)
- assert iterations <= 2, f"Rapid strategy took {iterations} iterations"
- logger.info(f"Rapid strategy completed in {iterations} iteration(s)")
-
- def test_uses_original_query_directly(
- self,
- strategy_mock_llm,
- strategy_mock_search,
- strategy_settings_snapshot,
- ):
- """Test that rapid strategy searches with original query."""
- from local_deep_research.search_system_factory import (
- create_strategy,
- )
-
- strategy = create_strategy(
- strategy_name="rapid",
- model=strategy_mock_llm,
- search=strategy_mock_search,
- settings_snapshot=strategy_settings_snapshot,
- )
-
- query = "Test original query"
- strategy.analyze_topic(query)
-
- # Check that search was called
- assert strategy_mock_search.run.called
-
-
-class TestParallelStrategy:
- """Detailed tests for ParallelSearchStrategy."""
-
- def test_executes_multiple_searches(
- self,
- strategy_mock_llm,
- strategy_mock_search,
- strategy_settings_snapshot,
- ):
- """Test that parallel strategy executes multiple searches."""
- from local_deep_research.search_system_factory import (
- create_strategy,
- )
-
- strategy = create_strategy(
- strategy_name="parallel",
- model=strategy_mock_llm,
- search=strategy_mock_search,
- settings_snapshot=strategy_settings_snapshot,
- )
-
- strategy.analyze_topic("Test query for parallel")
-
- # Should have made multiple search calls
- call_count = strategy_mock_search.run.call_count
- logger.info(f"Parallel strategy made {call_count} search calls")
-
-
-class TestIterDRAGStrategy:
- """Detailed tests for IterDRAGStrategy."""
-
- def test_builds_knowledge_iteratively(
- self,
- strategy_mock_llm,
- strategy_mock_search,
- strategy_settings_snapshot,
- ):
- """Test that IterDRAG builds knowledge through iterations."""
- from local_deep_research.search_system_factory import (
- create_strategy,
- )
-
- strategy = create_strategy(
- strategy_name="iterdrag",
- model=strategy_mock_llm,
- search=strategy_mock_search,
- settings_snapshot=strategy_settings_snapshot,
- )
-
- result = strategy.analyze_topic("Complex research topic")
-
- # Should have current_knowledge
- assert "current_knowledge" in result
- assert result["current_knowledge"] is not None
-
-
class TestNewsStrategy:
"""Detailed tests for NewsAggregationStrategy."""
@@ -270,162 +160,6 @@ class TestFocusedIterationStrategy:
assert strategy.questions_by_iteration is not None
-class TestConstrainedStrategies:
- """Tests for constraint-based strategies."""
-
- @pytest.mark.parametrize(
- "strategy_name",
- [
- "constrained",
- "parallel-constrained",
- "early-stop-constrained",
- ],
- )
- def test_constrained_strategy_works(
- self,
- strategy_name,
- strategy_mock_llm,
- strategy_mock_search,
- strategy_settings_snapshot,
- ):
- """Test that constrained strategies can analyze topics."""
- from local_deep_research.search_system_factory import (
- create_strategy,
- )
-
- strategy = create_strategy(
- strategy_name=strategy_name,
- model=strategy_mock_llm,
- search=strategy_mock_search,
- settings_snapshot=strategy_settings_snapshot,
- )
-
- result = strategy.analyze_topic("Find X that matches Y constraint")
-
- assert isinstance(result, dict)
- logger.info(f"{strategy_name} returned: {list(result.keys())}")
-
-
-class TestDualConfidenceStrategies:
- """Tests for dual confidence strategies."""
-
- @pytest.mark.parametrize(
- "strategy_name",
- [
- "dual-confidence",
- "dual-confidence-with-rejection",
- "concurrent-dual-confidence",
- ],
- )
- def test_dual_confidence_strategy_works(
- self,
- strategy_name,
- strategy_mock_llm,
- strategy_mock_search,
- strategy_settings_snapshot,
- ):
- """Test that dual confidence strategies work."""
- from local_deep_research.search_system_factory import (
- create_strategy,
- )
-
- strategy = create_strategy(
- strategy_name=strategy_name,
- model=strategy_mock_llm,
- search=strategy_mock_search,
- settings_snapshot=strategy_settings_snapshot,
- )
-
- result = strategy.analyze_topic(
- "Question requiring confidence assessment"
- )
-
- assert isinstance(result, dict)
- logger.info(f"{strategy_name} keys: {list(result.keys())}")
-
-
-class TestModularStrategies:
- """Tests for modular strategies."""
-
- @pytest.mark.parametrize("strategy_name", ["modular", "modular-parallel"])
- def test_modular_strategy_works(
- self,
- strategy_name,
- strategy_mock_llm,
- strategy_mock_search,
- strategy_settings_snapshot,
- ):
- """Test that modular strategies work."""
- from local_deep_research.search_system_factory import (
- create_strategy,
- )
-
- strategy = create_strategy(
- strategy_name=strategy_name,
- model=strategy_mock_llm,
- search=strategy_mock_search,
- settings_snapshot=strategy_settings_snapshot,
- )
-
- result = strategy.analyze_topic("Modular research query")
-
- assert isinstance(result, dict)
-
-
-class TestBrowseCompStrategy:
- """Tests for BrowseComp strategy."""
-
- def test_browsecomp_handles_puzzle_queries(
- self,
- strategy_mock_llm,
- strategy_mock_search,
- strategy_settings_snapshot,
- ):
- """Test BrowseComp with puzzle-style queries."""
- from local_deep_research.search_system_factory import (
- create_strategy,
- )
-
- strategy = create_strategy(
- strategy_name="browsecomp",
- model=strategy_mock_llm,
- search=strategy_mock_search,
- settings_snapshot=strategy_settings_snapshot,
- )
-
- puzzle_query = "What is the name of the location that was formed during the ice age?"
- result = strategy.analyze_topic(puzzle_query)
-
- assert isinstance(result, dict)
- logger.info(f"BrowseComp result keys: {list(result.keys())}")
-
-
-class TestSmartQueryStrategy:
- """Tests for SmartQueryStrategy."""
-
- def test_smart_query_selects_strategy(
- self,
- strategy_mock_llm,
- strategy_mock_search,
- strategy_settings_snapshot,
- ):
- """Test that smart-query selects appropriate strategy."""
- from local_deep_research.search_system_factory import (
- create_strategy,
- )
-
- strategy = create_strategy(
- strategy_name="smart-query",
- model=strategy_mock_llm,
- search=strategy_mock_search,
- settings_snapshot=strategy_settings_snapshot,
- )
-
- result = strategy.analyze_topic("Research question")
-
- assert isinstance(result, dict)
-
-
class TestTopicOrganizationStrategy:
"""Tests for TopicOrganizationStrategy."""
@@ -458,30 +192,3 @@ class TestTopicOrganizationStrategy:
result = strategy.analyze_topic("Multi-topic research question")
assert isinstance(result, dict)
-
-
-class TestIterativeRefinementStrategy:
- """Tests for IterativeRefinementStrategy."""
-
- def test_iterative_refinement_works(
- self,
- strategy_mock_llm,
- strategy_mock_search,
- strategy_settings_snapshot,
- ):
- """Test iterative refinement strategy."""
- from local_deep_research.search_system_factory import (
- create_strategy,
- )
-
- strategy = create_strategy(
- strategy_name="iterative-refinement",
- model=strategy_mock_llm,
- search=strategy_mock_search,
- settings_snapshot=strategy_settings_snapshot,
- )
-
- result = strategy.analyze_topic("Question to refine iteratively")
-
- assert isinstance(result, dict)
- logger.info(f"Iterative refinement keys: {list(result.keys())}")
diff --git a/tests/test_search_system.py b/tests/test_search_system.py
index 0b6f9ffa97..803d189c30 100644
--- a/tests/test_search_system.py
+++ b/tests/test_search_system.py
@@ -138,106 +138,6 @@ def test_init_source_based_strategy(monkeypatch):
)
-def test_init_iterdrag_strategy(monkeypatch):
- """Test initialization with IterDRAG strategy."""
- # Set up mock LLM and search
- mock_llm_instance = Mock()
- mock_search_instance = Mock()
-
- # Mock get_llm and get_search from their actual modules
- monkeypatch.setattr(
- "local_deep_research.config.llm_config.get_llm",
- lambda **kwargs: mock_llm_instance,
- )
- monkeypatch.setattr(
- "local_deep_research.config.search_config.get_search",
- lambda llm_instance=None, **kwargs: mock_search_instance,
- )
-
- # Import after mocking
- from local_deep_research.search_system import AdvancedSearchSystem
-
- # Create with IterDRAG strategy
- system = AdvancedSearchSystem(
- llm=mock_llm_instance,
- search=mock_search_instance,
- strategy_name="iterdrag",
- )
-
- # Check if the correct strategy type was created
- assert "IterDRAGStrategy" in system.strategy.__class__.__name__
-
-
-def test_init_parallel_strategy(monkeypatch):
- """Test initialization with parallel strategy."""
- # Set up mock LLM and search
- mock_llm_instance = Mock()
- mock_search_instance = Mock()
-
- # Mock get_llm and get_search from their actual modules
- monkeypatch.setattr(
- "local_deep_research.config.llm_config.get_llm",
- lambda **kwargs: mock_llm_instance,
- )
- monkeypatch.setattr(
- "local_deep_research.config.search_config.get_search",
- lambda llm_instance=None, **kwargs: mock_search_instance,
- )
-
- # Import after mocking
- from local_deep_research.search_system import AdvancedSearchSystem
-
- # Create settings snapshot for the test
- settings_snapshot = {
- "search.cross_engine_max_results": {"value": 100, "type": "int"},
- "search.cross_engine_use_reddit": {"value": False, "type": "bool"},
- "search.cross_engine_min_date": {"value": None, "type": "str"},
- "search.iterations": {"value": 2, "type": "int"},
- "search.questions_per_iteration": {"value": 3, "type": "int"},
- }
-
- # Create with parallel strategy
- system = AdvancedSearchSystem(
- llm=mock_llm_instance,
- search=mock_search_instance,
- strategy_name="parallel",
- settings_snapshot=settings_snapshot,
- )
-
- # Check if the correct strategy type was created
- assert "ParallelSearchStrategy" in system.strategy.__class__.__name__
-
-
-def test_init_rapid_strategy(monkeypatch):
- """Test initialization with rapid strategy."""
- # Set up mock LLM and search
- mock_llm_instance = Mock()
- mock_search_instance = Mock()
-
- # Mock get_llm and get_search from their actual modules
- monkeypatch.setattr(
- "local_deep_research.config.llm_config.get_llm",
- lambda **kwargs: mock_llm_instance,
- )
- monkeypatch.setattr(
- "local_deep_research.config.search_config.get_search",
- lambda llm_instance=None, **kwargs: mock_search_instance,
- )
-
- # Import after mocking
- from local_deep_research.search_system import AdvancedSearchSystem
-
- # Create with rapid strategy
- system = AdvancedSearchSystem(
- llm=mock_llm_instance,
- search=mock_search_instance,
- strategy_name="rapid",
- )
-
- # Check if the correct strategy type was created
- assert "RapidSearchStrategy" in system.strategy.__class__.__name__
-
-
def test_init_invalid_strategy(monkeypatch):
"""Test initialization with invalid strategy (should default to source-based)."""
# Set up mock LLM and search
diff --git a/tests/test_search_system_factory.py b/tests/test_search_system_factory.py
index 18e152ee49..2fa4e82388 100644
--- a/tests/test_search_system_factory.py
+++ b/tests/test_search_system_factory.py
@@ -151,9 +151,7 @@ class TestStrategyRegistryConsistency:
)
# Known issues with some strategies (pre-existing bugs)
- known_issues = {
- "iterative": "IterativeReasoningStrategy doesn't accept settings_snapshot",
- }
+ known_issues = {}
for strategy_info in AVAILABLE_STRATEGIES:
name = strategy_info["name"]
diff --git a/tests/test_search_system_factory_high_value.py b/tests/test_search_system_factory_high_value.py
index 9ce8f5eed3..cd99dd04c2 100644
--- a/tests/test_search_system_factory_high_value.py
+++ b/tests/test_search_system_factory_high_value.py
@@ -7,7 +7,6 @@ without importing any strategy classes.
import pytest
from local_deep_research.search_system_factory import (
- ALL_STRATEGIES,
AVAILABLE_STRATEGIES,
_get_setting,
get_available_strategies,
@@ -21,7 +20,7 @@ class TestAvailableStrategiesList:
assert isinstance(AVAILABLE_STRATEGIES, list)
def test_expected_count(self):
- assert len(AVAILABLE_STRATEGIES) == 5
+ assert len(AVAILABLE_STRATEGIES) == 6
def test_all_entries_are_dicts(self):
for entry in AVAILABLE_STRATEGIES:
@@ -51,6 +50,7 @@ class TestAvailableStrategiesList:
"source-based",
"focused-iteration",
"focused-iteration-standard",
+ "topic-organization",
"mcp",
"langgraph-agent",
],
@@ -100,35 +100,6 @@ class TestGetAvailableStrategies:
assert len(AVAILABLE_STRATEGIES) == original_len
-class TestAllStrategiesList:
- """Tests for the ALL_STRATEGIES list (show_all=True)."""
-
- def test_all_contains_more_than_available(self):
- assert len(ALL_STRATEGIES) > len(AVAILABLE_STRATEGIES)
-
- def test_all_starts_with_available(self):
- """ALL_STRATEGIES should begin with AVAILABLE_STRATEGIES entries."""
- for i, entry in enumerate(AVAILABLE_STRATEGIES):
- assert ALL_STRATEGIES[i]["name"] == entry["name"]
-
- def test_all_entries_have_required_keys(self):
- for entry in ALL_STRATEGIES:
- assert set(entry.keys()) == {"name", "label", "description"}
-
- def test_no_duplicate_names_in_all(self):
- names = [entry["name"] for entry in ALL_STRATEGIES]
- assert len(names) == len(set(names))
-
- def test_get_available_show_all_returns_all(self):
- result = get_available_strategies(show_all=True)
- assert result == ALL_STRATEGIES
-
- def test_get_available_default_returns_subset(self):
- result = get_available_strategies()
- assert result == AVAILABLE_STRATEGIES
- assert len(result) < len(ALL_STRATEGIES)
-
-
class TestGetSetting:
"""Tests for _get_setting() helper function."""
diff --git a/tests/web/routes/test_metrics_routes.py b/tests/web/routes/test_metrics_routes.py
index 2164a99a80..0e0e8f0edb 100644
--- a/tests/web/routes/test_metrics_routes.py
+++ b/tests/web/routes/test_metrics_routes.py
@@ -688,12 +688,12 @@ class TestGetAvailableStrategies:
get_available_strategies,
)
- strategies = get_available_strategies(show_all=True)
+ strategies = get_available_strategies()
strategy_names = [s["name"] for s in strategies]
assert "source-based" in strategy_names
assert "focused-iteration" in strategy_names
- assert "iterative-refinement" in strategy_names
+ assert "topic-organization" in strategy_names
class TestApiResearchJournals:
diff --git a/tests/web/routes/test_metrics_routes_coverage.py b/tests/web/routes/test_metrics_routes_coverage.py
index cb5e44de31..dcbcfd10e1 100644
--- a/tests/web/routes/test_metrics_routes_coverage.py
+++ b/tests/web/routes/test_metrics_routes_coverage.py
@@ -228,22 +228,22 @@ class TestExtractDomain:
class TestGetAvailableStrategies:
def test_returns_list(self):
- result = get_available_strategies(show_all=True)
+ result = get_available_strategies()
assert isinstance(result, list)
- assert len(result) >= 7
+ assert len(result) == 6
def test_each_strategy_has_name_and_description(self):
- for s in get_available_strategies(show_all=True):
+ for s in get_available_strategies():
assert "name" in s
assert "description" in s
def test_source_based_strategy_present(self):
- names = [s["name"] for s in get_available_strategies(show_all=True)]
+ names = [s["name"] for s in get_available_strategies()]
assert "source-based" in names
- def test_iterative_refinement_strategy_present(self):
- names = [s["name"] for s in get_available_strategies(show_all=True)]
- assert "iterative-refinement" in names
+ def test_topic_organization_strategy_present(self):
+ names = [s["name"] for s in get_available_strategies()]
+ assert "topic-organization" in names
# =========================================================================