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

126 statements  

« prev     ^ index     » next       coverage.py v7.12.0, created at 2026-03-04 01:17 -0600

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

2 

3from __future__ import annotations 

4 

5from typing import TYPE_CHECKING, Any 

6 

7if TYPE_CHECKING: 

8 from little_loops.config import DependencyMappingConfig 

9 from little_loops.dependency_graph import DependencyGraph, WaveContentionNote 

10 from little_loops.logger import Logger 

11 

12 

13def _render_execution_plan( 

14 waves: list[list[Any]], 

15 dep_graph: DependencyGraph, 

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

17) -> str: 

18 """Render execution plan with wave groupings. 

19 

20 Args: 

21 waves: List of execution waves from get_execution_waves() 

22 dep_graph: DependencyGraph for looking up blockers 

23 contention_notes: Optional per-wave contention annotations from 

24 refine_waves_for_contention(). Same length as waves. 

25 

26 Returns: 

27 Formatted string showing wave structure 

28 """ 

29 if not waves: 

30 return "" 

31 

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

33 # parent_wave_index are grouped together. 

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

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

36 

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

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

39 if note is not None: 

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

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

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

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

44 logical_waves[-1].append(idx) 

45 continue 

46 logical_waves.append([idx]) 

47 else: 

48 logical_waves.append([idx]) 

49 

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

51 num_logical = len(logical_waves) 

52 lines: list[str] = [] 

53 

54 lines.append("") 

55 lines.append("=" * 70) 

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

57 lines.append(f"EXECUTION PLAN ({total_issues} issues, {num_logical} {wave_word})") 

58 lines.append("=" * 70) 

59 

60 for logical_idx, group in enumerate(logical_waves): 

61 lines.append("") 

62 logical_num = logical_idx + 1 

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

64 group_count = len(group_issues) 

65 is_contention = len(group) > 1 

66 

67 if is_contention: 

68 # Multiple sub-waves from overlap splitting 

69 lines.append( 

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

71 ) 

72 step = 0 

73 for widx in group: 

74 for issue in waves[widx]: 

75 step += 1 

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

77 

78 # Truncate title if too long 

79 title = issue.title 

80 if len(title) > 45: 

81 title = title[:42] + "..." 

82 

83 lines.append( 

84 f" \u2514\u2500\u2500 {issue.issue_id}: {title} ({issue.priority})" 

85 ) 

86 

87 # Show blockers for this issue 

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

89 if blockers: 

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

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

92 

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

94 first_note = notes[group[0]] 

95 if first_note: 

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

97 extra = len(first_note.contended_paths) - 2 

98 if extra > 0: 

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

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

101 else: 

102 # Single wave (no overlap splitting) 

103 widx = group[0] 

104 wave = waves[widx] 

105 

106 if logical_num == 1: 

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

108 else: 

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

110 if len(wave) > 1: 

111 parallel_note += " parallel" 

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

113 

114 for i, issue in enumerate(wave): 

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

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

117 

118 # Truncate title if too long 

119 title = issue.title 

120 if len(title) > 45: 

121 title = title[:42] + "..." 

122 

123 lines.append(f"{prefix}{issue.issue_id}: {title} ({issue.priority})") 

124 

125 # Show blockers for this issue 

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

127 if blockers: 

128 blocker_prefix = ( 

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

130 ) 

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

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

133 

134 return "\n".join(lines) 

135 

136 

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

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

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

140 

141 

142def _render_dependency_analysis( 

143 report: Any, 

144 logger: Logger, 

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

146 *, 

147 config: DependencyMappingConfig | None = None, 

148) -> None: 

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

150 

151 Args: 

152 report: DependencyReport from analyze_dependencies() 

153 logger: Logger instance 

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

155 provided, proposals where the target already runs before the 

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

157 config: Optional dependency mapping config for custom thresholds. 

158 """ 

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

160 return 

161 

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

163 

164 if report.proposals: 

165 # Partition proposals into novel vs already-satisfied 

166 novel: list[Any] = [] 

167 satisfied_count = 0 

168 for p in report.proposals: 

169 if issue_to_wave is not None: 

170 target_wave = issue_to_wave.get(p.target_id) 

171 source_wave = issue_to_wave.get(p.source_id) 

172 if ( 

173 target_wave is not None 

174 and source_wave is not None 

175 and target_wave < source_wave 

176 ): 

177 satisfied_count += 1 

178 continue 

179 novel.append(p) 

180 

181 if novel: 

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

183 high_threshold = config.high_conflict_threshold if config else 0.7 

184 conflict_threshold = config.conflict_threshold if config else 0.4 

185 for p in novel: 

186 if p.conflict_score >= high_threshold: 

187 conflict = "HIGH" 

188 elif p.conflict_score >= conflict_threshold: 

189 conflict = "MEDIUM" 

190 else: 

191 conflict = "LOW" 

192 logger.warning( 

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

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

195 ) 

196 if p.overlapping_files: 

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

198 if len(p.overlapping_files) > 3: 

199 files += " and more" 

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

201 

202 if satisfied_count > 0: 

203 total = len(report.proposals) 

204 if not novel: 

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

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

207 else: 

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

209 

210 if report.validation.has_issues: 

211 v = report.validation 

212 if v.broken_refs: 

213 for issue_id, ref_id in v.broken_refs: 

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

215 if v.stale_completed_refs: 

216 for issue_id, ref_id in v.stale_completed_refs: 

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

218 if v.missing_backlinks: 

219 for issue_id, ref_id in v.missing_backlinks: 

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

221 

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

223 print() # blank line separator