Coverage for little_loops / issue_history / summary.py: 0%

122 statements  

« prev     ^ index     » next       coverage.py v7.12.0, created at 2026-03-14 23:20 -0500

1"""Issue history summary and period metrics analysis.""" 

2 

3from __future__ import annotations 

4 

5from collections import defaultdict 

6from datetime import date, timedelta 

7from pathlib import Path 

8from typing import Literal 

9 

10from little_loops.issue_history._utils import get_issue_content 

11from little_loops.issue_history.models import ( 

12 CompletedIssue, 

13 HistorySummary, 

14 PeriodMetrics, 

15 SubsystemHealth, 

16) 

17from little_loops.issue_history.parsing import _extract_subsystem 

18 

19 

20def calculate_summary(issues: list[CompletedIssue]) -> HistorySummary: 

21 """Calculate summary statistics from issues. 

22 

23 Args: 

24 issues: List of CompletedIssue objects 

25 

26 Returns: 

27 HistorySummary with calculated statistics 

28 """ 

29 type_counts: dict[str, int] = {} 

30 priority_counts: dict[str, int] = {} 

31 discovery_counts: dict[str, int] = {} 

32 dates: list[date] = [] 

33 

34 for issue in issues: 

35 # Count by type 

36 type_counts[issue.issue_type] = type_counts.get(issue.issue_type, 0) + 1 

37 

38 # Count by priority 

39 priority_counts[issue.priority] = priority_counts.get(issue.priority, 0) + 1 

40 

41 # Count by discovery source 

42 source = issue.discovered_by or "unknown" 

43 discovery_counts[source] = discovery_counts.get(source, 0) + 1 

44 

45 # Collect dates 

46 if issue.completed_date: 

47 dates.append(issue.completed_date) 

48 

49 # Sort counts for consistent output 

50 type_counts = dict(sorted(type_counts.items())) 

51 priority_counts = dict(sorted(priority_counts.items())) 

52 discovery_counts = dict(sorted(discovery_counts.items(), key=lambda x: (-x[1], x[0]))) 

53 

54 return HistorySummary( 

55 total_count=len(issues), 

56 type_counts=type_counts, 

57 priority_counts=priority_counts, 

58 discovery_counts=discovery_counts, 

59 earliest_date=min(dates) if dates else None, 

60 latest_date=max(dates) if dates else None, 

61 ) 

62 

63 

64def _calculate_period_label(start: date, period_type: str) -> str: 

65 """Generate human-readable period label. 

66 

67 Args: 

68 start: Period start date 

69 period_type: "weekly", "monthly", "quarterly" 

70 

71 Returns: 

72 Label like "Q1 2025", "Jan 2025", "Week 3 2025" 

73 """ 

74 if period_type == "quarterly": 

75 quarter = (start.month - 1) // 3 + 1 

76 return f"Q{quarter} {start.year}" 

77 elif period_type == "monthly": 

78 return start.strftime("%b %Y") 

79 else: # weekly 

80 week_num = start.isocalendar()[1] 

81 return f"Week {week_num} {start.year}" 

82 

83 

84def _group_by_period( 

85 issues: list[CompletedIssue], 

86 period_type: Literal["weekly", "monthly", "quarterly"] = "monthly", 

87) -> list[PeriodMetrics]: 

88 """Group issues by time period and calculate metrics. 

89 

90 Args: 

91 issues: List of completed issues with dates 

92 period_type: Grouping period 

93 

94 Returns: 

95 List of PeriodMetrics sorted by date ascending 

96 """ 

97 # Filter issues with dates 

98 dated_issues = [i for i in issues if i.completed_date] 

99 if not dated_issues: 

100 return [] 

101 

102 # Sort by date 

103 dated_issues.sort(key=lambda i: i.completed_date) # type: ignore 

104 

105 # Determine period boundaries 

106 periods: dict[str, list[CompletedIssue]] = defaultdict(list) 

107 

108 for issue in dated_issues: 

109 completed = issue.completed_date 

110 assert completed is not None 

111 

112 if period_type == "quarterly": 

113 quarter = (completed.month - 1) // 3 

114 period_start = date(completed.year, quarter * 3 + 1, 1) 

115 elif period_type == "monthly": 

116 period_start = date(completed.year, completed.month, 1) 

117 else: # weekly 

118 # Start of week (Monday) 

119 period_start = completed - timedelta(days=completed.weekday()) 

120 

121 key = period_start.isoformat() 

122 periods[key].append(issue) 

123 

124 # Calculate metrics for each period 

125 result: list[PeriodMetrics] = [] 

126 for period_key in sorted(periods.keys()): 

127 period_issues = periods[period_key] 

128 period_start = date.fromisoformat(period_key) 

129 

130 # Calculate period end 

131 if period_type == "quarterly": 

132 month = period_start.month + 3 

133 year = period_start.year 

134 if month > 12: 

135 month = 1 

136 year += 1 

137 period_end = date(year, month, 1) - timedelta(days=1) 

138 elif period_type == "monthly": 

139 month = period_start.month + 1 

140 year = period_start.year 

141 if month > 12: 

142 month = 1 

143 year += 1 

144 period_end = date(year, month, 1) - timedelta(days=1) 

145 else: # weekly 

146 period_end = period_start + timedelta(days=6) 

147 

148 # Count types and priorities 

149 type_counts: dict[str, int] = {} 

150 priority_counts: dict[str, int] = {} 

151 

152 for issue in period_issues: 

153 type_counts[issue.issue_type] = type_counts.get(issue.issue_type, 0) + 1 

154 priority_counts[issue.priority] = priority_counts.get(issue.priority, 0) + 1 

155 

156 result.append( 

157 PeriodMetrics( 

158 period_start=period_start, 

159 period_end=period_end, 

160 period_label=_calculate_period_label(period_start, period_type), 

161 total_completed=len(period_issues), 

162 type_counts=dict(sorted(type_counts.items())), 

163 priority_counts=dict(sorted(priority_counts.items())), 

164 ) 

165 ) 

166 

167 return result 

168 

169 

170def _calculate_trend(values: list[float]) -> str: 

171 """Determine trend from a series of values. 

172 

173 Args: 

174 values: Time-ordered series of values 

175 

176 Returns: 

177 "increasing", "decreasing", or "stable" 

178 """ 

179 if len(values) < 3: 

180 return "stable" 

181 

182 # Simple linear regression slope 

183 n = len(values) 

184 sum_x = sum(range(n)) 

185 sum_y = sum(values) 

186 sum_xy = sum(i * v for i, v in enumerate(values)) 

187 sum_x2 = sum(i * i for i in range(n)) 

188 

189 denominator = n * sum_x2 - sum_x * sum_x 

190 if denominator == 0: 

191 return "stable" 

192 

193 slope = (n * sum_xy - sum_x * sum_y) / denominator 

194 

195 # Normalize slope by average value 

196 avg = sum_y / n if n > 0 else 1 

197 if avg == 0: 

198 avg = 1 

199 normalized_slope = slope / avg 

200 

201 if normalized_slope > 0.05: 

202 return "increasing" 

203 elif normalized_slope < -0.05: 

204 return "decreasing" 

205 return "stable" 

206 

207 

208def _analyze_subsystems( 

209 issues: list[CompletedIssue], 

210 recent_days: int = 30, 

211 contents: dict[Path, str] | None = None, 

212) -> list[SubsystemHealth]: 

213 """Analyze health by subsystem/directory. 

214 

215 Args: 

216 issues: List of completed issues 

217 recent_days: Days to consider "recent" 

218 contents: Pre-loaded issue file contents (path -> content) 

219 

220 Returns: 

221 List of SubsystemHealth sorted by total issues descending 

222 """ 

223 subsystems: dict[str, SubsystemHealth] = {} 

224 cutoff = date.today() - timedelta(days=recent_days) 

225 

226 for issue in issues: 

227 content = get_issue_content(issue, contents) 

228 if content is None: 

229 continue 

230 

231 subsystem = _extract_subsystem(content) 

232 if not subsystem: 

233 continue 

234 

235 if subsystem not in subsystems: 

236 subsystems[subsystem] = SubsystemHealth(subsystem=subsystem) 

237 

238 health = subsystems[subsystem] 

239 health.total_issues += 1 

240 health.issue_ids.append(issue.issue_id) 

241 

242 if issue.completed_date and issue.completed_date >= cutoff: 

243 health.recent_issues += 1 

244 

245 # Calculate trends based on recent vs historical ratio 

246 for health in subsystems.values(): 

247 if health.total_issues >= 5: 

248 recent_ratio = health.recent_issues / health.total_issues 

249 if recent_ratio > 0.5: 

250 health.trend = "degrading" 

251 elif recent_ratio < 0.2: 

252 health.trend = "improving" 

253 

254 # Sort by total issues descending 

255 result = sorted(subsystems.values(), key=lambda s: -s.total_issues) 

256 return result[:10] # Top 10