Coverage for little_loops / issue_history / parsing.py: 0%

155 statements  

« prev     ^ index     » next       coverage.py v7.12.0, created at 2026-04-02 13:03 -0500

1"""Issue history parsing and scanning functions. 

2 

3Provides functions to parse completed issue files, extract metadata 

4from frontmatter and content, scan directories for issues, and 

5extract file paths from issue content. 

6""" 

7 

8from __future__ import annotations 

9 

10import logging 

11import re 

12from datetime import date 

13from pathlib import Path 

14from typing import Any 

15 

16from little_loops.frontmatter import parse_frontmatter 

17from little_loops.issue_history.models import CompletedIssue 

18from little_loops.text_utils import extract_file_paths 

19 

20logger = logging.getLogger(__name__) 

21 

22 

23def parse_completed_issue(file_path: Path) -> CompletedIssue: 

24 """Parse a completed issue file. 

25 

26 Args: 

27 file_path: Path to the issue markdown file 

28 

29 Returns: 

30 CompletedIssue with parsed metadata 

31 """ 

32 filename = file_path.name 

33 content = file_path.read_text(encoding="utf-8") 

34 

35 # Extract from filename: P[0-5]-[TYPE]-[NNN]-description.md 

36 issue_type = "UNKNOWN" 

37 priority = "P5" 

38 issue_id = "UNKNOWN" 

39 

40 # Match priority 

41 priority_match = re.match(r"^(P\d)", filename) 

42 if priority_match: 

43 priority = priority_match.group(1) 

44 

45 # Match type and ID 

46 type_match = re.search(r"(BUG|ENH|FEAT)-(\d+)", filename) 

47 if type_match: 

48 issue_type = type_match.group(1) 

49 issue_id = f"{type_match.group(1)}-{type_match.group(2)}" 

50 

51 # Parse frontmatter once for discovered_by and discovered_date 

52 fm = parse_frontmatter(content) 

53 discovered_by = _parse_discovered_by(fm) 

54 discovered_date = _parse_discovered_date(fm) 

55 

56 # Parse completion date from Resolution section or file mtime 

57 completed_date = _parse_completion_date(content, file_path) 

58 

59 return CompletedIssue( 

60 path=file_path, 

61 issue_type=issue_type, 

62 priority=priority, 

63 issue_id=issue_id, 

64 discovered_by=discovered_by, 

65 discovered_date=discovered_date, 

66 completed_date=completed_date, 

67 ) 

68 

69 

70def _parse_discovered_by(fm: dict[str, Any]) -> str | None: 

71 """Extract discovered_by from parsed frontmatter. 

72 

73 Args: 

74 fm: Parsed frontmatter dictionary 

75 

76 Returns: 

77 discovered_by value or None 

78 """ 

79 value = fm.get("discovered_by") 

80 return value if isinstance(value, str) else None 

81 

82 

83def _parse_completion_date(content: str, file_path: Path) -> date | None: 

84 """Extract completion date from Resolution section or file mtime. 

85 

86 Args: 

87 content: File content 

88 file_path: Path for mtime fallback 

89 

90 Returns: 

91 Completion date or None 

92 """ 

93 # Try Resolution section: **Completed**: YYYY-MM-DD 

94 match = re.search(r"\*\*Completed\*\*:\s*(\d{4}-\d{2}-\d{2})", content) 

95 if match: 

96 try: 

97 return date.fromisoformat(match.group(1)) 

98 except ValueError: 

99 pass 

100 

101 # Fallback to file mtime 

102 try: 

103 mtime = file_path.stat().st_mtime 

104 return date.fromtimestamp(mtime) 

105 except OSError: 

106 return None 

107 

108 

109def _parse_resolution_action(content: str) -> str: 

110 """Extract resolution action category from issue content. 

111 

112 Categorizes based on Resolution section fields: 

113 - "completed": Normal completion with **Action**: fix/implement 

114 - "rejected": Explicitly rejected (out of scope, not valid) 

115 - "invalid": Invalid reference or spec 

116 - "duplicate": Duplicate of existing issue 

117 - "deferred": Deferred to future work 

118 

119 Args: 

120 content: Issue file content 

121 

122 Returns: 

123 Resolution category string 

124 """ 

125 # Look for Status field patterns 

126 status_match = re.search(r"\*\*Status\*\*:\s*(.+?)(?:\n|$)", content) 

127 if status_match: 

128 status = status_match.group(1).strip().lower() 

129 if "closed" in status: 

130 # Check Reason field for specific category 

131 reason_match = re.search(r"\*\*Reason\*\*:\s*(.+?)(?:\n|$)", content) 

132 if reason_match: 

133 reason = reason_match.group(1).strip().lower() 

134 if "duplicate" in reason: 

135 return "duplicate" 

136 if "invalid" in reason: 

137 return "invalid" 

138 if "deferred" in reason: 

139 return "deferred" 

140 if "rejected" in reason or "out of scope" in reason: 

141 return "rejected" 

142 # Generic closed without specific reason 

143 return "rejected" 

144 

145 # Check for Action field (normal completion) 

146 action_match = re.search(r"\*\*Action\*\*:\s*(.+?)(?:\n|$)", content) 

147 if action_match: 

148 return "completed" 

149 

150 # Default to completed if no resolution section 

151 return "completed" 

152 

153 

154def _detect_processing_agent(content: str, discovered_source: str | None = None) -> str: 

155 """Detect which processing agent handled an issue. 

156 

157 Detection strategy (in priority order): 

158 1. Check discovered_source field for 'll-parallel' or 'll-auto' 

159 2. Check content for '**Log Type**:' field 

160 3. Check content for '**Tool**:' field 

161 4. Default to 'manual' 

162 

163 Args: 

164 content: Issue file content 

165 discovered_source: Optional discovered_source frontmatter value 

166 

167 Returns: 

168 Agent name: 'll-auto', 'll-parallel', or 'manual' 

169 """ 

170 # Check discovered_source first 

171 if discovered_source: 

172 source_lower = discovered_source.lower() 

173 if "ll-parallel" in source_lower: 

174 return "ll-parallel" 

175 if "ll-auto" in source_lower: 

176 return "ll-auto" 

177 

178 # Check Log Type field 

179 log_type_match = re.search(r"\*\*Log Type\*\*:\s*(.+?)(?:\n|$)", content) 

180 if log_type_match: 

181 log_type = log_type_match.group(1).strip().lower() 

182 if "ll-parallel" in log_type: 

183 return "ll-parallel" 

184 if "ll-auto" in log_type: 

185 return "ll-auto" 

186 

187 # Check Tool field 

188 tool_match = re.search(r"\*\*Tool\*\*:\s*(.+?)(?:\n|$)", content) 

189 if tool_match: 

190 tool = tool_match.group(1).strip().lower() 

191 if "ll-parallel" in tool: 

192 return "ll-parallel" 

193 if "ll-auto" in tool: 

194 return "ll-auto" 

195 

196 # Default to manual 

197 return "manual" 

198 

199 

200def scan_completed_issues(completed_dir: Path) -> list[CompletedIssue]: 

201 """Scan completed directory for issue files. 

202 

203 Args: 

204 completed_dir: Path to .issues/completed/ 

205 

206 Returns: 

207 List of parsed CompletedIssue objects 

208 """ 

209 issues: list[CompletedIssue] = [] 

210 

211 if not completed_dir.exists(): 

212 return issues 

213 

214 for file_path in sorted(completed_dir.glob("*.md")): 

215 try: 

216 issue = parse_completed_issue(file_path) 

217 issues.append(issue) 

218 except Exception as e: 

219 logger.warning("Failed to parse %s: %s", file_path, e) 

220 continue 

221 

222 return issues 

223 

224 

225def _parse_discovered_date(fm: dict[str, Any]) -> date | None: 

226 """Extract discovered_date from parsed frontmatter. 

227 

228 Args: 

229 fm: Parsed frontmatter dictionary 

230 

231 Returns: 

232 discovered_date value or None 

233 """ 

234 value = fm.get("discovered_date") 

235 if not isinstance(value, str): 

236 return None 

237 try: 

238 return date.fromisoformat(value) 

239 except ValueError: 

240 return None 

241 

242 

243def _extract_subsystem(content: str) -> str | None: 

244 """Extract primary subsystem/directory from issue content. 

245 

246 Args: 

247 content: Issue file content 

248 

249 Returns: 

250 Directory path (e.g., "scripts/little_loops/") or None 

251 """ 

252 # Look for file paths in Location or common patterns 

253 patterns = [ 

254 r"\*\*File\*\*:\s*`?([^`\n]+/)[^/`\n]+`?", # **File**: path/to/file.py 

255 r"`([a-zA-Z_][\w/.-]+/)[^/`]+\.py`", # `path/to/file.py` 

256 ] 

257 

258 for pattern in patterns: 

259 match = re.search(pattern, content) 

260 if match: 

261 return match.group(1) 

262 

263 return None 

264 

265 

266def _extract_paths_from_issue(content: str) -> list[str]: 

267 """Extract all file paths from issue content. 

268 

269 Delegates to :func:`~little_loops.text_utils.extract_file_paths` 

270 and returns results as a sorted list for backward compatibility. 

271 

272 Args: 

273 content: Issue file content 

274 

275 Returns: 

276 Sorted list of file paths found in content 

277 """ 

278 return sorted(extract_file_paths(content)) 

279 

280 

281def _find_test_file(source_path: str, project_root: Path | None = None) -> str | None: 

282 """Find corresponding test file for a source file. 

283 

284 Checks common test file naming patterns: 

285 - tests/test_<name>.py 

286 - tests/<path>/test_<name>.py 

287 - <path>/test_<name>.py 

288 - <path>/<name>_test.py 

289 - <path>/tests/test_<name>.py 

290 

291 Args: 

292 source_path: Path to source file (e.g., "src/core/processor.py") 

293 project_root: Project root for anchoring existence checks. Defaults to CWD. 

294 

295 Returns: 

296 Path to test file if found, None otherwise 

297 """ 

298 if not source_path.endswith(".py"): 

299 return None # Only check Python files for now 

300 

301 path = Path(source_path) 

302 stem = path.stem # filename without extension 

303 parent = str(path.parent) if path.parent != Path(".") else "" 

304 

305 # Generate candidate test file paths 

306 candidates: list[str] = [ 

307 f"tests/test_{stem}.py", 

308 f"{parent}/test_{stem}.py" if parent else f"test_{stem}.py", 

309 f"{parent}/{stem}_test.py" if parent else f"{stem}_test.py", 

310 f"{parent}/tests/test_{stem}.py" if parent else f"tests/test_{stem}.py", 

311 ] 

312 

313 # Add path-aware test locations 

314 if parent: 

315 candidates.append(f"tests/{parent}/test_{stem}.py") 

316 

317 # Project-specific pattern for little-loops 

318 # e.g., scripts/little_loops/foo.py -> scripts/tests/test_foo.py 

319 if source_path.startswith("scripts/little_loops/"): 

320 candidates.append(f"scripts/tests/test_{stem}.py") 

321 

322 for candidate in candidates: 

323 if (project_root / candidate).exists() if project_root else Path(candidate).exists(): 

324 return candidate 

325 

326 return None 

327 

328 

329def scan_active_issues( 

330 issues_dir: Path, 

331 category_dirs: list[str] | None = None, 

332) -> list[tuple[Path, str, str, date | None]]: 

333 """Scan active issue directories. 

334 

335 Args: 

336 issues_dir: Path to .issues/ directory 

337 category_dirs: List of category subdirectory names to scan. When 

338 omitted, defaults to ``["bugs", "features", "enhancements"]`` for 

339 backward compatibility. Pass ``config.issue_categories`` to 

340 include custom project categories. 

341 

342 Returns: 

343 List of (path, issue_type, priority, discovered_date) tuples 

344 """ 

345 results: list[tuple[Path, str, str, date | None]] = [] 

346 

347 for category_dir in category_dirs or ["bugs", "features", "enhancements"]: 

348 category_path = issues_dir / category_dir 

349 if not category_path.exists(): 

350 continue 

351 

352 for file_path in category_path.glob("*.md"): 

353 filename = file_path.name 

354 

355 # Extract priority 

356 priority = "P5" 

357 priority_match = re.match(r"^(P\d)", filename) 

358 if priority_match: 

359 priority = priority_match.group(1) 

360 

361 # Extract type 

362 issue_type = "UNKNOWN" 

363 type_match = re.search(r"(BUG|ENH|FEAT)", filename) 

364 if type_match: 

365 issue_type = type_match.group(1) 

366 

367 # Extract discovered date from content 

368 discovered_date = None 

369 try: 

370 content = file_path.read_text(encoding="utf-8") 

371 fm = parse_frontmatter(content) 

372 discovered_date = _parse_discovered_date(fm) 

373 except Exception as e: 

374 logger.warning("Failed to parse %s: %s", file_path, e) 

375 

376 results.append((file_path, issue_type, priority, discovered_date)) 

377 

378 return results