Coverage for little_loops / issue_parser.py: 25%
248 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 parsing for little-loops.
3Parses issue markdown files to extract metadata like priority, ID, type, and title.
4"""
6from __future__ import annotations
8import logging
9import re
10from dataclasses import dataclass, field
11from pathlib import Path
12from typing import TYPE_CHECKING, Any
14from little_loops.frontmatter import parse_frontmatter
16if TYPE_CHECKING:
17 from little_loops.config import BRConfig
20logger = logging.getLogger(__name__)
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)
28_NORMALIZED_RE = re.compile(r"^P[0-5]-(BUG|FEAT|ENH)-[0-9]{3,}-[a-z0-9-]+\.md$")
29_ISSUE_TYPE_RE = re.compile(r"-(BUG|FEAT|ENH)-")
32def is_normalized(filename: str) -> bool:
33 """Check whether an issue filename conforms to naming conventions.
35 Args:
36 filename: The basename of the issue file (e.g. 'P2-BUG-010-my-issue.md').
38 Returns:
39 True if the filename matches ``^P[0-5]-(BUG|FEAT|ENH)-[0-9]{3,}-[a-z0-9-]+\\.md$``.
40 """
41 return bool(_NORMALIZED_RE.match(filename))
44def is_formatted(issue_path: Path, templates_dir: Path | None = None) -> bool:
45 """Check whether an issue file has been formatted.
47 An issue is considered formatted if either:
48 1. Its ## Session Log contains a ``/ll:format-issue`` entry, OR
49 2. It has all required sections per its type template (structural check).
51 Args:
52 issue_path: Path to the issue markdown file.
53 templates_dir: Optional override for the templates directory.
55 Returns:
56 True if the issue is formatted by either criterion, False otherwise.
57 Returns False for files whose type cannot be determined or whose template
58 cannot be loaded.
59 """
60 from little_loops.issue_template import load_issue_sections
61 from little_loops.session_log import parse_session_log
63 try:
64 content = issue_path.read_text(encoding="utf-8")
65 except Exception:
66 return False
68 # Criterion 1: /ll:format-issue appears in the session log
69 if "/ll:format-issue" in parse_session_log(content):
70 return True
72 # Criterion 2: all required sections are present as ## headings
73 type_match = _ISSUE_TYPE_RE.search(issue_path.name)
74 if not type_match:
75 return False
76 issue_type = type_match.group(1)
78 try:
79 sections_data = load_issue_sections(issue_type, templates_dir)
80 except Exception:
81 return False
83 required: set[str] = set()
84 for name, defn in sections_data.get("common_sections", {}).items():
85 if defn.get("required") is True and not defn.get("deprecated", False):
86 required.add(name)
87 for name, defn in sections_data.get("type_sections", {}).items():
88 if defn.get("level") == "required" and not defn.get("deprecated", False):
89 required.add(name)
91 if not required:
92 return True
94 headings = {m.strip() for m in re.findall(r"^##\s+(.+)$", content, re.MULTILINE)}
95 return required.issubset(headings)
98def slugify(text: str) -> str:
99 """Convert text to slug format for filenames.
101 Args:
102 text: Text to convert
104 Returns:
105 Lowercase slug with hyphens
106 """
107 text = re.sub(r"[^\w\s-]", "", text)
108 text = re.sub(r"[-\s]+", "-", text)
109 return text.strip("-").lower()
112def get_next_issue_number(config: BRConfig, category: str | None = None) -> int:
113 """Determine the next globally unique issue number.
115 Scans ALL issue directories (active and completed) to find the highest
116 existing number across ALL issue types (BUG, FEAT, ENH). Issue numbers
117 are globally unique regardless of type.
119 Args:
120 config: Project configuration
121 category: Unused, kept for backwards compatibility
123 Returns:
124 Next available issue number (globally unique across all types)
125 """
126 max_num = 0
128 # Get all known prefixes from configuration
129 all_prefixes = [cat_config.prefix for cat_config in config.issues.categories.values()]
131 # Directories to scan: ALL category directories + completed + deferred
132 dirs_to_scan = [config.get_completed_dir(), config.get_deferred_dir()]
133 for cat_name in config.issues.categories:
134 dirs_to_scan.append(config.get_issue_dir(cat_name))
136 if not all_prefixes:
137 return max_num + 1
139 # Pre-compile a single union regex to match any known prefix
140 prefix_pattern = re.compile(r"(?:" + "|".join(re.escape(p) for p in all_prefixes) + r")-(\d+)")
142 for dir_path in dirs_to_scan:
143 if not dir_path.exists():
144 continue
145 for file in dir_path.glob("*.md"):
146 match = prefix_pattern.search(file.name)
147 if match:
148 num = int(match.group(1))
149 if num > max_num:
150 max_num = num
152 return max_num + 1
155@dataclass
156class ProductImpact:
157 """Product impact assessment for an issue.
159 Attributes:
160 goal_alignment: ID of the strategic priority this supports
161 persona_impact: ID of the persona affected
162 business_value: Business value assessment (high|medium|low)
163 user_benefit: Description of how this helps the target user
164 """
166 goal_alignment: str | None = None
167 persona_impact: str | None = None
168 business_value: str | None = None # high|medium|low
169 user_benefit: str | None = None
171 def to_dict(self) -> dict[str, Any]:
172 """Convert to dictionary for JSON serialization."""
173 return {
174 "goal_alignment": self.goal_alignment,
175 "persona_impact": self.persona_impact,
176 "business_value": self.business_value,
177 "user_benefit": self.user_benefit,
178 }
180 @classmethod
181 def from_dict(cls, data: dict[str, Any] | None) -> ProductImpact | None:
182 """Create ProductImpact from dictionary.
184 Args:
185 data: Dictionary with product impact fields, or None
187 Returns:
188 ProductImpact instance or None if data is None/empty
189 """
190 if not data:
191 return None
192 return cls(
193 goal_alignment=data.get("goal_alignment"),
194 persona_impact=data.get("persona_impact"),
195 business_value=data.get("business_value"),
196 user_benefit=data.get("user_benefit"),
197 )
200@dataclass
201class IssueInfo:
202 """Parsed information from an issue file.
204 Attributes:
205 path: Path to the issue file
206 issue_type: Type of issue (e.g., "bugs", "features")
207 priority: Priority level (e.g., "P0", "P1")
208 issue_id: Issue identifier (e.g., "BUG-123")
209 title: Issue title from markdown header
210 blocked_by: List of issue IDs that block this issue
211 blocks: List of issue IDs that this issue blocks
212 discovered_by: Source command/workflow that created this issue
213 product_impact: Product impact assessment (optional)
214 effort: Effort estimate (1=low, 2=medium, 3=high), inferred from priority if absent
215 impact: Impact estimate (1=low, 2=medium, 3=high), inferred from priority if absent
216 confidence_score: Readiness score (0-100) written by /ll:confidence-check, or None
217 outcome_confidence: Outcome confidence (0-100) written by /ll:confidence-check, or None
218 session_commands: Distinct /ll:* commands found in the ## Session Log section
219 session_command_counts: Per-command occurrence counts from the ## Session Log section
220 """
222 path: Path
223 issue_type: str
224 priority: str
225 issue_id: str
226 title: str
227 blocked_by: list[str] = field(default_factory=list)
228 blocks: list[str] = field(default_factory=list)
229 discovered_by: str | None = None
230 product_impact: ProductImpact | None = None
231 effort: int | None = None
232 impact: int | None = None
233 confidence_score: int | None = None
234 outcome_confidence: int | None = None
235 session_commands: list[str] = field(default_factory=list)
236 session_command_counts: dict[str, int] = field(default_factory=dict)
238 @property
239 def priority_int(self) -> int:
240 """Convert priority to integer for comparison (lower = higher priority)."""
241 # Support P0-P5 priorities
242 match = re.match(r"^P(\d+)$", self.priority)
243 if match:
244 return int(match.group(1))
245 return 99 # Unknown priority sorts last
247 def to_dict(self) -> dict[str, Any]:
248 """Convert to dictionary for JSON serialization."""
249 return {
250 "path": str(self.path),
251 "issue_type": self.issue_type,
252 "priority": self.priority,
253 "issue_id": self.issue_id,
254 "title": self.title,
255 "blocked_by": self.blocked_by,
256 "blocks": self.blocks,
257 "discovered_by": self.discovered_by,
258 "product_impact": (self.product_impact.to_dict() if self.product_impact else None),
259 "effort": self.effort,
260 "impact": self.impact,
261 "confidence_score": self.confidence_score,
262 "outcome_confidence": self.outcome_confidence,
263 "session_commands": self.session_commands,
264 "session_command_counts": self.session_command_counts,
265 }
267 @classmethod
268 def from_dict(cls, data: dict[str, Any]) -> IssueInfo:
269 """Create IssueInfo from dictionary."""
270 return cls(
271 path=Path(data["path"]),
272 issue_type=data["issue_type"],
273 priority=data["priority"],
274 issue_id=data["issue_id"],
275 title=data["title"],
276 blocked_by=data.get("blocked_by", []),
277 blocks=data.get("blocks", []),
278 discovered_by=data.get("discovered_by"),
279 product_impact=ProductImpact.from_dict(data.get("product_impact")),
280 effort=data.get("effort"),
281 impact=data.get("impact"),
282 confidence_score=data.get("confidence_score"),
283 outcome_confidence=data.get("outcome_confidence"),
284 session_commands=data.get("session_commands", []),
285 session_command_counts=data.get("session_command_counts", {}),
286 )
289class IssueParser:
290 """Parses issue files based on project configuration.
292 Uses BRConfig to understand issue categories, prefixes, and priorities.
293 """
295 def __init__(self, config: BRConfig) -> None:
296 """Initialize parser with project configuration.
298 Args:
299 config: Project configuration
300 """
301 self.config = config
302 self._build_prefix_map()
304 def _build_prefix_map(self) -> None:
305 """Build mapping from issue prefixes to category names."""
306 self._prefix_to_category: dict[str, str] = {}
307 for category_name, category in self.config.issues.categories.items():
308 self._prefix_to_category[category.prefix] = category_name
310 def parse_file(self, issue_path: Path) -> IssueInfo:
311 """Parse an issue file to extract metadata.
313 Args:
314 issue_path: Path to the issue markdown file
316 Returns:
317 Parsed IssueInfo
318 """
319 filename = issue_path.name
321 # Parse priority from filename prefix (e.g., P1-BUG-123-...)
322 priority = self._parse_priority(filename)
324 # Parse issue type and ID from filename
325 issue_type, issue_id = self._parse_type_and_id(filename, issue_path)
327 # Read content once for all content-based parsing
328 content = self._read_content(issue_path)
330 # Parse frontmatter for discovered_by, product impact, effort, and impact
331 frontmatter = parse_frontmatter(content)
332 discovered_by = frontmatter.get("discovered_by")
333 product_impact = self._parse_product_impact(frontmatter)
334 effort_raw = frontmatter.get("effort")
335 impact_raw = frontmatter.get("impact")
336 effort = int(effort_raw) if effort_raw is not None and str(effort_raw).isdigit() else None
337 impact = int(impact_raw) if impact_raw is not None and str(impact_raw).isdigit() else None
338 confidence_raw = frontmatter.get("confidence_score")
339 outcome_raw = frontmatter.get("outcome_confidence")
340 confidence_score = (
341 int(confidence_raw)
342 if confidence_raw is not None and str(confidence_raw).isdigit()
343 else None
344 )
345 outcome_confidence = (
346 int(outcome_raw) if outcome_raw is not None and str(outcome_raw).isdigit() else None
347 )
349 # Parse title and dependencies from file content
350 title = self._parse_title_from_content(content, issue_path)
351 blocked_by = self._parse_blocked_by(content)
352 blocks = self._parse_blocks(content)
354 # Parse session commands from ## Session Log section
355 from little_loops.session_log import count_session_commands, parse_session_log
357 session_commands = parse_session_log(content)
358 session_command_counts = count_session_commands(content)
360 return IssueInfo(
361 path=issue_path,
362 issue_type=issue_type,
363 priority=priority,
364 issue_id=issue_id,
365 title=title,
366 blocked_by=blocked_by,
367 blocks=blocks,
368 discovered_by=discovered_by,
369 product_impact=product_impact,
370 effort=effort,
371 impact=impact,
372 confidence_score=confidence_score,
373 outcome_confidence=outcome_confidence,
374 session_commands=session_commands,
375 session_command_counts=session_command_counts,
376 )
378 def _parse_priority(self, filename: str) -> str:
379 """Extract priority from filename.
381 Args:
382 filename: Issue filename
384 Returns:
385 Priority string (e.g., "P1") or last priority if not found
386 """
387 for priority in self.config.issue_priorities:
388 if filename.startswith(f"{priority}-"):
389 return priority
390 # Default to lowest priority if not found
391 return self.config.issue_priorities[-1] if self.config.issue_priorities else "P3"
393 def _get_category_for_prefix(self, prefix: str) -> str:
394 """Get category name from issue prefix.
396 Args:
397 prefix: Issue prefix (e.g., "BUG", "FEAT")
399 Returns:
400 Category name (e.g., "bugs", "features"), defaults to "bugs"
401 """
402 return self._prefix_to_category.get(prefix, "bugs")
404 def _parse_type_and_id(self, filename: str, issue_path: Path) -> tuple[str, str]:
405 """Extract issue type and ID from filename.
407 Args:
408 filename: Issue filename
409 issue_path: Full path to issue file
411 Returns:
412 Tuple of (issue_type, issue_id)
413 """
414 # Try to match known prefixes (BUG, FEAT, ENH, etc.)
415 for prefix, category in self._prefix_to_category.items():
416 pattern = rf"({prefix})-(\d+)"
417 match = re.search(pattern, filename)
418 if match:
419 issue_id = f"{match.group(1)}-{match.group(2)}"
420 return category, issue_id
422 # Fall back to inferring from directory
423 parent_name = issue_path.parent.name
424 for category_name, category_config in self.config.issues.categories.items():
425 if parent_name == category_config.dir:
426 # Generate ID from filename
427 issue_id = self._generate_id_from_filename(filename, category_config.prefix)
428 return category_name, issue_id
430 # Last resort: use filename as ID
431 return "bugs", filename.replace(".md", "")
433 def _generate_id_from_filename(self, filename: str, prefix: str) -> str:
434 """Generate an issue ID from filename when not explicitly present.
436 Args:
437 filename: Issue filename
438 prefix: Issue prefix to use
440 Returns:
441 Generated issue ID
442 """
443 # Try to extract a number from the filename
444 numbers = re.findall(r"\d+", filename)
445 if numbers:
446 return f"{prefix}-{numbers[0]}"
447 # Use next sequential number instead of hash-based fallback
448 # This ensures IDs are deterministic and don't collide with existing issues
449 category = self._get_category_for_prefix(prefix)
450 next_num = get_next_issue_number(self.config, category)
451 return f"{prefix}-{next_num:03d}"
453 def _read_content(self, issue_path: Path) -> str:
454 """Read file content, returning empty string on error.
456 Args:
457 issue_path: Path to issue file
459 Returns:
460 File content or empty string on error
461 """
462 try:
463 return issue_path.read_text(encoding="utf-8")
464 except Exception as e:
465 logger.warning("Failed to read %s: %s", issue_path.name, e)
466 return ""
468 def _parse_title_from_content(self, content: str, issue_path: Path) -> str:
469 """Extract title from issue file content.
471 Args:
472 content: Pre-read file content
473 issue_path: Path to issue file (for fallback)
475 Returns:
476 Issue title or filename stem as fallback
477 """
478 if content:
479 # Look for markdown header: # ISSUE-ID: Title
480 match = re.search(r"^#\s+[\w-]+:\s*(.+)$", content, re.MULTILINE)
481 if match:
482 return match.group(1).strip()
483 # Try first header of any format
484 match = re.search(r"^#\s+(.+)$", content, re.MULTILINE)
485 if match:
486 return match.group(1).strip()
487 # Fall back to filename
488 return issue_path.stem
490 def _parse_section_items(self, content: str, section_name: str) -> list[str]:
491 """Extract issue IDs from a markdown section.
493 Finds section header (## Section Name) and extracts issue IDs
494 from list items until the next section or end of file.
495 Skips content inside code fences.
497 Args:
498 content: File content to parse
499 section_name: Section name to find (e.g., "Blocked By")
501 Returns:
502 List of issue IDs found in the section
503 """
504 if not content:
505 return []
507 # Strip code fences to avoid matching sections in examples
508 content_without_code = self._strip_code_fences(content)
510 # Match section header case-insensitively
511 section_pattern = rf"^##\s+{re.escape(section_name)}\s*$"
512 match = re.search(section_pattern, content_without_code, re.MULTILINE | re.IGNORECASE)
513 if not match:
514 return []
516 # Get content after section header until next ## header or end
517 start = match.end()
518 next_section = re.search(r"^##\s+", content_without_code[start:], re.MULTILINE)
519 if next_section:
520 section_content = content_without_code[start : start + next_section.start()]
521 else:
522 section_content = content_without_code[start:]
524 # Extract issue IDs from list items
525 issue_ids = ISSUE_ID_PATTERN.findall(section_content)
526 return issue_ids
528 def _strip_code_fences(self, content: str) -> str:
529 """Remove code fence blocks from content.
531 Replaces content between ``` markers with empty lines to preserve
532 line numbers while removing code fence content from parsing.
534 Args:
535 content: File content
537 Returns:
538 Content with code fence blocks replaced by empty lines
539 """
540 # Match code fences: ``` or ```language through closing ```
541 result = []
542 in_fence = False
543 for line in content.split("\n"):
544 if line.startswith("```"):
545 in_fence = not in_fence
546 result.append("") # Preserve line count
547 elif in_fence:
548 result.append("") # Replace fenced content with empty line
549 else:
550 result.append(line)
551 return "\n".join(result)
553 def _parse_blocked_by(self, content: str) -> list[str]:
554 """Extract issue IDs from ## Blocked By section.
556 Args:
557 content: File content to parse
559 Returns:
560 List of issue IDs that block this issue
561 """
562 return self._parse_section_items(content, "Blocked By")
564 def _parse_blocks(self, content: str) -> list[str]:
565 """Extract issue IDs from ## Blocks section.
567 Args:
568 content: File content to parse
570 Returns:
571 List of issue IDs that this issue blocks
572 """
573 return self._parse_section_items(content, "Blocks")
575 def _parse_product_impact(self, frontmatter: dict[str, Any]) -> ProductImpact | None:
576 """Extract product impact from frontmatter.
578 Args:
579 frontmatter: Dictionary of frontmatter fields
581 Returns:
582 ProductImpact instance if any product fields are present, None otherwise
583 """
584 # Check if any product fields are present
585 product_fields = ("goal_alignment", "persona_impact", "business_value", "user_benefit")
586 if not any(frontmatter.get(key) for key in product_fields):
587 return None
589 return ProductImpact(
590 goal_alignment=frontmatter.get("goal_alignment"),
591 persona_impact=frontmatter.get("persona_impact"),
592 business_value=frontmatter.get("business_value"),
593 user_benefit=frontmatter.get("user_benefit"),
594 )
597def find_issues(
598 config: BRConfig,
599 category: str | None = None,
600 skip_ids: set[str] | None = None,
601 only_ids: set[str] | None = None,
602 type_prefixes: set[str] | None = None,
603) -> list[IssueInfo]:
604 """Find all issues matching criteria.
606 Args:
607 config: Project configuration
608 category: Optional category to filter (e.g., "bugs")
609 skip_ids: Issue IDs to skip
610 only_ids: If provided, only include these issue IDs
611 type_prefixes: If provided, only include issues whose ID starts with
612 one of these prefixes (e.g., {"BUG", "ENH"})
614 Returns:
615 List of IssueInfo sorted by priority
616 """
617 skip_ids = skip_ids or set()
618 parser = IssueParser(config)
619 issues: list[IssueInfo] = []
621 # Get completed and deferred directories for duplicate detection
622 completed_dir = config.get_completed_dir()
623 deferred_dir = config.get_deferred_dir()
625 # Determine which categories to search
626 if category:
627 categories = [category] if category in config.issue_categories else []
628 else:
629 categories = config.issue_categories
631 for cat in categories:
632 issue_dir = config.get_issue_dir(cat)
633 if not issue_dir.exists():
634 continue
636 for issue_file in issue_dir.glob("*.md"):
637 # Pre-flight check: skip if already exists in completed or deferred directory
638 completed_path = completed_dir / issue_file.name
639 if completed_path.exists():
640 continue
641 deferred_path = deferred_dir / issue_file.name
642 if deferred_path.exists():
643 continue
645 info = parser.parse_file(issue_file)
646 # Apply skip filter
647 if info.issue_id in skip_ids:
648 continue
649 # Apply only filter (if specified)
650 if only_ids is not None and info.issue_id not in only_ids:
651 continue
652 # Apply type filter (if specified)
653 if type_prefixes is not None:
654 prefix = info.issue_id.split("-", 1)[0]
655 if prefix not in type_prefixes:
656 continue
657 issues.append(info)
659 # Sort by priority (lower int = higher priority)
660 issues.sort(key=lambda x: (x.priority_int, x.issue_id))
661 return issues
664def find_highest_priority_issue(
665 config: BRConfig,
666 category: str | None = None,
667 skip_ids: set[str] | None = None,
668 only_ids: set[str] | None = None,
669 type_prefixes: set[str] | None = None,
670) -> IssueInfo | None:
671 """Find the highest priority issue.
673 Args:
674 config: Project configuration
675 category: Optional category to filter
676 skip_ids: Issue IDs to skip
677 only_ids: If provided, only include these issue IDs
678 type_prefixes: If provided, only include issues with these type prefixes
680 Returns:
681 Highest priority IssueInfo or None if no issues found
682 """
683 issues = find_issues(config, category, skip_ids, only_ids, type_prefixes)
684 return issues[0] if issues else None