Coverage for little_loops / issue_history / debt.py: 94%
195 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 technical debt analysis: cross-cutting concerns, agent effectiveness, complexity."""
3from __future__ import annotations
5from datetime import date, timedelta
6from pathlib import Path
7from typing import Any
9from little_loops.issue_history.models import (
10 AgentEffectivenessAnalysis,
11 AgentOutcome,
12 CompletedIssue,
13 ComplexityProxy,
14 ComplexityProxyAnalysis,
15 CrossCuttingAnalysis,
16 CrossCuttingSmell,
17 HotspotAnalysis,
18 TechnicalDebtMetrics,
19)
20from little_loops.issue_history.parsing import (
21 _detect_processing_agent,
22 _extract_paths_from_issue,
23 _parse_resolution_action,
24)
26# Cross-cutting concern keywords for smell detection
27_CROSS_CUTTING_KEYWORDS: dict[str, list[str]] = {
28 "logging": ["log", "logger", "logging", "debug", "trace", "print"],
29 "error-handling": ["error", "exception", "try", "catch", "raise", "except", "fail"],
30 "validation": ["valid", "validate", "check", "assert", "verify", "sanitize"],
31 "auth": ["auth", "permission", "role", "access", "token", "credential", "login"],
32 "caching": ["cache", "memo", "memoize", "store", "ttl", "expire", "cached"],
33}
35# Suggested patterns for each cross-cutting concern type
36_CONCERN_PATTERNS: dict[str, str] = {
37 "logging": "decorator",
38 "error-handling": "middleware",
39 "validation": "decorator",
40 "auth": "middleware",
41 "caching": "decorator",
42}
45def detect_cross_cutting_smells(
46 issues: list[CompletedIssue],
47 hotspots: HotspotAnalysis,
48 contents: dict[Path, str] | None = None,
49) -> CrossCuttingAnalysis:
50 """Detect cross-cutting concerns scattered across the codebase.
52 Identifies when issues consistently touch multiple unrelated directories,
53 suggesting missing abstractions for cross-cutting concerns like logging,
54 error handling, or validation.
56 Args:
57 issues: List of completed issues
58 hotspots: Hotspot analysis results (provides directory reference)
59 contents: Pre-loaded issue file contents (path -> content)
61 Returns:
62 CrossCuttingAnalysis with detected smells
63 """
64 if not issues:
65 return CrossCuttingAnalysis()
67 # Track concern data: {concern_type: {dirs: set, issues: list}}
68 concern_data: dict[str, dict[str, Any]] = {}
69 for concern_type in _CROSS_CUTTING_KEYWORDS:
70 concern_data[concern_type] = {
71 "directories": set(),
72 "issue_ids": [],
73 }
75 # Get all unique directories from hotspots for scatter score calculation
76 all_directories: set[str] = set()
77 if hotspots.directory_hotspots:
78 all_directories = {h.path for h in hotspots.directory_hotspots}
80 # Analyze each issue
81 for issue in issues:
82 if contents is not None and issue.path in contents:
83 content = contents[issue.path]
84 else:
85 try:
86 content = issue.path.read_text(encoding="utf-8")
87 except Exception:
88 continue
89 content_lower = content.lower()
91 # Extract paths from this issue
92 paths = _extract_paths_from_issue(content)
93 issue_dirs = {str(Path(p).parent) for p in paths if "/" in p or "\\" in p}
94 all_directories.update(issue_dirs)
96 # Check if this issue touches multiple directories (3+)
97 if len(issue_dirs) < 3:
98 continue
100 # Check for concern keywords
101 for concern_type, keywords in _CROSS_CUTTING_KEYWORDS.items():
102 if any(kw in content_lower for kw in keywords):
103 concern_data[concern_type]["directories"].update(issue_dirs)
104 if issue.issue_id not in concern_data[concern_type]["issue_ids"]:
105 concern_data[concern_type]["issue_ids"].append(issue.issue_id)
107 # Build CrossCuttingSmell objects
108 smells: list[CrossCuttingSmell] = []
109 total_dirs = len(all_directories) if all_directories else 1
111 for concern_type, data in concern_data.items():
112 if data["issue_ids"]: # Only include concerns with detected issues
113 dirs = sorted(data["directories"])
114 scatter_score = len(dirs) / total_dirs if total_dirs > 0 else 0.0
116 smell = CrossCuttingSmell(
117 concern_type=concern_type,
118 affected_directories=dirs,
119 issue_count=len(data["issue_ids"]),
120 issue_ids=data["issue_ids"],
121 scatter_score=scatter_score,
122 suggested_pattern=_CONCERN_PATTERNS.get(concern_type, "aspect"),
123 )
124 smells.append(smell)
126 # Sort by scatter score descending
127 smells.sort(key=lambda s: -s.scatter_score)
129 # Identify most scattered concern
130 most_scattered = smells[0].concern_type if smells else ""
132 # Build consolidation opportunities
133 consolidation_opportunities = []
134 for smell in smells:
135 if smell.scatter_score >= 0.3: # Threshold for suggesting consolidation
136 consolidation_opportunities.append(
137 f"Centralize {smell.concern_type} ({smell.issue_count} issues would benefit)"
138 )
140 return CrossCuttingAnalysis(
141 smells=smells,
142 most_scattered_concern=most_scattered,
143 consolidation_opportunities=consolidation_opportunities[:10],
144 )
147def analyze_agent_effectiveness(
148 issues: list[CompletedIssue],
149 contents: dict[Path, str] | None = None,
150) -> AgentEffectivenessAnalysis:
151 """Analyze agent effectiveness across issue types.
153 Groups issues by processing agent and issue type, calculating
154 success/failure/rejection rates for each combination.
156 Args:
157 issues: List of completed issues
158 contents: Pre-loaded issue file contents (path -> content)
160 Returns:
161 AgentEffectivenessAnalysis with outcomes and recommendations
162 """
163 if not issues:
164 return AgentEffectivenessAnalysis()
166 # Track outcomes by (agent, issue_type)
167 outcomes_map: dict[tuple[str, str], AgentOutcome] = {}
169 for issue in issues:
170 if contents is not None and issue.path in contents:
171 content = contents[issue.path]
172 else:
173 try:
174 content = issue.path.read_text(encoding="utf-8")
175 except Exception:
176 continue
178 # Detect agent (discovered_by may contain source info in some cases)
179 agent = _detect_processing_agent(content, issue.discovered_by)
181 # Get resolution outcome
182 resolution = _parse_resolution_action(content)
184 # Get or create outcome tracker
185 key = (agent, issue.issue_type)
186 if key not in outcomes_map:
187 outcomes_map[key] = AgentOutcome(
188 agent_name=agent,
189 issue_type=issue.issue_type,
190 )
192 outcome = outcomes_map[key]
194 # Categorize outcome
195 if resolution == "completed":
196 outcome.success_count += 1
197 elif resolution in ("rejected", "invalid", "duplicate"):
198 outcome.rejection_count += 1
199 else: # deferred or other
200 outcome.failure_count += 1
202 # Build outcomes list
203 outcomes = list(outcomes_map.values())
205 # Determine best agent per issue type
206 best_agent_by_type: dict[str, str] = {}
207 type_agents: dict[str, list[AgentOutcome]] = {}
209 for outcome in outcomes:
210 if outcome.issue_type not in type_agents:
211 type_agents[outcome.issue_type] = []
212 type_agents[outcome.issue_type].append(outcome)
214 for issue_type, agent_outcomes in type_agents.items():
215 # Require minimum sample size
216 significant_outcomes = [o for o in agent_outcomes if o.total_count >= 3]
217 if significant_outcomes:
218 best = max(significant_outcomes, key=lambda o: o.success_rate)
219 best_agent_by_type[issue_type] = best.agent_name
221 # Identify problematic combinations (success rate < 50% with >= 5 samples)
222 problematic_combinations: list[tuple[str, str, str]] = []
223 for outcome in outcomes:
224 if outcome.total_count >= 5 and outcome.success_rate < 0.5:
225 reason = (
226 f"{outcome.success_rate * 100:.0f}% success "
227 f"({outcome.success_count}/{outcome.total_count})"
228 )
229 problematic_combinations.append((outcome.agent_name, outcome.issue_type, reason))
231 # Sort by success rate ascending (worst first)
232 problematic_combinations.sort(key=lambda x: float(x[2].split("%")[0]))
234 return AgentEffectivenessAnalysis(
235 outcomes=sorted(outcomes, key=lambda o: (o.agent_name, o.issue_type)),
236 best_agent_by_type=best_agent_by_type,
237 problematic_combinations=problematic_combinations,
238 )
241def analyze_complexity_proxy(
242 issues: list[CompletedIssue],
243 hotspots: HotspotAnalysis,
244 contents: dict[Path, str] | None = None,
245) -> ComplexityProxyAnalysis:
246 """Use issue duration as proxy for code complexity.
248 Areas that consistently take longer to resolve suggest higher complexity,
249 insufficient documentation, or accumulated technical debt.
251 Args:
252 issues: List of completed issues with dates
253 hotspots: Pre-computed hotspot analysis for path information
254 contents: Pre-loaded issue file contents (path -> content)
256 Returns:
257 ComplexityProxyAnalysis with duration-based complexity metrics
258 """
259 # Calculate durations for all issues with both dates
260 issue_durations: dict[str, float] = {} # issue_id -> days
261 for issue in issues:
262 if issue.discovered_date and issue.completed_date:
263 delta = issue.completed_date - issue.discovered_date
264 days = float(delta.days)
265 if days >= 0: # Sanity check
266 issue_durations[issue.issue_id] = days
268 if not issue_durations:
269 return ComplexityProxyAnalysis()
271 # Calculate baseline (median duration)
272 all_durations = sorted(issue_durations.values())
273 n = len(all_durations)
274 if n % 2 == 0:
275 baseline_days = (all_durations[n // 2 - 1] + all_durations[n // 2]) / 2
276 else:
277 baseline_days = all_durations[n // 2]
279 if baseline_days == 0:
280 baseline_days = 1.0 # Avoid division by zero
282 # Map issues to their affected files by reading issue content
283 issue_to_files: dict[str, list[str]] = {}
284 for issue in issues:
285 if issue.issue_id in issue_durations:
286 if contents is not None and issue.path in contents:
287 content = contents[issue.path]
288 else:
289 try:
290 content = issue.path.read_text(encoding="utf-8")
291 except Exception:
292 continue
293 paths = _extract_paths_from_issue(content)
294 if paths:
295 issue_to_files[issue.issue_id] = paths
297 # Aggregate durations by file
298 file_durations: dict[str, list[tuple[str, float]]] = {} # path -> [(issue_id, days), ...]
299 for issue_id, files in issue_to_files.items():
300 days = issue_durations[issue_id]
301 for f in files:
302 if f not in file_durations:
303 file_durations[f] = []
304 file_durations[f].append((issue_id, days))
306 # Aggregate durations by directory
307 dir_durations: dict[str, list[tuple[str, float]]] = {}
308 for path, entries in file_durations.items():
309 dir_path = "/".join(path.split("/")[:-1]) + "/" if "/" in path else "./"
310 if dir_path not in dir_durations:
311 dir_durations[dir_path] = []
312 dir_durations[dir_path].extend(entries)
314 # Build file complexity proxies
315 file_complexity: list[ComplexityProxy] = []
316 for path, entries in file_durations.items():
317 if len(entries) < 2: # Need at least 2 data points
318 continue
320 durations = [d for _, d in entries]
321 avg = sum(durations) / len(durations)
322 sorted_d = sorted(durations)
323 median = sorted_d[len(sorted_d) // 2]
324 slowest = max(entries, key=lambda x: x[1])
326 # Normalize complexity score (0-1 based on how much slower than baseline)
327 ratio = avg / baseline_days
328 complexity_score = min(1.0, (ratio - 1) / 4) # 5x slower = 1.0
329 complexity_score = max(0.0, complexity_score)
331 comparison = f"{ratio:.1f}x baseline" if ratio >= 1.5 else "near baseline"
333 file_complexity.append(
334 ComplexityProxy(
335 path=path,
336 avg_resolution_days=avg,
337 median_resolution_days=median,
338 issue_count=len(entries),
339 slowest_issue=slowest,
340 complexity_score=complexity_score,
341 comparison_to_baseline=comparison,
342 )
343 )
345 # Build directory complexity proxies
346 directory_complexity: list[ComplexityProxy] = []
347 for dir_path, entries in dir_durations.items():
348 if len(entries) < 3: # Need at least 3 data points for directories
349 continue
351 # Deduplicate by issue_id for directory-level stats
352 unique_entries: dict[str, float] = {}
353 for issue_id, days in entries:
354 if issue_id not in unique_entries or days > unique_entries[issue_id]:
355 unique_entries[issue_id] = days
357 entries_list = list(unique_entries.items())
358 durations = list(unique_entries.values())
359 avg = sum(durations) / len(durations)
360 sorted_d = sorted(durations)
361 median = sorted_d[len(sorted_d) // 2]
362 slowest = max(entries_list, key=lambda x: x[1])
364 ratio = avg / baseline_days
365 complexity_score = min(1.0, (ratio - 1) / 4)
366 complexity_score = max(0.0, complexity_score)
368 comparison = f"{ratio:.1f}x baseline" if ratio >= 1.5 else "near baseline"
370 directory_complexity.append(
371 ComplexityProxy(
372 path=dir_path,
373 avg_resolution_days=avg,
374 median_resolution_days=median,
375 issue_count=len(unique_entries),
376 slowest_issue=slowest,
377 complexity_score=complexity_score,
378 comparison_to_baseline=comparison,
379 )
380 )
382 # Sort by complexity score descending
383 file_complexity.sort(key=lambda c: -c.complexity_score)
384 directory_complexity.sort(key=lambda c: -c.complexity_score)
386 # Identify outliers (>2x baseline)
387 complexity_outliers = [
388 c.path for c in file_complexity if c.avg_resolution_days > baseline_days * 2
389 ]
391 return ComplexityProxyAnalysis(
392 file_complexity=file_complexity[:10],
393 directory_complexity=directory_complexity[:10],
394 baseline_days=baseline_days,
395 complexity_outliers=complexity_outliers[:10],
396 )
399def _calculate_debt_metrics(
400 completed_issues: list[CompletedIssue],
401 active_issues: list[tuple[Path, str, str, date | None]],
402) -> TechnicalDebtMetrics:
403 """Calculate technical debt health metrics.
405 Args:
406 completed_issues: List of completed issues
407 active_issues: List of active issue tuples
409 Returns:
410 TechnicalDebtMetrics with calculated values
411 """
412 today = date.today()
413 metrics = TechnicalDebtMetrics()
415 # Backlog size
416 metrics.backlog_size = len(active_issues)
418 # Count aging and high priority
419 for _path, _issue_type, priority, discovered_date in active_issues:
420 if priority in ("P0", "P1"):
421 metrics.high_priority_open += 1
423 if discovered_date:
424 age = (today - discovered_date).days
425 if age >= 30:
426 metrics.aging_30_plus += 1
427 if age >= 60:
428 metrics.aging_60_plus += 1
430 # Calculate backlog growth rate (issues per week)
431 # Look at last 4 weeks of completions vs creations
432 four_weeks_ago = today - timedelta(days=28)
434 completed_recently = sum(
435 1 for i in completed_issues if i.completed_date and i.completed_date >= four_weeks_ago
436 )
438 created_recently = sum(1 for _, _, _, d in active_issues if d and d >= four_weeks_ago)
440 # Net change per week
441 if completed_recently > 0 or created_recently > 0:
442 metrics.backlog_growth_rate = (created_recently - completed_recently) / 4.0
444 # Debt paydown ratio (bug fixes vs features)
445 bug_count = sum(1 for i in completed_issues if i.issue_type == "BUG")
446 feat_count = sum(1 for i in completed_issues if i.issue_type == "FEAT")
448 if feat_count > 0:
449 metrics.debt_paydown_ratio = bug_count / feat_count
450 elif bug_count > 0:
451 metrics.debt_paydown_ratio = float(bug_count) # All maintenance
453 return metrics