Coverage for little_loops / issue_discovery / search.py: 0%
167 statements
« prev ^ index » next coverage.py v7.12.0, created at 2026-03-14 23:20 -0500
« prev ^ index » next coverage.py v7.12.0, created at 2026-03-14 23:20 -0500
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 best_pass2: tuple[Path, bool, float, list[str]] | None = None
223 best_pass2_score = best_match.match_score
224 for issue_path, is_completed in _get_all_issue_files(config):
225 try:
226 # Extract title from issue file
227 content = issue_path.read_text(encoding="utf-8")
228 title_match = re.search(r"^#\s+[\w-]+:\s*(.+)$", content, re.MULTILINE)
229 if title_match:
230 issue_title = title_match.group(1)
231 issue_words = _extract_words(issue_title)
232 overlap = _calculate_word_overlap(title_words, issue_words)
233 if overlap > 0.7 and overlap > best_pass2_score:
234 best_pass2_score = overlap
235 best_pass2 = (
236 issue_path,
237 is_completed,
238 overlap,
239 list(title_words & issue_words),
240 )
241 except Exception:
242 continue
244 # Determine classification once for the single best Pass 2 match
245 if best_pass2 is not None:
246 issue_path, is_completed, overlap, matched_terms = best_pass2
247 if is_completed:
248 classification, evidence = detect_regression_or_duplicate(config, issue_path)
249 else:
250 classification = MatchClassification.DUPLICATE
251 evidence = None
252 best_match = FindingMatch(
253 issue_path=issue_path,
254 match_type="similar",
255 match_score=overlap,
256 is_completed=is_completed,
257 matched_terms=matched_terms,
258 classification=classification,
259 regression_evidence=evidence,
260 )
262 # Pass 3: Content analysis
263 if best_match.match_score < 0.5:
264 content_matches = search_issues_by_content(
265 config,
266 [finding_title, finding_content],
267 )
268 best_pass3: tuple[Path, bool, float] | None = None
269 best_pass3_score = best_match.match_score
270 for issue_path, score, is_completed in content_matches[:5]: # Top 5
271 adjusted_score = score * 0.8 # Content matches are less precise
272 if adjusted_score > best_pass3_score:
273 best_pass3_score = adjusted_score
274 best_pass3 = (issue_path, is_completed, adjusted_score)
276 # Determine classification once for the single best Pass 3 match
277 if best_pass3 is not None:
278 issue_path, is_completed, adjusted_score = best_pass3
279 if is_completed:
280 classification, evidence = detect_regression_or_duplicate(config, issue_path)
281 else:
282 classification = MatchClassification.DUPLICATE
283 evidence = None
284 best_match = FindingMatch(
285 issue_path=issue_path,
286 match_type="content",
287 match_score=adjusted_score,
288 is_completed=is_completed,
289 classification=classification,
290 regression_evidence=evidence,
291 )
293 # If no match found, classification is NEW_ISSUE (the default)
294 return best_match
297# =============================================================================
298# Issue Reopening and Updating
299# =============================================================================
302def _get_category_from_issue_path(issue_path: Path, config: BRConfig) -> str:
303 """Determine the category for an issue based on its filename.
305 Args:
306 issue_path: Path to issue file
307 config: Project configuration
309 Returns:
310 Category name (e.g., "bugs", "enhancements", "features")
311 """
312 filename = issue_path.name.upper()
313 for category_name, category_config in config.issues.categories.items():
314 if category_config.prefix in filename:
315 return category_name
316 return "bugs" # Default
319def reopen_issue(
320 config: BRConfig,
321 completed_issue_path: Path,
322 reopen_reason: str,
323 new_context: str,
324 source_command: str,
325 logger: Logger,
326 classification: MatchClassification | None = None,
327 regression_evidence: RegressionEvidence | None = None,
328) -> Path | None:
329 """Move issue from completed back to active with Reopened section.
331 Args:
332 config: Project configuration
333 completed_issue_path: Path to issue in completed/
334 reopen_reason: Reason for reopening
335 new_context: New context/findings to add
336 source_command: Command triggering the reopen
337 logger: Logger for output
338 classification: How this issue was classified (regression, invalid_fix, etc.)
339 regression_evidence: Evidence supporting the classification
341 Returns:
342 New path to reopened issue, or None if failed
343 """
344 if not completed_issue_path.exists():
345 logger.error(f"Completed issue not found: {completed_issue_path}")
346 return None
348 # Determine target category directory
349 category = _get_category_from_issue_path(completed_issue_path, config)
350 target_dir = config.get_issue_dir(category)
351 target_dir.mkdir(parents=True, exist_ok=True)
353 target_path = target_dir / completed_issue_path.name
355 # Safety check - don't overwrite existing active issue
356 if target_path.exists():
357 logger.warning(f"Active issue already exists: {target_path}")
358 return None
360 # Log with classification info if available
361 if classification == MatchClassification.REGRESSION:
362 logger.info(f"Reopening {completed_issue_path.name} as REGRESSION -> {category}/")
363 elif classification == MatchClassification.INVALID_FIX:
364 logger.info(f"Reopening {completed_issue_path.name} as INVALID_FIX -> {category}/")
365 else:
366 logger.info(f"Reopening {completed_issue_path.name} -> {category}/")
368 try:
369 # Read and update content
370 content = completed_issue_path.read_text(encoding="utf-8")
372 # Add reopened section with classification info
373 reopen_section = _build_reopen_section(
374 reopen_reason,
375 new_context,
376 source_command,
377 classification,
378 regression_evidence,
379 )
380 content += reopen_section
382 # Try git mv first for history preservation
383 result = subprocess.run(
384 ["git", "mv", str(completed_issue_path), str(target_path)],
385 capture_output=True,
386 text=True,
387 )
389 if result.returncode != 0:
390 # Fall back to manual copy
391 logger.warning(f"git mv failed, using manual copy: {result.stderr}")
392 target_path.write_text(content, encoding="utf-8")
393 completed_issue_path.unlink()
394 else:
395 # Write updated content
396 target_path.write_text(content, encoding="utf-8")
398 logger.success(f"Reopened: {target_path.name}")
399 return target_path
401 except Exception as e:
402 logger.error(f"Failed to reopen issue: {e}")
403 return None
406def update_existing_issue(
407 config: BRConfig,
408 issue_path: Path,
409 update_section_name: str,
410 update_content: str,
411 source_command: str,
412 logger: Logger,
413) -> bool:
414 """Add new findings to an existing issue.
416 Args:
417 config: Project configuration
418 issue_path: Path to issue file
419 update_section_name: Name for the update section
420 update_content: Content to add
421 source_command: Command triggering the update
422 logger: Logger for output
424 Returns:
425 True if update succeeded
426 """
427 if not issue_path.exists():
428 logger.error(f"Issue not found: {issue_path}")
429 return False
431 try:
432 content = issue_path.read_text(encoding="utf-8")
434 # Build update section
435 update_section = f"""
437---
439## {update_section_name}
441- **Date**: {datetime.now().strftime("%Y-%m-%d")}
442- **Source**: {source_command}
444{update_content}
445"""
447 # Check if section already exists
448 if f"## {update_section_name}" not in content:
449 content += update_section
450 issue_path.write_text(content, encoding="utf-8")
451 logger.success(f"Updated: {issue_path.name}")
452 else:
453 logger.info(f"Section already exists in {issue_path.name}, skipping")
455 return True
457 except Exception as e:
458 logger.error(f"Failed to update issue: {e}")
459 return False