Coverage for little_loops / issue_parser.py: 99%

219 statements  

« prev     ^ index     » next       coverage.py v7.12.0, created at 2026-03-04 01:17 -0600

1"""Issue file parsing for little-loops. 

2 

3Parses issue markdown files to extract metadata like priority, ID, type, and title. 

4""" 

5 

6from __future__ import annotations 

7 

8import logging 

9import re 

10from dataclasses import dataclass, field 

11from pathlib import Path 

12from typing import TYPE_CHECKING, Any 

13 

14from little_loops.frontmatter import parse_frontmatter 

15 

16if TYPE_CHECKING: 

17 from little_loops.config import BRConfig 

18 

19 

20logger = logging.getLogger(__name__) 

21 

22# Regex pattern for issue IDs in list items 

23# Matches: "- FEAT-001", "- BUG-123", "* ENH-005", "- FEAT-001 (some note)" 

24# Also handles bold markdown: "- **ENH-1000**: description" 

25ISSUE_ID_PATTERN = re.compile(r"^[-*]\s+\*{0,2}([A-Z]+-\d+)", re.MULTILINE) 

26 

27 

28_NORMALIZED_RE = re.compile(r"^P[0-5]-(BUG|FEAT|ENH)-[0-9]{3,}-[a-z0-9-]+\.md$") 

29 

30 

31def is_normalized(filename: str) -> bool: 

32 """Check whether an issue filename conforms to naming conventions. 

33 

34 Args: 

35 filename: The basename of the issue file (e.g. 'P2-BUG-010-my-issue.md'). 

36 

37 Returns: 

38 True if the filename matches ``^P[0-5]-(BUG|FEAT|ENH)-[0-9]{3,}-[a-z0-9-]+\\.md$``. 

39 """ 

40 return bool(_NORMALIZED_RE.match(filename)) 

41 

42 

43def slugify(text: str) -> str: 

44 """Convert text to slug format for filenames. 

45 

46 Args: 

47 text: Text to convert 

48 

49 Returns: 

50 Lowercase slug with hyphens 

51 """ 

52 text = re.sub(r"[^\w\s-]", "", text) 

53 text = re.sub(r"[-\s]+", "-", text) 

54 return text.strip("-").lower() 

55 

56 

57def get_next_issue_number(config: BRConfig, category: str | None = None) -> int: 

58 """Determine the next globally unique issue number. 

59 

60 Scans ALL issue directories (active and completed) to find the highest 

61 existing number across ALL issue types (BUG, FEAT, ENH). Issue numbers 

62 are globally unique regardless of type. 

63 

64 Args: 

65 config: Project configuration 

66 category: Unused, kept for backwards compatibility 

67 

68 Returns: 

69 Next available issue number (globally unique across all types) 

70 """ 

71 max_num = 0 

72 

73 # Get all known prefixes from configuration 

74 all_prefixes = [cat_config.prefix for cat_config in config.issues.categories.values()] 

75 

76 # Directories to scan: ALL category directories + completed + deferred 

77 dirs_to_scan = [config.get_completed_dir(), config.get_deferred_dir()] 

78 for cat_name in config.issues.categories: 

79 dirs_to_scan.append(config.get_issue_dir(cat_name)) 

80 

81 if not all_prefixes: 

82 return max_num + 1 

83 

84 # Pre-compile a single union regex to match any known prefix 

85 prefix_pattern = re.compile(r"(?:" + "|".join(re.escape(p) for p in all_prefixes) + r")-(\d+)") 

86 

87 for dir_path in dirs_to_scan: 

88 if not dir_path.exists(): 

89 continue 

90 for file in dir_path.glob("*.md"): 

91 match = prefix_pattern.search(file.name) 

92 if match: 

93 num = int(match.group(1)) 

94 if num > max_num: 

95 max_num = num 

96 

97 return max_num + 1 

98 

99 

100@dataclass 

101class ProductImpact: 

102 """Product impact assessment for an issue. 

103 

104 Attributes: 

105 goal_alignment: ID of the strategic priority this supports 

106 persona_impact: ID of the persona affected 

107 business_value: Business value assessment (high|medium|low) 

108 user_benefit: Description of how this helps the target user 

109 """ 

110 

111 goal_alignment: str | None = None 

112 persona_impact: str | None = None 

113 business_value: str | None = None # high|medium|low 

114 user_benefit: str | None = None 

115 

116 def to_dict(self) -> dict[str, Any]: 

117 """Convert to dictionary for JSON serialization.""" 

118 return { 

119 "goal_alignment": self.goal_alignment, 

120 "persona_impact": self.persona_impact, 

121 "business_value": self.business_value, 

122 "user_benefit": self.user_benefit, 

123 } 

124 

125 @classmethod 

126 def from_dict(cls, data: dict[str, Any] | None) -> ProductImpact | None: 

127 """Create ProductImpact from dictionary. 

128 

129 Args: 

130 data: Dictionary with product impact fields, or None 

131 

132 Returns: 

133 ProductImpact instance or None if data is None/empty 

134 """ 

135 if not data: 

136 return None 

137 return cls( 

138 goal_alignment=data.get("goal_alignment"), 

139 persona_impact=data.get("persona_impact"), 

140 business_value=data.get("business_value"), 

141 user_benefit=data.get("user_benefit"), 

142 ) 

143 

144 

145@dataclass 

146class IssueInfo: 

147 """Parsed information from an issue file. 

148 

149 Attributes: 

150 path: Path to the issue file 

151 issue_type: Type of issue (e.g., "bugs", "features") 

152 priority: Priority level (e.g., "P0", "P1") 

153 issue_id: Issue identifier (e.g., "BUG-123") 

154 title: Issue title from markdown header 

155 blocked_by: List of issue IDs that block this issue 

156 blocks: List of issue IDs that this issue blocks 

157 discovered_by: Source command/workflow that created this issue 

158 product_impact: Product impact assessment (optional) 

159 effort: Effort estimate (1=low, 2=medium, 3=high), inferred from priority if absent 

160 impact: Impact estimate (1=low, 2=medium, 3=high), inferred from priority if absent 

161 confidence_score: Readiness score (0-100) written by /ll:confidence-check, or None 

162 outcome_confidence: Outcome confidence (0-100) written by /ll:confidence-check, or None 

163 session_commands: Distinct /ll:* commands found in the ## Session Log section 

164 session_command_counts: Per-command occurrence counts from the ## Session Log section 

165 """ 

166 

167 path: Path 

168 issue_type: str 

169 priority: str 

170 issue_id: str 

171 title: str 

172 blocked_by: list[str] = field(default_factory=list) 

173 blocks: list[str] = field(default_factory=list) 

174 discovered_by: str | None = None 

175 product_impact: ProductImpact | None = None 

176 effort: int | None = None 

177 impact: int | None = None 

178 confidence_score: int | None = None 

179 outcome_confidence: int | None = None 

180 session_commands: list[str] = field(default_factory=list) 

181 session_command_counts: dict[str, int] = field(default_factory=dict) 

182 

183 @property 

184 def priority_int(self) -> int: 

185 """Convert priority to integer for comparison (lower = higher priority).""" 

186 # Support P0-P5 priorities 

187 match = re.match(r"^P(\d+)$", self.priority) 

188 if match: 

189 return int(match.group(1)) 

190 return 99 # Unknown priority sorts last 

191 

192 def to_dict(self) -> dict[str, Any]: 

193 """Convert to dictionary for JSON serialization.""" 

194 return { 

195 "path": str(self.path), 

196 "issue_type": self.issue_type, 

197 "priority": self.priority, 

198 "issue_id": self.issue_id, 

199 "title": self.title, 

200 "blocked_by": self.blocked_by, 

201 "blocks": self.blocks, 

202 "discovered_by": self.discovered_by, 

203 "product_impact": (self.product_impact.to_dict() if self.product_impact else None), 

204 "effort": self.effort, 

205 "impact": self.impact, 

206 "confidence_score": self.confidence_score, 

207 "outcome_confidence": self.outcome_confidence, 

208 "session_commands": self.session_commands, 

209 "session_command_counts": self.session_command_counts, 

210 } 

211 

212 @classmethod 

213 def from_dict(cls, data: dict[str, Any]) -> IssueInfo: 

214 """Create IssueInfo from dictionary.""" 

215 return cls( 

216 path=Path(data["path"]), 

217 issue_type=data["issue_type"], 

218 priority=data["priority"], 

219 issue_id=data["issue_id"], 

220 title=data["title"], 

221 blocked_by=data.get("blocked_by", []), 

222 blocks=data.get("blocks", []), 

223 discovered_by=data.get("discovered_by"), 

224 product_impact=ProductImpact.from_dict(data.get("product_impact")), 

225 effort=data.get("effort"), 

226 impact=data.get("impact"), 

227 confidence_score=data.get("confidence_score"), 

228 outcome_confidence=data.get("outcome_confidence"), 

229 session_commands=data.get("session_commands", []), 

230 session_command_counts=data.get("session_command_counts", {}), 

231 ) 

232 

233 

234class IssueParser: 

235 """Parses issue files based on project configuration. 

236 

237 Uses BRConfig to understand issue categories, prefixes, and priorities. 

238 """ 

239 

240 def __init__(self, config: BRConfig) -> None: 

241 """Initialize parser with project configuration. 

242 

243 Args: 

244 config: Project configuration 

245 """ 

246 self.config = config 

247 self._build_prefix_map() 

248 

249 def _build_prefix_map(self) -> None: 

250 """Build mapping from issue prefixes to category names.""" 

251 self._prefix_to_category: dict[str, str] = {} 

252 for category_name, category in self.config.issues.categories.items(): 

253 self._prefix_to_category[category.prefix] = category_name 

254 

255 def parse_file(self, issue_path: Path) -> IssueInfo: 

256 """Parse an issue file to extract metadata. 

257 

258 Args: 

259 issue_path: Path to the issue markdown file 

260 

261 Returns: 

262 Parsed IssueInfo 

263 """ 

264 filename = issue_path.name 

265 

266 # Parse priority from filename prefix (e.g., P1-BUG-123-...) 

267 priority = self._parse_priority(filename) 

268 

269 # Parse issue type and ID from filename 

270 issue_type, issue_id = self._parse_type_and_id(filename, issue_path) 

271 

272 # Read content once for all content-based parsing 

273 content = self._read_content(issue_path) 

274 

275 # Parse frontmatter for discovered_by, product impact, effort, and impact 

276 frontmatter = parse_frontmatter(content) 

277 discovered_by = frontmatter.get("discovered_by") 

278 product_impact = self._parse_product_impact(frontmatter) 

279 effort_raw = frontmatter.get("effort") 

280 impact_raw = frontmatter.get("impact") 

281 effort = int(effort_raw) if effort_raw is not None and str(effort_raw).isdigit() else None 

282 impact = int(impact_raw) if impact_raw is not None and str(impact_raw).isdigit() else None 

283 confidence_raw = frontmatter.get("confidence_score") 

284 outcome_raw = frontmatter.get("outcome_confidence") 

285 confidence_score = ( 

286 int(confidence_raw) 

287 if confidence_raw is not None and str(confidence_raw).isdigit() 

288 else None 

289 ) 

290 outcome_confidence = ( 

291 int(outcome_raw) 

292 if outcome_raw is not None and str(outcome_raw).isdigit() 

293 else None 

294 ) 

295 

296 # Parse title and dependencies from file content 

297 title = self._parse_title_from_content(content, issue_path) 

298 blocked_by = self._parse_blocked_by(content) 

299 blocks = self._parse_blocks(content) 

300 

301 # Parse session commands from ## Session Log section 

302 from little_loops.session_log import count_session_commands, parse_session_log 

303 

304 session_commands = parse_session_log(content) 

305 session_command_counts = count_session_commands(content) 

306 

307 return IssueInfo( 

308 path=issue_path, 

309 issue_type=issue_type, 

310 priority=priority, 

311 issue_id=issue_id, 

312 title=title, 

313 blocked_by=blocked_by, 

314 blocks=blocks, 

315 discovered_by=discovered_by, 

316 product_impact=product_impact, 

317 effort=effort, 

318 impact=impact, 

319 confidence_score=confidence_score, 

320 outcome_confidence=outcome_confidence, 

321 session_commands=session_commands, 

322 session_command_counts=session_command_counts, 

323 ) 

324 

325 def _parse_priority(self, filename: str) -> str: 

326 """Extract priority from filename. 

327 

328 Args: 

329 filename: Issue filename 

330 

331 Returns: 

332 Priority string (e.g., "P1") or last priority if not found 

333 """ 

334 for priority in self.config.issue_priorities: 

335 if filename.startswith(f"{priority}-"): 

336 return priority 

337 # Default to lowest priority if not found 

338 return self.config.issue_priorities[-1] if self.config.issue_priorities else "P3" 

339 

340 def _get_category_for_prefix(self, prefix: str) -> str: 

341 """Get category name from issue prefix. 

342 

343 Args: 

344 prefix: Issue prefix (e.g., "BUG", "FEAT") 

345 

346 Returns: 

347 Category name (e.g., "bugs", "features"), defaults to "bugs" 

348 """ 

349 return self._prefix_to_category.get(prefix, "bugs") 

350 

351 def _parse_type_and_id(self, filename: str, issue_path: Path) -> tuple[str, str]: 

352 """Extract issue type and ID from filename. 

353 

354 Args: 

355 filename: Issue filename 

356 issue_path: Full path to issue file 

357 

358 Returns: 

359 Tuple of (issue_type, issue_id) 

360 """ 

361 # Try to match known prefixes (BUG, FEAT, ENH, etc.) 

362 for prefix, category in self._prefix_to_category.items(): 

363 pattern = rf"({prefix})-(\d+)" 

364 match = re.search(pattern, filename) 

365 if match: 

366 issue_id = f"{match.group(1)}-{match.group(2)}" 

367 return category, issue_id 

368 

369 # Fall back to inferring from directory 

370 parent_name = issue_path.parent.name 

371 for category_name, category_config in self.config.issues.categories.items(): 

372 if parent_name == category_config.dir: 

373 # Generate ID from filename 

374 issue_id = self._generate_id_from_filename(filename, category_config.prefix) 

375 return category_name, issue_id 

376 

377 # Last resort: use filename as ID 

378 return "bugs", filename.replace(".md", "") 

379 

380 def _generate_id_from_filename(self, filename: str, prefix: str) -> str: 

381 """Generate an issue ID from filename when not explicitly present. 

382 

383 Args: 

384 filename: Issue filename 

385 prefix: Issue prefix to use 

386 

387 Returns: 

388 Generated issue ID 

389 """ 

390 # Try to extract a number from the filename 

391 numbers = re.findall(r"\d+", filename) 

392 if numbers: 

393 return f"{prefix}-{numbers[0]}" 

394 # Use next sequential number instead of hash-based fallback 

395 # This ensures IDs are deterministic and don't collide with existing issues 

396 category = self._get_category_for_prefix(prefix) 

397 next_num = get_next_issue_number(self.config, category) 

398 return f"{prefix}-{next_num:03d}" 

399 

400 def _read_content(self, issue_path: Path) -> str: 

401 """Read file content, returning empty string on error. 

402 

403 Args: 

404 issue_path: Path to issue file 

405 

406 Returns: 

407 File content or empty string on error 

408 """ 

409 try: 

410 return issue_path.read_text(encoding="utf-8") 

411 except Exception as e: 

412 logger.warning("Failed to read %s: %s", issue_path.name, e) 

413 return "" 

414 

415 def _parse_title_from_content(self, content: str, issue_path: Path) -> str: 

416 """Extract title from issue file content. 

417 

418 Args: 

419 content: Pre-read file content 

420 issue_path: Path to issue file (for fallback) 

421 

422 Returns: 

423 Issue title or filename stem as fallback 

424 """ 

425 if content: 

426 # Look for markdown header: # ISSUE-ID: Title 

427 match = re.search(r"^#\s+[\w-]+:\s*(.+)$", content, re.MULTILINE) 

428 if match: 

429 return match.group(1).strip() 

430 # Try first header of any format 

431 match = re.search(r"^#\s+(.+)$", content, re.MULTILINE) 

432 if match: 

433 return match.group(1).strip() 

434 # Fall back to filename 

435 return issue_path.stem 

436 

437 def _parse_section_items(self, content: str, section_name: str) -> list[str]: 

438 """Extract issue IDs from a markdown section. 

439 

440 Finds section header (## Section Name) and extracts issue IDs 

441 from list items until the next section or end of file. 

442 Skips content inside code fences. 

443 

444 Args: 

445 content: File content to parse 

446 section_name: Section name to find (e.g., "Blocked By") 

447 

448 Returns: 

449 List of issue IDs found in the section 

450 """ 

451 if not content: 

452 return [] 

453 

454 # Strip code fences to avoid matching sections in examples 

455 content_without_code = self._strip_code_fences(content) 

456 

457 # Match section header case-insensitively 

458 section_pattern = rf"^##\s+{re.escape(section_name)}\s*$" 

459 match = re.search(section_pattern, content_without_code, re.MULTILINE | re.IGNORECASE) 

460 if not match: 

461 return [] 

462 

463 # Get content after section header until next ## header or end 

464 start = match.end() 

465 next_section = re.search(r"^##\s+", content_without_code[start:], re.MULTILINE) 

466 if next_section: 

467 section_content = content_without_code[start : start + next_section.start()] 

468 else: 

469 section_content = content_without_code[start:] 

470 

471 # Extract issue IDs from list items 

472 issue_ids = ISSUE_ID_PATTERN.findall(section_content) 

473 return issue_ids 

474 

475 def _strip_code_fences(self, content: str) -> str: 

476 """Remove code fence blocks from content. 

477 

478 Replaces content between ``` markers with empty lines to preserve 

479 line numbers while removing code fence content from parsing. 

480 

481 Args: 

482 content: File content 

483 

484 Returns: 

485 Content with code fence blocks replaced by empty lines 

486 """ 

487 # Match code fences: ``` or ```language through closing ``` 

488 result = [] 

489 in_fence = False 

490 for line in content.split("\n"): 

491 if line.startswith("```"): 

492 in_fence = not in_fence 

493 result.append("") # Preserve line count 

494 elif in_fence: 

495 result.append("") # Replace fenced content with empty line 

496 else: 

497 result.append(line) 

498 return "\n".join(result) 

499 

500 def _parse_blocked_by(self, content: str) -> list[str]: 

501 """Extract issue IDs from ## Blocked By section. 

502 

503 Args: 

504 content: File content to parse 

505 

506 Returns: 

507 List of issue IDs that block this issue 

508 """ 

509 return self._parse_section_items(content, "Blocked By") 

510 

511 def _parse_blocks(self, content: str) -> list[str]: 

512 """Extract issue IDs from ## Blocks section. 

513 

514 Args: 

515 content: File content to parse 

516 

517 Returns: 

518 List of issue IDs that this issue blocks 

519 """ 

520 return self._parse_section_items(content, "Blocks") 

521 

522 def _parse_product_impact(self, frontmatter: dict[str, Any]) -> ProductImpact | None: 

523 """Extract product impact from frontmatter. 

524 

525 Args: 

526 frontmatter: Dictionary of frontmatter fields 

527 

528 Returns: 

529 ProductImpact instance if any product fields are present, None otherwise 

530 """ 

531 # Check if any product fields are present 

532 product_fields = ("goal_alignment", "persona_impact", "business_value", "user_benefit") 

533 if not any(frontmatter.get(key) for key in product_fields): 

534 return None 

535 

536 return ProductImpact( 

537 goal_alignment=frontmatter.get("goal_alignment"), 

538 persona_impact=frontmatter.get("persona_impact"), 

539 business_value=frontmatter.get("business_value"), 

540 user_benefit=frontmatter.get("user_benefit"), 

541 ) 

542 

543 

544def find_issues( 

545 config: BRConfig, 

546 category: str | None = None, 

547 skip_ids: set[str] | None = None, 

548 only_ids: set[str] | None = None, 

549 type_prefixes: set[str] | None = None, 

550) -> list[IssueInfo]: 

551 """Find all issues matching criteria. 

552 

553 Args: 

554 config: Project configuration 

555 category: Optional category to filter (e.g., "bugs") 

556 skip_ids: Issue IDs to skip 

557 only_ids: If provided, only include these issue IDs 

558 type_prefixes: If provided, only include issues whose ID starts with 

559 one of these prefixes (e.g., {"BUG", "ENH"}) 

560 

561 Returns: 

562 List of IssueInfo sorted by priority 

563 """ 

564 skip_ids = skip_ids or set() 

565 parser = IssueParser(config) 

566 issues: list[IssueInfo] = [] 

567 

568 # Get completed and deferred directories for duplicate detection 

569 completed_dir = config.get_completed_dir() 

570 deferred_dir = config.get_deferred_dir() 

571 

572 # Determine which categories to search 

573 if category: 

574 categories = [category] if category in config.issue_categories else [] 

575 else: 

576 categories = config.issue_categories 

577 

578 for cat in categories: 

579 issue_dir = config.get_issue_dir(cat) 

580 if not issue_dir.exists(): 

581 continue 

582 

583 for issue_file in issue_dir.glob("*.md"): 

584 # Pre-flight check: skip if already exists in completed or deferred directory 

585 completed_path = completed_dir / issue_file.name 

586 if completed_path.exists(): 

587 continue 

588 deferred_path = deferred_dir / issue_file.name 

589 if deferred_path.exists(): 

590 continue 

591 

592 info = parser.parse_file(issue_file) 

593 # Apply skip filter 

594 if info.issue_id in skip_ids: 

595 continue 

596 # Apply only filter (if specified) 

597 if only_ids is not None and info.issue_id not in only_ids: 

598 continue 

599 # Apply type filter (if specified) 

600 if type_prefixes is not None: 

601 prefix = info.issue_id.split("-", 1)[0] 

602 if prefix not in type_prefixes: 

603 continue 

604 issues.append(info) 

605 

606 # Sort by priority (lower int = higher priority) 

607 issues.sort(key=lambda x: (x.priority_int, x.issue_id)) 

608 return issues 

609 

610 

611def find_highest_priority_issue( 

612 config: BRConfig, 

613 category: str | None = None, 

614 skip_ids: set[str] | None = None, 

615 only_ids: set[str] | None = None, 

616 type_prefixes: set[str] | None = None, 

617) -> IssueInfo | None: 

618 """Find the highest priority issue. 

619 

620 Args: 

621 config: Project configuration 

622 category: Optional category to filter 

623 skip_ids: Issue IDs to skip 

624 only_ids: If provided, only include these issue IDs 

625 type_prefixes: If provided, only include issues with these type prefixes 

626 

627 Returns: 

628 Highest priority IssueInfo or None if no issues found 

629 """ 

630 issues = find_issues(config, category, skip_ids, only_ids, type_prefixes) 

631 return issues[0] if issues else None