Coverage for little_loops / issue_history / quality.py: 92%
201 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 history quality analysis: test gaps, rejections, manual patterns, config gaps."""
3from __future__ import annotations
5import json
6import re
7from pathlib import Path
8from typing import Any
10from little_loops.issue_history.models import (
11 CompletedIssue,
12 ConfigGap,
13 ConfigGapsAnalysis,
14 HotspotAnalysis,
15 ManualPattern,
16 ManualPatternAnalysis,
17 RejectionAnalysis,
18 RejectionMetrics,
19 TestGap,
20 TestGapAnalysis,
21)
22from little_loops.issue_history.parsing import _find_test_file, _parse_resolution_action
25def analyze_test_gaps(
26 issues: list[CompletedIssue],
27 hotspots: HotspotAnalysis,
28) -> TestGapAnalysis:
29 """Correlate bug occurrences with test coverage gaps.
31 Args:
32 issues: List of completed issues (unused, for API consistency)
33 hotspots: Pre-computed hotspot analysis
35 Returns:
36 TestGapAnalysis with test coverage gap information
37 """
38 # Build map of source files to bug info from hotspots
39 bug_files: dict[str, dict[str, Any]] = {}
41 for hotspot in hotspots.file_hotspots:
42 bug_count = hotspot.issue_types.get("BUG", 0)
43 if bug_count > 0:
44 # Filter to only BUG issue IDs
45 bug_ids = [iid for iid in hotspot.issue_ids if iid.startswith("BUG-")]
46 bug_files[hotspot.path] = {
47 "bug_count": bug_count,
48 "bug_ids": bug_ids,
49 }
51 if not bug_files:
52 return TestGapAnalysis()
54 # Analyze test coverage for each file with bugs
55 gaps: list[TestGap] = []
56 files_with_tests: list[int] = [] # bug counts
57 files_without_tests: list[int] = [] # bug counts
59 for source_file, data in bug_files.items():
60 bug_count = data["bug_count"]
61 bug_ids = data["bug_ids"]
63 test_file = _find_test_file(source_file)
64 has_test = test_file is not None
66 # Calculate gap score: higher = more urgent to add tests
67 # Files without tests get amplified scores
68 if has_test:
69 gap_score = bug_count * 1.0
70 files_with_tests.append(bug_count)
71 else:
72 gap_score = bug_count * 10.0 # Amplify untested files
73 files_without_tests.append(bug_count)
75 # Determine priority based on bug count and test presence
76 if not has_test and bug_count >= 5:
77 priority = "critical"
78 elif not has_test and bug_count >= 3:
79 priority = "high"
80 elif not has_test or bug_count >= 4:
81 priority = "medium"
82 else:
83 priority = "low"
85 gaps.append(
86 TestGap(
87 source_file=source_file,
88 bug_count=bug_count,
89 bug_ids=bug_ids,
90 has_test_file=has_test,
91 test_file_path=test_file,
92 gap_score=gap_score,
93 priority=priority,
94 )
95 )
97 # Sort by gap score descending (highest priority first)
98 gaps.sort(key=lambda g: (-g.gap_score, -g.bug_count))
100 # Calculate averages for correlation
101 avg_with_tests = sum(files_with_tests) / len(files_with_tests) if files_with_tests else 0.0
102 avg_without_tests = (
103 sum(files_without_tests) / len(files_without_tests) if files_without_tests else 0.0
104 )
106 # Identify untested bug magnets (from hotspot analysis)
107 untested_magnets = [h.path for h in hotspots.bug_magnets if _find_test_file(h.path) is None]
109 # Priority test targets: untested files sorted by bug count
110 priority_targets = [g.source_file for g in gaps if not g.has_test_file]
112 return TestGapAnalysis(
113 gaps=gaps[:15], # Top 15
114 untested_bug_magnets=untested_magnets,
115 files_with_tests_avg_bugs=avg_with_tests,
116 files_without_tests_avg_bugs=avg_without_tests,
117 priority_test_targets=priority_targets[:10],
118 )
121def analyze_rejection_rates(
122 issues: list[CompletedIssue],
123 contents: dict[Path, str] | None = None,
124) -> RejectionAnalysis:
125 """Analyze rejection and invalid closure patterns.
127 Args:
128 issues: List of completed issues
129 contents: Pre-loaded issue file contents (path -> content)
131 Returns:
132 RejectionAnalysis with overall and grouped metrics
133 """
134 if not issues:
135 return RejectionAnalysis()
137 # Count by category
138 overall = RejectionMetrics()
139 by_type: dict[str, RejectionMetrics] = {}
140 by_month: dict[str, RejectionMetrics] = {}
141 reason_counts: dict[str, int] = {}
143 for issue in issues:
144 if contents is not None and issue.path in contents:
145 content = contents[issue.path]
146 else:
147 try:
148 content = issue.path.read_text(encoding="utf-8")
149 except Exception:
150 continue
152 category = _parse_resolution_action(content)
153 overall.total_closed += 1
155 # Update overall counts
156 if category == "completed":
157 overall.completed_count += 1
158 elif category == "rejected":
159 overall.rejected_count += 1
160 elif category == "invalid":
161 overall.invalid_count += 1
162 elif category == "duplicate":
163 overall.duplicate_count += 1
164 elif category == "deferred":
165 overall.deferred_count += 1
167 # By type
168 if issue.issue_type not in by_type:
169 by_type[issue.issue_type] = RejectionMetrics()
170 type_metrics = by_type[issue.issue_type]
171 type_metrics.total_closed += 1
172 if category == "rejected":
173 type_metrics.rejected_count += 1
174 elif category == "invalid":
175 type_metrics.invalid_count += 1
176 elif category == "duplicate":
177 type_metrics.duplicate_count += 1
178 elif category == "deferred":
179 type_metrics.deferred_count += 1
180 elif category == "completed":
181 type_metrics.completed_count += 1
183 # By month
184 if issue.completed_date:
185 month_key = issue.completed_date.strftime("%Y-%m")
186 if month_key not in by_month:
187 by_month[month_key] = RejectionMetrics()
188 month_metrics = by_month[month_key]
189 month_metrics.total_closed += 1
190 if category == "rejected":
191 month_metrics.rejected_count += 1
192 elif category == "invalid":
193 month_metrics.invalid_count += 1
194 elif category == "duplicate":
195 month_metrics.duplicate_count += 1
196 elif category == "deferred":
197 month_metrics.deferred_count += 1
198 elif category == "completed":
199 month_metrics.completed_count += 1
201 # Extract reason for rejection/invalid
202 if category in ("rejected", "invalid", "duplicate", "deferred"):
203 reason_match = re.search(r"\*\*Reason\*\*:\s*(.+?)(?:\n|$)", content)
204 if reason_match:
205 reason = reason_match.group(1).strip()
206 reason_counts[reason] = reason_counts.get(reason, 0) + 1
208 # Calculate trend from monthly data
209 sorted_months = sorted(by_month.keys())
210 if len(sorted_months) >= 3:
211 recent = sorted_months[-3:]
212 rates = [by_month[m].rejection_rate + by_month[m].invalid_rate for m in recent]
213 if rates[-1] < rates[0] * 0.8:
214 trend = "improving"
215 elif rates[-1] > rates[0] * 1.2:
216 trend = "degrading"
217 else:
218 trend = "stable"
219 else:
220 trend = "stable"
222 # Sort reasons by count
223 common_reasons = sorted(reason_counts.items(), key=lambda x: -x[1])[:10]
225 return RejectionAnalysis(
226 overall=overall,
227 by_type=by_type,
228 by_month=by_month,
229 common_reasons=common_reasons,
230 trend=trend,
231 )
234# Pattern definitions for manual activity detection
235_MANUAL_PATTERNS: dict[str, dict[str, Any]] = {
236 "test": {
237 "patterns": [
238 r"(?:pytest|python -m pytest|npm test|yarn test|jest|cargo test|go test)",
239 r"(?:python -m unittest|nosetests|tox)",
240 ],
241 "description": "Test execution after code changes",
242 "suggestion": "Add post-edit hook for automatic test runs",
243 "complexity": "trivial",
244 },
245 "lint": {
246 "patterns": [
247 r"(?:ruff check|ruff format|black|isort|flake8|pylint)",
248 r"(?:eslint|prettier|tslint)",
249 ],
250 "description": "Lint/format fixes after implementation",
251 "suggestion": "Add pre-commit hook for auto-formatting",
252 "complexity": "simple",
253 },
254 "type_check": {
255 "patterns": [
256 r"(?:mypy|pyright|python -m mypy)",
257 r"(?:tsc|npx tsc)",
258 ],
259 "description": "Type checking during development",
260 "suggestion": "Add mypy to pre-commit or post-edit hook",
261 "complexity": "simple",
262 },
263 "build": {
264 "patterns": [
265 r"(?:npm run build|yarn build|make|cargo build|go build)",
266 r"(?:python -m build|pip install -e)",
267 ],
268 "description": "Build steps during implementation",
269 "suggestion": "Add build verification to test suite or CI",
270 "complexity": "moderate",
271 },
272 "git": {
273 "patterns": [
274 r"git (?:add|commit|push|pull|checkout|branch)",
275 ],
276 "description": "Git operations during issue resolution",
277 "suggestion": "Use /ll:commit skill for standardized commits",
278 "complexity": "trivial",
279 },
280}
283def detect_manual_patterns(
284 issues: list[CompletedIssue],
285 contents: dict[Path, str] | None = None,
286) -> ManualPatternAnalysis:
287 """Detect recurring manual activities that could be automated.
289 Args:
290 issues: List of completed issues
291 contents: Pre-loaded issue file contents (path -> content)
293 Returns:
294 ManualPatternAnalysis with detected patterns
295 """
296 if not issues:
297 return ManualPatternAnalysis()
299 # Track pattern occurrences
300 pattern_data: dict[str, dict[str, Any]] = {}
302 for pattern_type, config in _MANUAL_PATTERNS.items():
303 pattern_data[pattern_type] = {
304 "count": 0,
305 "issues": [],
306 "commands": [],
307 "config": config,
308 }
310 # Scan issue content for patterns
311 for issue in issues:
312 if contents is not None and issue.path in contents:
313 content = contents[issue.path]
314 else:
315 try:
316 content = issue.path.read_text(encoding="utf-8")
317 except Exception:
318 continue
320 for pattern_type, config in _MANUAL_PATTERNS.items():
321 for pattern in config["patterns"]:
322 matches = re.findall(pattern, content, re.IGNORECASE)
323 if matches:
324 data = pattern_data[pattern_type]
325 data["count"] += len(matches)
326 if issue.issue_id not in data["issues"]:
327 data["issues"].append(issue.issue_id)
328 # Store unique command examples
329 for match in matches:
330 if match not in data["commands"]:
331 data["commands"].append(match)
333 # Build ManualPattern objects
334 patterns: list[ManualPattern] = []
335 total_interventions = 0
336 automatable = 0
338 for pattern_type, data in pattern_data.items():
339 if data["count"] > 0:
340 config = data["config"]
341 pattern = ManualPattern(
342 pattern_type=pattern_type,
343 pattern_description=config["description"],
344 occurrence_count=data["count"],
345 affected_issues=data["issues"],
346 example_commands=data["commands"][:5],
347 suggested_automation=config["suggestion"],
348 automation_complexity=config["complexity"],
349 )
350 patterns.append(pattern)
351 total_interventions += data["count"]
352 automatable += data["count"]
354 # Sort by occurrence count descending
355 patterns.sort(key=lambda p: -p.occurrence_count)
357 # Build automation suggestions
358 suggestions = [p.suggested_automation for p in patterns if p.occurrence_count >= 2]
360 return ManualPatternAnalysis(
361 patterns=patterns,
362 total_manual_interventions=total_interventions,
363 automatable_count=automatable,
364 automation_suggestions=suggestions[:10],
365 )
368# Mapping from manual pattern types to configuration solutions
369_PATTERN_TO_CONFIG: dict[str, dict[str, Any]] = {
370 "test": {
371 "hook_event": "PostToolUse",
372 "description": "Automatic test execution after code changes",
373 "suggested_config": """hooks/hooks.json:
374 "PostToolUse": [{
375 "matcher": "Edit|Write",
376 "hooks": [{
377 "type": "command",
378 "command": "pytest tests/ -x -q",
379 "timeout": 30000
380 }]
381 }]""",
382 },
383 "lint": {
384 "hook_event": "PreToolUse",
385 "description": "Automatic formatting before file writes",
386 "suggested_config": """hooks/hooks.json:
387 "PreToolUse": [{
388 "matcher": "Write|Edit",
389 "hooks": [{
390 "type": "command",
391 "command": "ruff format --check .",
392 "timeout": 10000
393 }]
394 }]""",
395 },
396 "type_check": {
397 "hook_event": "PostToolUse",
398 "description": "Type checking after code modifications",
399 "suggested_config": """hooks/hooks.json:
400 "PostToolUse": [{
401 "matcher": "Edit|Write",
402 "hooks": [{
403 "type": "command",
404 "command": "mypy --fast .",
405 "timeout": 30000
406 }]
407 }]""",
408 },
409 "build": {
410 "hook_event": "PostToolUse",
411 "description": "Build verification after changes",
412 "suggested_config": """hooks/hooks.json:
413 "PostToolUse": [{
414 "matcher": "Edit|Write",
415 "hooks": [{
416 "type": "command",
417 "command": "npm run build",
418 "timeout": 60000
419 }]
420 }]""",
421 },
422}
425def detect_config_gaps(
426 manual_pattern_analysis: ManualPatternAnalysis,
427 project_root: Path | None = None,
428) -> ConfigGapsAnalysis:
429 """Detect configuration gaps based on manual pattern analysis.
431 Args:
432 manual_pattern_analysis: Results from detect_manual_patterns()
433 project_root: Project root directory (defaults to cwd)
435 Returns:
436 ConfigGapsAnalysis with identified gaps and coverage metrics
437 """
438 if project_root is None:
439 project_root = Path.cwd()
441 # Discover current configuration
442 current_hooks: list[str] = []
443 current_skills: list[str] = []
444 current_agents: list[str] = []
446 # Load hooks configuration
447 hooks_file = project_root / "hooks" / "hooks.json"
448 if hooks_file.exists():
449 try:
450 with open(hooks_file, encoding="utf-8") as f:
451 hooks_data = json.load(f)
452 current_hooks = list(hooks_data.get("hooks", {}).keys())
453 except Exception:
454 pass
456 # Scan for agents
457 agents_dir = project_root / "agents"
458 if agents_dir.is_dir():
459 for agent_file in agents_dir.glob("*.md"):
460 current_agents.append(agent_file.stem)
462 # Scan for skills
463 skills_dir = project_root / "skills"
464 if skills_dir.is_dir():
465 for skill_dir in skills_dir.iterdir():
466 if skill_dir.is_dir() and (skill_dir / "SKILL.md").exists():
467 current_skills.append(skill_dir.name)
469 # Identify gaps from manual patterns
470 gaps: list[ConfigGap] = []
471 covered_patterns = 0
472 recognized_patterns = 0
474 for pattern in manual_pattern_analysis.patterns:
475 config_mapping = _PATTERN_TO_CONFIG.get(pattern.pattern_type)
476 if not config_mapping:
477 continue
479 recognized_patterns += 1
480 hook_event = config_mapping["hook_event"]
482 # Check if hook event is already configured
483 if hook_event in current_hooks:
484 covered_patterns += 1
485 continue
487 # Determine priority based on occurrence count
488 if pattern.occurrence_count >= 10:
489 priority = "high"
490 elif pattern.occurrence_count >= 5:
491 priority = "medium"
492 else:
493 priority = "low"
495 gap = ConfigGap(
496 gap_type="hook",
497 description=config_mapping["description"],
498 evidence=pattern.affected_issues,
499 suggested_config=config_mapping["suggested_config"],
500 priority=priority,
501 pattern_type=pattern.pattern_type,
502 )
503 gaps.append(gap)
505 # Calculate coverage score based on recognized patterns only
506 coverage_score = covered_patterns / recognized_patterns if recognized_patterns > 0 else 1.0
508 # Sort gaps by priority (high first)
509 priority_order = {"high": 0, "medium": 1, "low": 2}
510 gaps.sort(key=lambda g: priority_order.get(g.priority, 3))
512 return ConfigGapsAnalysis(
513 gaps=gaps,
514 current_hooks=current_hooks,
515 current_skills=current_skills,
516 current_agents=current_agents,
517 coverage_score=coverage_score,
518 )