Coverage for little_loops / issue_discovery / search.py: 76%
155 statements
« prev ^ index » next coverage.py v7.12.0, created at 2026-03-04 01:17 -0600
« prev ^ index » next coverage.py v7.12.0, created at 2026-03-04 01:17 -0600
1"""Issue file search and main discovery functions."""
3from __future__ import annotations
5import re
6import subprocess
7from datetime import datetime
8from pathlib import Path
9from typing import TYPE_CHECKING
11from little_loops.issue_discovery.extraction import (
12 _build_reopen_section,
13 detect_regression_or_duplicate,
14)
15from little_loops.issue_discovery.matching import (
16 FindingMatch,
17 MatchClassification,
18 RegressionEvidence,
19 _calculate_word_overlap,
20 _extract_words,
21 _matches_issue_type,
22)
24if TYPE_CHECKING:
25 from little_loops.config import BRConfig
26 from little_loops.logger import Logger
29# =============================================================================
30# Issue Search Functions
31# =============================================================================
34def _get_all_issue_files(
35 config: BRConfig,
36 include_completed: bool = True,
37 include_deferred: bool = False,
38) -> list[tuple[Path, bool]]:
39 """Get all issue files with their completion status.
41 Args:
42 config: Project configuration
43 include_completed: Whether to include completed issues
44 include_deferred: Whether to include deferred issues
46 Returns:
47 List of (path, is_completed) tuples.
48 For deferred issues, is_completed is set to True (non-active).
49 """
50 files: list[tuple[Path, bool]] = []
52 # Active issues
53 for category in config.issue_categories:
54 issue_dir = config.get_issue_dir(category)
55 if issue_dir.exists():
56 for f in issue_dir.glob("*.md"):
57 files.append((f, False))
59 # Completed issues
60 if include_completed:
61 completed_dir = config.get_completed_dir()
62 if completed_dir.exists():
63 for f in completed_dir.glob("*.md"):
64 files.append((f, True))
66 # Deferred issues
67 if include_deferred:
68 deferred_dir = config.get_deferred_dir()
69 if deferred_dir.exists():
70 for f in deferred_dir.glob("*.md"):
71 files.append((f, True))
73 return files
76def search_issues_by_content(
77 config: BRConfig,
78 search_terms: list[str],
79 include_completed: bool = True,
80) -> list[tuple[Path, float, bool]]:
81 """Search issues by content with relevance scoring.
83 Args:
84 config: Project configuration
85 search_terms: Terms to search for
86 include_completed: Whether to include completed issues
88 Returns:
89 List of (path, score, is_completed) sorted by score descending
90 """
91 results: list[tuple[Path, float, bool]] = []
92 search_words = set()
93 for term in search_terms:
94 search_words.update(_extract_words(term))
96 if not search_words:
97 return results
99 for issue_path, is_completed in _get_all_issue_files(config, include_completed):
100 try:
101 content = issue_path.read_text(encoding="utf-8")
102 content_words = _extract_words(content)
103 score = _calculate_word_overlap(search_words, content_words)
104 if score > 0.1: # Minimum threshold
105 results.append((issue_path, score, is_completed))
106 except Exception:
107 continue
109 results.sort(key=lambda x: x[1], reverse=True)
110 return results
113def search_issues_by_file_path(
114 config: BRConfig,
115 file_path: str,
116 include_completed: bool = True,
117) -> list[tuple[Path, bool]]:
118 """Search for issues mentioning a specific file path.
120 Args:
121 config: Project configuration
122 file_path: File path to search for
123 include_completed: Whether to include completed issues
125 Returns:
126 List of (issue_path, is_completed) tuples
127 """
128 results: list[tuple[Path, bool]] = []
129 normalized_path = file_path.strip().lower()
131 # Also match partial paths (e.g., "module.py" matches "src/module.py")
132 path_parts = normalized_path.split("/")
133 filename = path_parts[-1] if path_parts else normalized_path
135 for issue_path, is_completed in _get_all_issue_files(config, include_completed):
136 try:
137 content = issue_path.read_text(encoding="utf-8").lower()
138 # Check for exact path or filename match
139 if normalized_path in content or filename in content:
140 results.append((issue_path, is_completed))
141 except Exception:
142 continue
144 return results
147# =============================================================================
148# Main Discovery Functions
149# =============================================================================
152def find_existing_issue(
153 config: BRConfig,
154 finding_type: str,
155 file_path: str | None,
156 finding_title: str,
157 finding_content: str,
158) -> FindingMatch:
159 """Search for an existing issue matching this finding.
161 Uses a multi-pass approach:
162 1. Exact file path match in Location sections
163 2. Title word overlap (>70% = likely duplicate)
164 3. Content overlap analysis
166 For matches to completed issues, performs regression analysis to determine
167 if the match is a regression (fix broke) or invalid fix (never worked).
169 Args:
170 config: Project configuration
171 finding_type: Issue type ("BUG", "ENH", "FEAT")
172 file_path: File path from finding (if any)
173 finding_title: Title of the finding
174 finding_content: Full content/description of finding
176 Returns:
177 FindingMatch with best match details, including classification and
178 regression evidence for completed issue matches
179 """
180 best_match = FindingMatch(
181 issue_path=None,
182 match_type="none",
183 match_score=0.0,
184 )
186 # Pass 1: Exact file path match
187 if file_path:
188 path_matches = search_issues_by_file_path(config, file_path)
189 for issue_path, is_completed in path_matches:
190 try:
191 content = issue_path.read_text(encoding="utf-8")
192 # Check if same type of finding (uses configured categories)
193 issue_type_match = _matches_issue_type(
194 finding_type, issue_path, config, is_completed
195 )
196 if issue_type_match:
197 # Determine classification
198 if is_completed:
199 classification, evidence = detect_regression_or_duplicate(
200 config, issue_path
201 )
202 else:
203 classification = MatchClassification.DUPLICATE
204 evidence = None
206 # High confidence if same file + same type
207 return FindingMatch(
208 issue_path=issue_path,
209 match_type="exact",
210 match_score=0.85,
211 is_completed=is_completed,
212 matched_terms=[file_path],
213 classification=classification,
214 regression_evidence=evidence,
215 )
216 except Exception:
217 continue
219 # Pass 2: Title similarity
220 title_words = _extract_words(finding_title)
221 if title_words:
222 for issue_path, is_completed in _get_all_issue_files(config):
223 try:
224 # Extract title from issue file
225 content = issue_path.read_text(encoding="utf-8")
226 title_match = re.search(r"^#\s+[\w-]+:\s*(.+)$", content, re.MULTILINE)
227 if title_match:
228 issue_title = title_match.group(1)
229 issue_words = _extract_words(issue_title)
230 overlap = _calculate_word_overlap(title_words, issue_words)
231 if overlap > 0.7 and overlap > best_match.match_score:
232 # Determine classification
233 if is_completed:
234 classification, evidence = detect_regression_or_duplicate(
235 config, issue_path
236 )
237 else:
238 classification = MatchClassification.DUPLICATE
239 evidence = None
241 best_match = FindingMatch(
242 issue_path=issue_path,
243 match_type="similar",
244 match_score=overlap,
245 is_completed=is_completed,
246 matched_terms=list(title_words & issue_words),
247 classification=classification,
248 regression_evidence=evidence,
249 )
250 except Exception:
251 continue
253 # Pass 3: Content analysis
254 if best_match.match_score < 0.5:
255 content_matches = search_issues_by_content(
256 config,
257 [finding_title, finding_content],
258 )
259 for issue_path, score, is_completed in content_matches[:5]: # Top 5
260 adjusted_score = score * 0.8 # Content matches are less precise
261 if adjusted_score > best_match.match_score:
262 # Determine classification
263 if is_completed:
264 classification, evidence = detect_regression_or_duplicate(config, issue_path)
265 else:
266 classification = MatchClassification.DUPLICATE
267 evidence = None
269 best_match = FindingMatch(
270 issue_path=issue_path,
271 match_type="content",
272 match_score=adjusted_score,
273 is_completed=is_completed,
274 classification=classification,
275 regression_evidence=evidence,
276 )
278 # If no match found, classification is NEW_ISSUE (the default)
279 return best_match
282# =============================================================================
283# Issue Reopening and Updating
284# =============================================================================
287def _get_category_from_issue_path(issue_path: Path, config: BRConfig) -> str:
288 """Determine the category for an issue based on its filename.
290 Args:
291 issue_path: Path to issue file
292 config: Project configuration
294 Returns:
295 Category name (e.g., "bugs", "enhancements", "features")
296 """
297 filename = issue_path.name.upper()
298 for category_name, category_config in config.issues.categories.items():
299 if category_config.prefix in filename:
300 return category_name
301 return "bugs" # Default
304def reopen_issue(
305 config: BRConfig,
306 completed_issue_path: Path,
307 reopen_reason: str,
308 new_context: str,
309 source_command: str,
310 logger: Logger,
311 classification: MatchClassification | None = None,
312 regression_evidence: RegressionEvidence | None = None,
313) -> Path | None:
314 """Move issue from completed back to active with Reopened section.
316 Args:
317 config: Project configuration
318 completed_issue_path: Path to issue in completed/
319 reopen_reason: Reason for reopening
320 new_context: New context/findings to add
321 source_command: Command triggering the reopen
322 logger: Logger for output
323 classification: How this issue was classified (regression, invalid_fix, etc.)
324 regression_evidence: Evidence supporting the classification
326 Returns:
327 New path to reopened issue, or None if failed
328 """
329 if not completed_issue_path.exists():
330 logger.error(f"Completed issue not found: {completed_issue_path}")
331 return None
333 # Determine target category directory
334 category = _get_category_from_issue_path(completed_issue_path, config)
335 target_dir = config.get_issue_dir(category)
336 target_dir.mkdir(parents=True, exist_ok=True)
338 target_path = target_dir / completed_issue_path.name
340 # Safety check - don't overwrite existing active issue
341 if target_path.exists():
342 logger.warning(f"Active issue already exists: {target_path}")
343 return None
345 # Log with classification info if available
346 if classification == MatchClassification.REGRESSION:
347 logger.info(f"Reopening {completed_issue_path.name} as REGRESSION -> {category}/")
348 elif classification == MatchClassification.INVALID_FIX:
349 logger.info(f"Reopening {completed_issue_path.name} as INVALID_FIX -> {category}/")
350 else:
351 logger.info(f"Reopening {completed_issue_path.name} -> {category}/")
353 try:
354 # Read and update content
355 content = completed_issue_path.read_text(encoding="utf-8")
357 # Add reopened section with classification info
358 reopen_section = _build_reopen_section(
359 reopen_reason,
360 new_context,
361 source_command,
362 classification,
363 regression_evidence,
364 )
365 content += reopen_section
367 # Try git mv first for history preservation
368 result = subprocess.run(
369 ["git", "mv", str(completed_issue_path), str(target_path)],
370 capture_output=True,
371 text=True,
372 )
374 if result.returncode != 0:
375 # Fall back to manual copy
376 logger.warning(f"git mv failed, using manual copy: {result.stderr}")
377 target_path.write_text(content, encoding="utf-8")
378 completed_issue_path.unlink()
379 else:
380 # Write updated content
381 target_path.write_text(content, encoding="utf-8")
383 logger.success(f"Reopened: {target_path.name}")
384 return target_path
386 except Exception as e:
387 logger.error(f"Failed to reopen issue: {e}")
388 return None
391def update_existing_issue(
392 config: BRConfig,
393 issue_path: Path,
394 update_section_name: str,
395 update_content: str,
396 source_command: str,
397 logger: Logger,
398) -> bool:
399 """Add new findings to an existing issue.
401 Args:
402 config: Project configuration
403 issue_path: Path to issue file
404 update_section_name: Name for the update section
405 update_content: Content to add
406 source_command: Command triggering the update
407 logger: Logger for output
409 Returns:
410 True if update succeeded
411 """
412 if not issue_path.exists():
413 logger.error(f"Issue not found: {issue_path}")
414 return False
416 try:
417 content = issue_path.read_text(encoding="utf-8")
419 # Build update section
420 update_section = f"""
422---
424## {update_section_name}
426- **Date**: {datetime.now().strftime("%Y-%m-%d")}
427- **Source**: {source_command}
429{update_content}
430"""
432 # Check if section already exists
433 if f"## {update_section_name}" not in content:
434 content += update_section
435 issue_path.write_text(content, encoding="utf-8")
436 logger.success(f"Updated: {issue_path.name}")
437 else:
438 logger.info(f"Section already exists in {issue_path.name}, skipping")
440 return True
442 except Exception as e:
443 logger.error(f"Failed to update issue: {e}")
444 return False