Coverage for little_loops / cli / sprint / _helpers.py: 5%

153 statements  

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

1"""Shared helpers for ll-sprint CLI subcommands.""" 

2 

3from __future__ import annotations 

4 

5from typing import TYPE_CHECKING, Any 

6 

7from little_loops.cli.output import PRIORITY_COLOR, TYPE_COLOR, colorize, terminal_width 

8 

9if TYPE_CHECKING: 

10 from little_loops.config import DependencyMappingConfig 

11 from little_loops.dependency_graph import DependencyGraph, WaveContentionNote 

12 from little_loops.logger import Logger 

13 

14 

15def _score_suffix(issue: Any) -> str: 

16 """Build an inline score suffix like ' [ready: 85, conf: 72]'.""" 

17 cs = getattr(issue, "confidence_score", None) 

18 oc = getattr(issue, "outcome_confidence", None) 

19 if cs is None and oc is None: 

20 return "" 

21 parts: list[str] = [] 

22 if cs is not None: 

23 parts.append(f"ready: {cs}") 

24 if oc is not None: 

25 parts.append(f"conf: {oc}") 

26 return f" [{', '.join(parts)}]" 

27 

28 

29def _render_execution_plan( 

30 waves: list[list[Any]], 

31 dep_graph: DependencyGraph, 

32 contention_notes: list[WaveContentionNote | None] | None = None, 

33) -> str: 

34 """Render execution plan with wave groupings. 

35 

36 Args: 

37 waves: List of execution waves from get_execution_waves() 

38 dep_graph: DependencyGraph for looking up blockers 

39 contention_notes: Optional per-wave contention annotations from 

40 refine_waves_for_contention(). Same length as waves. 

41 

42 Returns: 

43 Formatted string showing wave structure 

44 """ 

45 if not waves: 

46 return "" 

47 

48 # Build logical wave groups: consecutive sub-waves from the same 

49 # parent_wave_index are grouped together. 

50 logical_waves: list[list[int]] = [] # each entry is list of indices into waves 

51 notes = contention_notes or [None] * len(waves) 

52 

53 for idx in range(len(waves)): 

54 note = notes[idx] if idx < len(notes) else None 

55 if note is not None: 

56 # Check if this belongs to the same parent as the previous group 

57 if logical_waves and notes[logical_waves[-1][0]] is not None: 

58 prev_note = notes[logical_waves[-1][0]] 

59 if prev_note and prev_note.parent_wave_index == note.parent_wave_index: 

60 logical_waves[-1].append(idx) 

61 continue 

62 logical_waves.append([idx]) 

63 else: 

64 logical_waves.append([idx]) 

65 

66 total_issues = sum(len(wave) for wave in waves) 

67 num_logical = len(logical_waves) 

68 lines: list[str] = [] 

69 

70 width = terminal_width() 

71 wave_word = "wave" if num_logical == 1 else "waves" 

72 header_text = f"Execution Plan ({total_issues} issues, {num_logical} {wave_word})" 

73 fill = "\u2500" * max(0, width - len(header_text) - 4) 

74 lines.append("") 

75 lines.append(f"\u2500\u2500 {header_text} {fill}") 

76 

77 max_title = max(45, width - 30) 

78 

79 for logical_idx, group in enumerate(logical_waves): 

80 lines.append("") 

81 logical_num = logical_idx + 1 

82 group_issues = [issue for widx in group for issue in waves[widx]] 

83 group_count = len(group_issues) 

84 is_contention = len(group) > 1 

85 

86 if is_contention: 

87 # Multiple sub-waves from overlap splitting 

88 lines.append( 

89 f"Wave {logical_num} ({group_count} issues, serialized \u2014 file overlap):" 

90 ) 

91 step = 0 

92 for widx in group: 

93 for issue in waves[widx]: 

94 step += 1 

95 lines.append(f" Step {step}/{group_count}:") 

96 

97 # Truncate title if too long 

98 title = issue.title 

99 if len(title) > max_title: 

100 title = title[: max_title - 3] + "..." 

101 

102 issue_type = issue.issue_id.split("-", 1)[0] 

103 colored_id = colorize(issue.issue_id, TYPE_COLOR.get(issue_type, "0")) 

104 colored_priority = colorize( 

105 issue.priority, PRIORITY_COLOR.get(issue.priority, "0") 

106 ) 

107 score_suffix = _score_suffix(issue) 

108 lines.append( 

109 f" \u2514\u2500\u2500 {colored_id}: {title} ({colored_priority}){score_suffix}" 

110 ) 

111 if hasattr(issue, "path") and issue.path: 

112 lines.append(f" {issue.path}") 

113 

114 # Show blockers for this issue 

115 blockers = dep_graph.blocked_by.get(issue.issue_id, set()) 

116 if blockers: 

117 blockers_str = ", ".join(sorted(blockers)) 

118 lines.append(f" blocked by: {blockers_str}") 

119 

120 # Show contended files once at the end of the group 

121 first_note = notes[group[0]] 

122 if first_note: 

123 paths_str = ", ".join(first_note.contended_paths[:2]) 

124 extra = len(first_note.contended_paths) - 2 

125 if extra > 0: 

126 paths_str += f" +{extra} more" 

127 lines.append(f" Contended files: {paths_str}") 

128 else: 

129 # Single wave (no overlap splitting) 

130 widx = group[0] 

131 wave = waves[widx] 

132 

133 if logical_num == 1: 

134 parallel_note = "(parallel)" if len(wave) > 1 else "" 

135 else: 

136 parallel_note = f"(after Wave {logical_num - 1})" 

137 if len(wave) > 1: 

138 parallel_note += " parallel" 

139 lines.append(f"Wave {logical_num} {parallel_note}:".strip()) 

140 

141 for i, issue in enumerate(wave): 

142 is_last = i == len(wave) - 1 

143 prefix = " \u2514\u2500\u2500 " if is_last else " \u251c\u2500\u2500 " 

144 

145 # Truncate title if too long 

146 title = issue.title 

147 if len(title) > max_title: 

148 title = title[: max_title - 3] + "..." 

149 

150 issue_type = issue.issue_id.split("-", 1)[0] 

151 colored_id = colorize(issue.issue_id, TYPE_COLOR.get(issue_type, "0")) 

152 colored_priority = colorize(issue.priority, PRIORITY_COLOR.get(issue.priority, "0")) 

153 score_suffix = _score_suffix(issue) 

154 lines.append(f"{prefix}{colored_id}: {title} ({colored_priority}){score_suffix}") 

155 

156 # Show file path 

157 path_indent = " " if is_last else " \u2502 " 

158 if hasattr(issue, "path") and issue.path: 

159 lines.append(f"{path_indent}{issue.path}") 

160 

161 # Show blockers for this issue 

162 blockers = dep_graph.blocked_by.get(issue.issue_id, set()) 

163 if blockers: 

164 blocker_prefix = ( 

165 " \u2514\u2500\u2500 " if is_last else " \u2502 \u2514\u2500\u2500 " 

166 ) 

167 blockers_str = ", ".join(sorted(blockers)) 

168 lines.append(f"{blocker_prefix}blocked by: {blockers_str}") 

169 

170 return "\n".join(lines) 

171 

172 

173def _build_issue_contents(issue_infos: list) -> dict[str, str]: 

174 """Build issue_id -> file content mapping for dependency analysis.""" 

175 return {info.issue_id: info.path.read_text() for info in issue_infos if info.path.exists()} 

176 

177 

178def _render_dependency_analysis( 

179 report: Any, 

180 logger: Logger, 

181 issue_to_wave: dict[str, int] | None = None, 

182 *, 

183 config: DependencyMappingConfig | None = None, 

184) -> None: 

185 """Display dependency analysis results in CLI format. 

186 

187 Args: 

188 report: DependencyReport from analyze_dependencies() 

189 logger: Logger instance 

190 issue_to_wave: Optional mapping of issue_id -> wave index. When 

191 provided, proposals where the target already runs before the 

192 source in wave ordering are counted as "already handled". 

193 config: Optional dependency mapping config for custom thresholds. 

194 """ 

195 if not report.proposals and not report.validation.has_issues: 

196 return 

197 

198 logger.header("Dependency Analysis", char="-", width=60) 

199 

200 if report.proposals: 

201 # Partition proposals into novel vs already-satisfied 

202 novel: list[Any] = [] 

203 satisfied_count = 0 

204 for p in report.proposals: 

205 if issue_to_wave is not None: 

206 target_wave = issue_to_wave.get(p.target_id) 

207 source_wave = issue_to_wave.get(p.source_id) 

208 if ( 

209 target_wave is not None 

210 and source_wave is not None 

211 and target_wave < source_wave 

212 ): 

213 satisfied_count += 1 

214 continue 

215 novel.append(p) 

216 

217 if novel: 

218 logger.warning(f"Found {len(novel)} potential missing dependency(ies):") 

219 high_threshold = config.high_conflict_threshold if config else 0.7 

220 conflict_threshold = config.conflict_threshold if config else 0.4 

221 for p in novel: 

222 if p.conflict_score >= high_threshold: 

223 conflict = "HIGH" 

224 elif p.conflict_score >= conflict_threshold: 

225 conflict = "MEDIUM" 

226 else: 

227 conflict = "LOW" 

228 logger.warning( 

229 f" {p.source_id} may depend on {p.target_id} " 

230 f"({conflict} conflict, {p.confidence:.0%} confidence)" 

231 ) 

232 if p.overlapping_files: 

233 files = ", ".join(p.overlapping_files[:3]) 

234 if len(p.overlapping_files) > 3: 

235 files += " and more" 

236 logger.info(f" Shared files: {files}") 

237 

238 if satisfied_count > 0: 

239 total = len(report.proposals) 

240 if not novel: 

241 dep_word = "dependency" if total == 1 else "dependencies" 

242 logger.info(f"All {total} potential {dep_word} already handled by wave ordering.") 

243 else: 

244 logger.info(f"({satisfied_count} additional already handled by wave ordering)") 

245 

246 if report.validation.has_issues: 

247 v = report.validation 

248 if v.broken_refs: 

249 for issue_id, ref_id in v.broken_refs: 

250 logger.warning(f" {issue_id}: references nonexistent {ref_id}") 

251 if v.stale_completed_refs: 

252 for issue_id, ref_id in v.stale_completed_refs: 

253 logger.warning(f" {issue_id}: blocked by {ref_id} (completed)") 

254 if v.missing_backlinks: 

255 for issue_id, ref_id in v.missing_backlinks: 

256 logger.warning(f" {issue_id} blocked by {ref_id}, but {ref_id} missing backlink") 

257 

258 logger.info("Run /ll:map-dependencies to apply discovered dependencies") 

259 print() # blank line separator