Coverage for little_loops / cli / issues / refine_status.py: 97%

110 statements  

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

1"""ll-issues refine-status: Refinement depth table for active issues.""" 

2 

3from __future__ import annotations 

4 

5import argparse 

6import json 

7import shutil 

8from typing import TYPE_CHECKING 

9 

10if TYPE_CHECKING: 

11 from little_loops.config import BRConfig 

12 from little_loops.issue_parser import IssueInfo 

13 

14# Minimum width for the title column (before terminal-width trimming) 

15_MIN_TITLE_WIDTH = 20 

16# Fixed column widths for non-title columns 

17_ID_WIDTH = 8 # "BUG-525 " 

18_PRI_WIDTH = 4 # "P2 " 

19_SCORE_WIDTH = 7 # "ready" col 

20_CONF_WIDTH = 10 # "confidence" col 

21_TOTAL_WIDTH = 5 # "total" 

22# Width of each command column: longest alias is "tradeoff" = 8 chars 

23_CMD_WIDTH = 8 

24_NORM_WIDTH = 4 # "norm" / "✓" / "✗" 

25_SOURCE_WIDTH = 7 # "source" header / "capture" value max 

26 

27# Commands that are excluded from dynamic columns (shown as `source` instead) 

28_SOURCE_CMDS = {"/ll:capture-issue", "/ll:scan-codebase", "/ll:audit-architecture"} 

29 

30# Canonical workflow order for command columns 

31_CANONICAL_CMD_ORDER = [ 

32 "/ll:capture-issue", 

33 "/ll:scan-codebase", 

34 "/ll:audit-architecture", 

35 "/ll:format-issue", 

36 "/ll:verify-issues", 

37 "/ll:refine-issue", 

38 "/ll:tradeoff-review-issues", 

39 "/ll:map-dependencies", 

40] 

41 

42_CMD_ALIASES: dict[str, str] = { 

43 "/ll:capture-issue": "capture", 

44 "/ll:scan-codebase": "scan", 

45 "/ll:audit-architecture": "audit", 

46 "/ll:format-issue": "format", 

47 "/ll:verify-issues": "verify", 

48 "/ll:refine-issue": "refine", 

49 "/ll:tradeoff-review-issues": "tradeoff", 

50 "/ll:map-dependencies": "map", 

51} 

52 

53 

54def _cmd_label(cmd: str) -> str: 

55 """Return display label for a command column header.""" 

56 if cmd in _CMD_ALIASES: 

57 return _CMD_ALIASES[cmd] 

58 # Fallback: strip /ll: prefix and truncate 

59 short = cmd[4:] if cmd.startswith("/ll:") else cmd 

60 return _truncate(short, _CMD_WIDTH) 

61 

62 

63def _source_label(discovered_by: str | None) -> str: 

64 """Return short display label for an issue's origin source.""" 

65 if not discovered_by: 

66 return "\u2014" # em-dash 

67 if discovered_by in _CMD_ALIASES: 

68 return _CMD_ALIASES[discovered_by] 

69 # Non-/ll: values like "github_sync" — truncate to fit 

70 return _truncate(discovered_by, _SOURCE_WIDTH) 

71 

72 

73def _truncate(text: str, width: int) -> str: 

74 """Truncate text to width, replacing last char with ellipsis if needed.""" 

75 if len(text) <= width: 

76 return text 

77 return text[: width - 1].rstrip() + "\u2026" 

78 

79 

80def _col(text: str, width: int) -> str: 

81 """Left-justify text in a fixed-width column.""" 

82 return text.ljust(width)[:width] 

83 

84 

85def _rcol(text: str, width: int) -> str: 

86 """Right-justify text in a fixed-width column.""" 

87 return text.rjust(width)[:width] 

88 

89 

90def cmd_refine_status(config: BRConfig, args: argparse.Namespace) -> int: 

91 """Render a refinement depth table for all active issues. 

92 

93 Each column represents a distinct /ll:* command found across Session Log 

94 sections. Issues are sorted descending by refinement depth (Total), then 

95 ascending by priority as a tiebreaker. 

96 

97 Args: 

98 config: Project configuration. 

99 args: Parsed arguments with optional .type and .format attributes. 

100 

101 Returns: 

102 Exit code (0 = success). 

103 """ 

104 from little_loops.issue_parser import find_issues, is_normalized 

105 

106 type_prefixes = {args.type} if getattr(args, "type", None) else None 

107 issues = find_issues(config, type_prefixes=type_prefixes) 

108 

109 if not issues: 

110 print("No active issues found.") 

111 return 0 

112 

113 # Derive dynamic column set: all distinct commands across all issues 

114 seen: dict[str, None] = {} 

115 for issue in issues: 

116 for cmd in issue.session_commands: 

117 seen[cmd] = None 

118 

119 def _canonical_sort_key(cmd: str) -> tuple[int, str]: 

120 try: 

121 return (_CANONICAL_CMD_ORDER.index(cmd), cmd) 

122 except ValueError: 

123 return (len(_CANONICAL_CMD_ORDER), cmd) 

124 

125 all_cmds: list[str] = [ 

126 cmd for cmd in sorted(seen.keys(), key=_canonical_sort_key) 

127 if cmd not in _SOURCE_CMDS 

128 ] 

129 

130 # Sort issues: descending by total commands touched, then ascending priority 

131 def _sort_key(issue: IssueInfo) -> tuple[int, int]: 

132 return (-len(issue.session_commands), issue.priority_int) 

133 

134 sorted_issues = sorted(issues, key=_sort_key) 

135 

136 fmt = getattr(args, "format", "table") 

137 

138 if fmt == "json": 

139 for issue in sorted_issues: 

140 record = { 

141 "id": issue.issue_id, 

142 "priority": issue.priority, 

143 "title": issue.title, 

144 "source": issue.discovered_by, 

145 "commands": issue.session_commands, 

146 "confidence_score": issue.confidence_score, 

147 "outcome_confidence": issue.outcome_confidence, 

148 "total": len(issue.session_commands), 

149 "normalized": is_normalized(issue.path.name), 

150 "refine_count": issue.session_command_counts.get("/ll:refine-issue", 0), 

151 } 

152 print(json.dumps(record)) 

153 return 0 

154 

155 # --- Table rendering --- 

156 term_cols = shutil.get_terminal_size().columns 

157 

158 # Compute how much space is consumed by fixed columns + command columns. 

159 # Layout: ID | Pri | Title | source | norm | [cmd cols...] | ready | confidence | total 

160 # _row uses " ".join(parts) — 2-char separator between each part. 

161 # Each "+2" below accounts for the 2-char separator that follows that column. 

162 # The final "- 2" accounts for the separator between Title and the next column (source). 

163 fixed_width = ( 

164 _ID_WIDTH + 2 

165 + _PRI_WIDTH + 2 

166 + _SOURCE_WIDTH + 2 # source (before norm) 

167 + _NORM_WIDTH + 2 # norm 

168 + _SCORE_WIDTH + 2 # ready 

169 + _CONF_WIDTH + 2 # confidence 

170 + _TOTAL_WIDTH 

171 ) 

172 cmd_cols_width = len(all_cmds) * (_CMD_WIDTH + 2) 

173 title_width = max(_MIN_TITLE_WIDTH, term_cols - fixed_width - cmd_cols_width - 2) 

174 

175 def _row( 

176 issue_id: str, 

177 pri: str, 

178 title: str, 

179 source: str, 

180 norm: str, 

181 cmd_cells: list[str], 

182 ready: str, 

183 conf: str, 

184 total: str, 

185 ) -> str: 

186 parts = [ 

187 _col(issue_id, _ID_WIDTH), 

188 _col(pri, _PRI_WIDTH), 

189 _col(title, title_width), 

190 _col(source, _SOURCE_WIDTH), 

191 _col(norm, _NORM_WIDTH), 

192 ] 

193 for cell in cmd_cells: 

194 parts.append(_col(cell, _CMD_WIDTH)) 

195 parts.append(_rcol(ready, _SCORE_WIDTH)) 

196 parts.append(_rcol(conf, _CONF_WIDTH)) 

197 parts.append(_rcol(total, _TOTAL_WIDTH)) 

198 return " ".join(parts) 

199 

200 # Header row 

201 cmd_headers = [_col(_cmd_label(c), _CMD_WIDTH) for c in all_cmds] 

202 header = _row("ID", "Pri", "Title", "source", "norm", cmd_headers, "ready", "confidence", "total") 

203 separator = "-" * len(header) 

204 

205 rows: list[str] = [header, separator] 

206 

207 for issue in sorted_issues: 

208 cmd_set = set(issue.session_commands) 

209 cmd_cells = [] 

210 for c in all_cmds: 

211 if c == "/ll:refine-issue": 

212 cmd_cells.append(str(issue.session_command_counts.get(c, 0))) 

213 else: 

214 cmd_cells.append("\u2713" if c in cmd_set else "\u2014") 

215 source_cell = _source_label(issue.discovered_by) 

216 norm_cell = "\u2713" if is_normalized(issue.path.name) else "\u2717" 

217 ready = str(issue.confidence_score) if issue.confidence_score is not None else "\u2014" 

218 out_conf = ( 

219 str(issue.outcome_confidence) if issue.outcome_confidence is not None else "\u2014" 

220 ) 

221 total = str(len(issue.session_commands)) 

222 rows.append( 

223 _row( 

224 issue.issue_id, 

225 issue.priority, 

226 _truncate(issue.title, title_width), 

227 source_cell, 

228 norm_cell, 

229 cmd_cells, 

230 ready, 

231 out_conf, 

232 total, 

233 ) 

234 ) 

235 

236 print("\n".join(rows)) 

237 

238 issue_word = "issue" if len(sorted_issues) == 1 else "issues" 

239 scored = sum(1 for i in sorted_issues if i.confidence_score is not None) 

240 print(f"\n{len(sorted_issues)} {issue_word} ({scored} scored)") 

241 

242 if not getattr(args, "no_key", False): 

243 _print_key(all_cmds) 

244 

245 return 0 

246 

247 

248def _print_key(all_cmds: list[str]) -> None: 

249 """Print a legend mapping column headers to their full command names.""" 

250 print("\nKey:") 

251 print(f" {'source':<12} Origin command/workflow that created the issue") 

252 print(f" {'norm':<12} Filename follows naming convention (P[0-5]-TYPE-NNN-desc.md)") 

253 for cmd in all_cmds: 

254 label = _cmd_label(cmd) 

255 if cmd == "/ll:refine-issue": 

256 print(f" {label:<12} Times /ll:refine-issue was run") 

257 else: 

258 print(f" {label:<12} {cmd}") 

259 print(f" {'ready':<12} Readiness score (0\u2013100)") 

260 print(f" {'confidence':<12} Outcome confidence score (0\u2013100)") 

261 print(f" {'total':<12} Number of /ll:* skills applied") 

262 

263