Coverage for little_loops / issue_history / summary.py: 60%
124 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 summary and period metrics analysis."""
3from __future__ import annotations
5from collections import defaultdict
6from datetime import date, timedelta
7from pathlib import Path
8from typing import Literal
10from little_loops.issue_history.models import (
11 CompletedIssue,
12 HistorySummary,
13 PeriodMetrics,
14 SubsystemHealth,
15)
16from little_loops.issue_history.parsing import _extract_subsystem
19def calculate_summary(issues: list[CompletedIssue]) -> HistorySummary:
20 """Calculate summary statistics from issues.
22 Args:
23 issues: List of CompletedIssue objects
25 Returns:
26 HistorySummary with calculated statistics
27 """
28 type_counts: dict[str, int] = {}
29 priority_counts: dict[str, int] = {}
30 discovery_counts: dict[str, int] = {}
31 dates: list[date] = []
33 for issue in issues:
34 # Count by type
35 type_counts[issue.issue_type] = type_counts.get(issue.issue_type, 0) + 1
37 # Count by priority
38 priority_counts[issue.priority] = priority_counts.get(issue.priority, 0) + 1
40 # Count by discovery source
41 source = issue.discovered_by or "unknown"
42 discovery_counts[source] = discovery_counts.get(source, 0) + 1
44 # Collect dates
45 if issue.completed_date:
46 dates.append(issue.completed_date)
48 # Sort counts for consistent output
49 type_counts = dict(sorted(type_counts.items()))
50 priority_counts = dict(sorted(priority_counts.items()))
51 discovery_counts = dict(sorted(discovery_counts.items(), key=lambda x: (-x[1], x[0])))
53 return HistorySummary(
54 total_count=len(issues),
55 type_counts=type_counts,
56 priority_counts=priority_counts,
57 discovery_counts=discovery_counts,
58 earliest_date=min(dates) if dates else None,
59 latest_date=max(dates) if dates else None,
60 )
63def _calculate_period_label(start: date, period_type: str) -> str:
64 """Generate human-readable period label.
66 Args:
67 start: Period start date
68 period_type: "weekly", "monthly", "quarterly"
70 Returns:
71 Label like "Q1 2025", "Jan 2025", "Week 3 2025"
72 """
73 if period_type == "quarterly":
74 quarter = (start.month - 1) // 3 + 1
75 return f"Q{quarter} {start.year}"
76 elif period_type == "monthly":
77 return start.strftime("%b %Y")
78 else: # weekly
79 week_num = start.isocalendar()[1]
80 return f"Week {week_num} {start.year}"
83def _group_by_period(
84 issues: list[CompletedIssue],
85 period_type: Literal["weekly", "monthly", "quarterly"] = "monthly",
86) -> list[PeriodMetrics]:
87 """Group issues by time period and calculate metrics.
89 Args:
90 issues: List of completed issues with dates
91 period_type: Grouping period
93 Returns:
94 List of PeriodMetrics sorted by date ascending
95 """
96 # Filter issues with dates
97 dated_issues = [i for i in issues if i.completed_date]
98 if not dated_issues:
99 return []
101 # Sort by date
102 dated_issues.sort(key=lambda i: i.completed_date) # type: ignore
104 # Determine period boundaries
105 periods: dict[str, list[CompletedIssue]] = defaultdict(list)
107 for issue in dated_issues:
108 completed = issue.completed_date
109 assert completed is not None
111 if period_type == "quarterly":
112 quarter = (completed.month - 1) // 3
113 period_start = date(completed.year, quarter * 3 + 1, 1)
114 elif period_type == "monthly":
115 period_start = date(completed.year, completed.month, 1)
116 else: # weekly
117 # Start of week (Monday)
118 period_start = completed - timedelta(days=completed.weekday())
120 key = period_start.isoformat()
121 periods[key].append(issue)
123 # Calculate metrics for each period
124 result: list[PeriodMetrics] = []
125 for period_key in sorted(periods.keys()):
126 period_issues = periods[period_key]
127 period_start = date.fromisoformat(period_key)
129 # Calculate period end
130 if period_type == "quarterly":
131 month = period_start.month + 3
132 year = period_start.year
133 if month > 12:
134 month = 1
135 year += 1
136 period_end = date(year, month, 1) - timedelta(days=1)
137 elif period_type == "monthly":
138 month = period_start.month + 1
139 year = period_start.year
140 if month > 12:
141 month = 1
142 year += 1
143 period_end = date(year, month, 1) - timedelta(days=1)
144 else: # weekly
145 period_end = period_start + timedelta(days=6)
147 # Count types and priorities
148 type_counts: dict[str, int] = {}
149 priority_counts: dict[str, int] = {}
151 for issue in period_issues:
152 type_counts[issue.issue_type] = type_counts.get(issue.issue_type, 0) + 1
153 priority_counts[issue.priority] = priority_counts.get(issue.priority, 0) + 1
155 result.append(
156 PeriodMetrics(
157 period_start=period_start,
158 period_end=period_end,
159 period_label=_calculate_period_label(period_start, period_type),
160 total_completed=len(period_issues),
161 type_counts=dict(sorted(type_counts.items())),
162 priority_counts=dict(sorted(priority_counts.items())),
163 )
164 )
166 return result
169def _calculate_trend(values: list[float]) -> str:
170 """Determine trend from a series of values.
172 Args:
173 values: Time-ordered series of values
175 Returns:
176 "increasing", "decreasing", or "stable"
177 """
178 if len(values) < 3:
179 return "stable"
181 # Simple linear regression slope
182 n = len(values)
183 sum_x = sum(range(n))
184 sum_y = sum(values)
185 sum_xy = sum(i * v for i, v in enumerate(values))
186 sum_x2 = sum(i * i for i in range(n))
188 denominator = n * sum_x2 - sum_x * sum_x
189 if denominator == 0:
190 return "stable"
192 slope = (n * sum_xy - sum_x * sum_y) / denominator
194 # Normalize slope by average value
195 avg = sum_y / n if n > 0 else 1
196 if avg == 0:
197 avg = 1
198 normalized_slope = slope / avg
200 if normalized_slope > 0.05:
201 return "increasing"
202 elif normalized_slope < -0.05:
203 return "decreasing"
204 return "stable"
207def _analyze_subsystems(
208 issues: list[CompletedIssue],
209 recent_days: int = 30,
210 contents: dict[Path, str] | None = None,
211) -> list[SubsystemHealth]:
212 """Analyze health by subsystem/directory.
214 Args:
215 issues: List of completed issues
216 recent_days: Days to consider "recent"
217 contents: Pre-loaded issue file contents (path -> content)
219 Returns:
220 List of SubsystemHealth sorted by total issues descending
221 """
222 subsystems: dict[str, SubsystemHealth] = {}
223 cutoff = date.today() - timedelta(days=recent_days)
225 for issue in issues:
226 if contents is not None and issue.path in contents:
227 content = contents[issue.path]
228 else:
229 try:
230 content = issue.path.read_text(encoding="utf-8")
231 except Exception:
232 continue
234 subsystem = _extract_subsystem(content)
235 if not subsystem:
236 continue
238 if subsystem not in subsystems:
239 subsystems[subsystem] = SubsystemHealth(subsystem=subsystem)
241 health = subsystems[subsystem]
242 health.total_issues += 1
243 health.issue_ids.append(issue.issue_id)
245 if issue.completed_date and issue.completed_date >= cutoff:
246 health.recent_issues += 1
248 # Calculate trends based on recent vs historical ratio
249 for health in subsystems.values():
250 if health.total_issues >= 5:
251 recent_ratio = health.recent_issues / health.total_issues
252 if recent_ratio > 0.5:
253 health.trend = "degrading"
254 elif recent_ratio < 0.2:
255 health.trend = "improving"
257 # Sort by total issues descending
258 result = sorted(subsystems.values(), key=lambda s: -s.total_issues)
259 return result[:10] # Top 10