Coverage for little_loops / cli / issues / show.py: 95%

189 statements  

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

1"""ll-issues show: Display summary card for a single issue.""" 

2 

3from __future__ import annotations 

4 

5import argparse 

6import re 

7import textwrap 

8from collections import Counter 

9from pathlib import Path 

10from typing import TYPE_CHECKING 

11 

12if TYPE_CHECKING: 

13 from little_loops.config import BRConfig 

14 

15 

16def _resolve_issue_id(config: BRConfig, user_input: str) -> Path | None: 

17 """Resolve user input to an issue file path. 

18 

19 Accepts three input formats: 

20 - Numeric ID only: "518" 

21 - Type + ID: "FEAT-518" 

22 - Priority + Type + ID: "P3-FEAT-518" 

23 

24 Searches all active category directories and the completed directory. 

25 

26 Args: 

27 config: Project configuration 

28 user_input: Issue ID string in any supported format 

29 

30 Returns: 

31 Path to the matched issue file, or None if not found 

32 """ 

33 user_input = user_input.strip() 

34 

35 # Parse input to extract components 

36 numeric_id: str | None = None 

37 type_prefix: str | None = None 

38 priority: str | None = None 

39 

40 # Try P-TYPE-NNN format (e.g., P3-FEAT-518) 

41 m = re.match(r"^(P\d)-(BUG|FEAT|ENH)-(\d+)$", user_input, re.IGNORECASE) 

42 if m: 

43 priority = m.group(1).upper() 

44 type_prefix = m.group(2).upper() 

45 numeric_id = m.group(3) 

46 else: 

47 # Try TYPE-NNN format (e.g., FEAT-518) 

48 m = re.match(r"^(BUG|FEAT|ENH)-(\d+)$", user_input, re.IGNORECASE) 

49 if m: 

50 type_prefix = m.group(1).upper() 

51 numeric_id = m.group(2) 

52 else: 

53 # Try numeric only (e.g., 518) 

54 m = re.match(r"^(\d+)$", user_input) 

55 if m: 

56 numeric_id = m.group(1) 

57 

58 if numeric_id is None: 

59 return None 

60 

61 # Build search directories: all active categories + completed 

62 search_dirs: list[Path] = [] 

63 for category in config.issue_categories: 

64 search_dirs.append(config.get_issue_dir(category)) 

65 search_dirs.append(config.get_completed_dir()) 

66 

67 # Search for matching files 

68 for search_dir in search_dirs: 

69 if not search_dir.is_dir(): 

70 continue 

71 for path in search_dir.glob(f"*-{numeric_id}-*.md"): 

72 filename = path.name 

73 # Verify type prefix if provided 

74 if type_prefix and f"-{type_prefix}-" not in filename.upper(): 

75 continue 

76 # Verify priority if provided 

77 if priority and not filename.upper().startswith(f"{priority}-"): 

78 continue 

79 return path 

80 

81 return None 

82 

83 

84def _parse_card_fields(path: Path, config: BRConfig) -> dict[str, str | None]: 

85 """Parse issue file to extract summary card fields. 

86 

87 Args: 

88 path: Path to the issue file 

89 config: Project configuration (used for relative path computation) 

90 

91 Returns: 

92 Dictionary of card fields 

93 """ 

94 from little_loops.frontmatter import parse_frontmatter 

95 

96 content = path.read_text() 

97 frontmatter = parse_frontmatter(content, coerce_types=True) 

98 filename = path.name 

99 

100 # Extract priority from filename (e.g., P3-FEAT-518-...) 

101 priority_match = re.match(r"^(P\d)-", filename) 

102 priority = priority_match.group(1) if priority_match else None 

103 

104 # Extract type and ID from filename (e.g., FEAT-518) 

105 type_id_match = re.search(r"(BUG|FEAT|ENH)-(\d+)", filename) 

106 issue_id = f"{type_id_match.group(1)}-{type_id_match.group(2)}" if type_id_match else None 

107 

108 # Extract title from content 

109 title: str | None = None 

110 title_match = re.search(r"^#\s+[\w-]+:\s*(.+)$", content, re.MULTILINE) 

111 if title_match: 

112 title = title_match.group(1).strip() 

113 else: 

114 header_match = re.search(r"^#\s+(.+)$", content, re.MULTILINE) 

115 if header_match: 

116 title = header_match.group(1).strip() 

117 else: 

118 title = path.stem 

119 

120 # Determine status 

121 is_completed = path.parent.name == "completed" 

122 status = "Completed" if is_completed else "Open" 

123 

124 # Extract optional frontmatter fields 

125 confidence = frontmatter.get("confidence_score") 

126 outcome = frontmatter.get("outcome_confidence") 

127 effort = frontmatter.get("effort") 

128 

129 # --- New fields --- 

130 

131 # Summary: full first paragraph from ## Summary section 

132 summary: str | None = None 

133 summary_match = re.search( 

134 r"^## Summary\s*\n+(.*?)(?:\n\n|\n##|\Z)", content, re.MULTILINE | re.DOTALL 

135 ) 

136 if summary_match: 

137 text = summary_match.group(1).strip() 

138 if text: 

139 summary = text 

140 

141 # Integration file count: count items under ### Files to Modify 

142 integration_files: int | None = None 

143 ftm_match = re.search(r"^### Files to Modify\s*$", content, re.MULTILINE) 

144 if ftm_match: 

145 start = ftm_match.end() 

146 next_header = re.search(r"^#{2,3}\s+", content[start:], re.MULTILINE) 

147 section = content[start : start + next_header.start()] if next_header else content[start:] 

148 count = len(re.findall(r"^- .+", section, re.MULTILINE)) 

149 if count > 0: 

150 integration_files = count 

151 

152 # Risk: extract from ## Impact section 

153 risk: str | None = None 

154 risk_match = re.search(r"\*\*Risk\*\*:\s*(Low|Medium|High)", content, re.IGNORECASE) 

155 if risk_match: 

156 risk = risk_match.group(1).capitalize() 

157 

158 # Labels: extract backtick-delimited labels from ## Labels section 

159 labels: str | None = None 

160 labels_match = re.search( 

161 r"^## Labels\s*\n+(.*?)(?:\n\n|\n##|\Z)", content, re.MULTILINE | re.DOTALL 

162 ) 

163 if labels_match: 

164 found = re.findall(r"`([^`]+)`", labels_match.group(1)) 

165 if found: 

166 labels = ", ".join(found) 

167 

168 # Session log: parse ## Session Log for unique /ll:* commands with counts 

169 history: str | None = None 

170 from little_loops.session_log import parse_session_log 

171 

172 log_match = re.search( 

173 r"^## Session Log\s*\n+(.*?)(?:\n##|\n---|\Z)", content, re.MULTILINE | re.DOTALL 

174 ) 

175 if log_match: 

176 raw_cmds = re.findall(r"`(/[\w:-]+)`", log_match.group(1)) 

177 if raw_cmds: 

178 counts = Counter(raw_cmds) 

179 distinct = parse_session_log(content) 

180 parts = [f"{cmd} ({counts[cmd]})" if counts[cmd] > 1 else cmd for cmd in distinct] 

181 history = ", ".join(parts) 

182 

183 # Relative path 

184 try: 

185 rel_path = str(path.relative_to(config.project_root)) 

186 except ValueError: 

187 rel_path = str(path) 

188 

189 return { 

190 "issue_id": issue_id, 

191 "title": title, 

192 "priority": priority, 

193 "status": status, 

194 "effort": str(effort) if effort is not None else None, 

195 "confidence": str(confidence) if confidence is not None else None, 

196 "outcome": str(outcome) if outcome is not None else None, 

197 "summary": summary, 

198 "integration_files": str(integration_files) if integration_files is not None else None, 

199 "risk": risk, 

200 "labels": labels, 

201 "history": history, 

202 "path": rel_path, 

203 } 

204 

205 

206def _render_card(fields: dict[str, str | None]) -> str: 

207 """Render a summary card using box-drawing characters. 

208 

209 Args: 

210 fields: Dictionary of card fields from _parse_card_fields 

211 

212 Returns: 

213 Formatted card string 

214 """ 

215 # Box-drawing characters 

216 h = "\u2500" # ─ 

217 v = "\u2502" # │ 

218 tl = "\u250c" # ┌ 

219 tr = "\u2510" # ┐ 

220 bl = "\u2514" # └ 

221 br = "\u2518" # ┘ 

222 ml = "\u251c" # ├ 

223 mr = "\u2524" # ┤ 

224 

225 issue_id = fields.get("issue_id") or "???" 

226 title = fields.get("title") or "Untitled" 

227 header = f"{issue_id}: {title}" 

228 

229 # Build metadata line 

230 meta_parts: list[str] = [] 

231 if fields.get("priority"): 

232 meta_parts.append(f"Priority: {fields['priority']}") 

233 if fields.get("status"): 

234 meta_parts.append(f"Status: {fields['status']}") 

235 if fields.get("effort"): 

236 meta_parts.append(f"Effort: {fields['effort']}") 

237 if fields.get("risk"): 

238 meta_parts.append(f"Risk: {fields['risk']}") 

239 meta_line = " \u2502 ".join(meta_parts) 

240 

241 # Build scores line (only if at least one score present) 

242 score_parts: list[str] = [] 

243 if fields.get("confidence"): 

244 score_parts.append(f"Confidence: {fields['confidence']}") 

245 if fields.get("outcome"): 

246 score_parts.append(f"Outcome: {fields['outcome']}") 

247 scores_line = " \u2502 ".join(score_parts) if score_parts else None 

248 

249 # Build detail lines (integration+labels, history) 

250 detail_lines: list[str] = [] 

251 detail_mid_parts: list[str] = [] 

252 if fields.get("integration_files"): 

253 detail_mid_parts.append(f"Integration: {fields['integration_files']} files") 

254 if fields.get("labels"): 

255 detail_mid_parts.append(f"Labels: {fields['labels']}") 

256 if detail_mid_parts: 

257 detail_lines.append(" \u2502 ".join(detail_mid_parts)) 

258 if fields.get("history"): 

259 detail_lines.append(f"History: {fields['history']}") 

260 

261 # Build path line 

262 path_line = f"Path: {fields.get('path', '???')}" 

263 

264 # Calculate structural width from non-summary content 

265 structural_lines = [header, meta_line, path_line] 

266 if scores_line: 

267 structural_lines.append(scores_line) 

268 structural_lines.extend(detail_lines) 

269 wrap_width = max((len(line) for line in structural_lines), default=60) 

270 wrap_width = max(wrap_width, 60) # minimum content width 

271 

272 # Build summary lines — wrap to fit structural width 

273 summary_lines: list[str] = [] 

274 summary_text = fields.get("summary") 

275 if summary_text: 

276 for line in summary_text.splitlines(): 

277 if line.strip(): 

278 summary_lines.extend(textwrap.wrap(line, width=wrap_width, break_long_words=False)) 

279 else: 

280 summary_lines.append("") 

281 

282 # Final width includes wrapped summary (may exceed wrap_width for unbreakable tokens) 

283 all_lines = structural_lines + summary_lines 

284 width = max(len(line) for line in all_lines) + 2 # +2 for padding 

285 

286 # Build card 

287 lines: list[str] = [] 

288 top_border = f"{tl}{h * width}{tr}" 

289 mid_border = f"{ml}{h * width}{mr}" 

290 bot_border = f"{bl}{h * width}{br}" 

291 

292 lines.append(top_border) 

293 lines.append(f"{v} {header:<{width - 1}}{v}") 

294 lines.append(mid_border) 

295 lines.append(f"{v} {meta_line:<{width - 1}}{v}") 

296 if scores_line: 

297 lines.append(f"{v} {scores_line:<{width - 1}}{v}") 

298 if summary_lines: 

299 lines.append(mid_border) 

300 for sl in summary_lines: 

301 lines.append(f"{v} {sl:<{width - 1}}{v}") 

302 if detail_lines: 

303 lines.append(mid_border) 

304 for dl in detail_lines: 

305 lines.append(f"{v} {dl:<{width - 1}}{v}") 

306 lines.append(mid_border) 

307 lines.append(f"{v} {path_line:<{width - 1}}{v}") 

308 lines.append(bot_border) 

309 

310 return "\n".join(lines) 

311 

312 

313def cmd_show(config: BRConfig, args: argparse.Namespace) -> int: 

314 """Display summary card for a single issue. 

315 

316 Args: 

317 config: Project configuration 

318 args: Parsed arguments with .issue_id attribute 

319 

320 Returns: 

321 Exit code (0 = success, 1 = not found) 

322 """ 

323 issue_id = args.issue_id 

324 path = _resolve_issue_id(config, issue_id) 

325 

326 if path is None: 

327 print(f"Error: Issue '{issue_id}' not found.") 

328 return 1 

329 

330 fields = _parse_card_fields(path, config) 

331 card = _render_card(fields) 

332 print(card) 

333 return 0