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

275 statements  

« prev     ^ index     » next       coverage.py v7.12.0, created at 2026-05-11 00:29 -0500

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

2 

3from __future__ import annotations 

4 

5import argparse 

6import re 

7import textwrap 

8from pathlib import Path 

9from typing import TYPE_CHECKING 

10 

11from little_loops.cli.output import PRIORITY_COLOR, TYPE_COLOR, colorize, print_json, terminal_width 

12 

13if TYPE_CHECKING: 

14 from little_loops.config import BRConfig 

15 

16 

17_SHOW_CMD_ALIASES: dict[str, str] = { 

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

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

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

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

22} 

23 

24 

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

26 """Return a short display label for the discovered_by frontmatter field.""" 

27 if not discovered_by: 

28 return "\u2014" 

29 return _SHOW_CMD_ALIASES.get(discovered_by, discovered_by[:7]) 

30 

31 

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

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

34 

35 Accepts three input formats: 

36 - Numeric ID only: "518" 

37 - Type + ID: "FEAT-518" 

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

39 

40 Searches all active category directories, the completed directory, and the deferred directory. 

41 

42 Args: 

43 config: Project configuration 

44 user_input: Issue ID string in any supported format 

45 

46 Returns: 

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

48 """ 

49 user_input = user_input.strip() 

50 

51 # Parse input to extract components 

52 numeric_id: str | None = None 

53 type_prefix: str | None = None 

54 priority: str | None = None 

55 

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

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

58 if m: 

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

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

61 numeric_id = m.group(3) 

62 else: 

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

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

65 if m: 

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

67 numeric_id = m.group(2) 

68 else: 

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

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

71 if m: 

72 numeric_id = m.group(1) 

73 

74 if numeric_id is None: 

75 return None 

76 

77 # Build search directories: type-scoped dirs only 

78 search_dirs: list[Path] = [] 

79 for category in config.issue_categories: 

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

81 

82 # Search for matching files 

83 for search_dir in search_dirs: 

84 if not search_dir.is_dir(): 

85 continue 

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

87 filename = path.name 

88 # Verify type prefix if provided 

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

90 continue 

91 # Verify priority if provided 

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

93 continue 

94 return path 

95 

96 return None 

97 

98 

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

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

101 

102 Args: 

103 path: Path to the issue file 

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

105 

106 Returns: 

107 Dictionary of card fields 

108 """ 

109 from little_loops.frontmatter import parse_frontmatter 

110 

111 content = path.read_text() 

112 frontmatter = parse_frontmatter(content, coerce_types=True) 

113 filename = path.name 

114 

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

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

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

118 

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

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

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

122 

123 # Extract title from content 

124 title: str | None = None 

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

126 if title_match: 

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

128 else: 

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

130 if header_match: 

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

132 else: 

133 title = path.stem 

134 

135 # Determine status from frontmatter field 

136 raw_status = frontmatter.get("status", "open") 

137 _STATUS_DISPLAY = { 

138 "done": "Completed", 

139 "cancelled": "Cancelled", 

140 "deferred": "Deferred", 

141 "in_progress": "In Progress", 

142 "blocked": "Blocked", 

143 "open": "Open", 

144 } 

145 status = _STATUS_DISPLAY.get(str(raw_status), str(raw_status).replace("_", " ").title()) 

146 

147 # Extract optional frontmatter fields 

148 confidence = frontmatter.get("confidence_score") 

149 outcome = frontmatter.get("outcome_confidence") 

150 score_complexity = frontmatter.get("score_complexity") 

151 score_test_coverage = frontmatter.get("score_test_coverage") 

152 score_ambiguity = frontmatter.get("score_ambiguity") 

153 score_change_surface = frontmatter.get("score_change_surface") 

154 effort = frontmatter.get("effort") 

155 discovered_by = frontmatter.get("discovered_by") 

156 captured_at = frontmatter.get("captured_at") 

157 completed_at = frontmatter.get("completed_at") 

158 decision_needed_raw = frontmatter.get("decision_needed") 

159 missing_artifacts_raw = frontmatter.get("missing_artifacts") 

160 

161 # Source / norm / fmt fields 

162 from little_loops.issue_parser import is_formatted, is_normalized 

163 

164 source = _source_label(discovered_by) 

165 norm = "\u2713" if is_normalized(path.name) else "\u2717" 

166 fmt = "\u2713" if is_formatted(path) else "\u2717" 

167 

168 # --- New fields --- 

169 

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

171 summary: str | None = None 

172 summary_match = re.search( 

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

174 ) 

175 if summary_match: 

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

177 if text: 

178 summary = text 

179 

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

181 integration_files: int | None = None 

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

183 if ftm_match: 

184 start = ftm_match.end() 

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

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

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

188 if count > 0: 

189 integration_files = count 

190 

191 # Risk: extract from ## Impact section 

192 risk: str | None = None 

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

194 if risk_match: 

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

196 

197 # Labels: prefer frontmatter labels: field; fall back to ## Labels body section 

198 labels: str | None = None 

199 fm_labels_raw = frontmatter.get("labels") 

200 if fm_labels_raw: 

201 if isinstance(fm_labels_raw, list): 

202 fm_label_list = [str(lb) for lb in fm_labels_raw if lb] 

203 else: 

204 fm_label_list = [lb.strip() for lb in str(fm_labels_raw).split(",") if lb.strip()] 

205 if fm_label_list: 

206 labels = ", ".join(fm_label_list) 

207 if not labels: 

208 labels_match = re.search( 

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

210 ) 

211 if labels_match: 

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

213 if found: 

214 labels = ", ".join(found) 

215 

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

217 history: str | None = None 

218 from little_loops.session_log import count_session_commands, parse_session_log 

219 

220 distinct = parse_session_log(content) 

221 if distinct: 

222 counts = count_session_commands(content) 

223 parts = [f"{cmd} ({counts[cmd]})" if counts.get(cmd, 1) > 1 else cmd for cmd in distinct] 

224 history = ", ".join(parts) 

225 

226 # Relative path 

227 try: 

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

229 except ValueError: 

230 rel_path = str(path) 

231 

232 return { 

233 "issue_id": issue_id, 

234 "title": title, 

235 "priority": priority, 

236 "status": status, 

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

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

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

240 "score_complexity": str(score_complexity) if score_complexity is not None else None, 

241 "score_test_coverage": str(score_test_coverage) 

242 if score_test_coverage is not None 

243 else None, 

244 "score_ambiguity": str(score_ambiguity) if score_ambiguity is not None else None, 

245 "score_change_surface": str(score_change_surface) 

246 if score_change_surface is not None 

247 else None, 

248 "summary": summary, 

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

250 "risk": risk, 

251 "labels": labels, 

252 "milestone": frontmatter.get("milestone") or None, 

253 "history": history, 

254 "path": rel_path, 

255 "source": source, 

256 "norm": norm, 

257 "fmt": fmt, 

258 "captured_at": str(captured_at) if captured_at is not None else None, 

259 "completed_at": str(completed_at) if completed_at is not None else None, 

260 "decision_needed": str(decision_needed_raw).lower() 

261 if decision_needed_raw is not None 

262 else None, 

263 "missing_artifacts": str(missing_artifacts_raw).lower() 

264 if missing_artifacts_raw is not None 

265 else None, 

266 } 

267 

268 

269_ANSI_RE = re.compile(r"\033\[[0-9;]*m") 

270 

271 

272def _strip_ansi(text: str) -> str: 

273 return _ANSI_RE.sub("", text) 

274 

275 

276def _ljust(text: str, width: int) -> str: 

277 """Left-justify text accounting for invisible ANSI escape codes.""" 

278 pad = max(0, width - len(_strip_ansi(text))) 

279 return text + " " * pad 

280 

281 

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

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

284 

285 Args: 

286 fields: Dictionary of card fields from _parse_card_fields 

287 

288 Returns: 

289 Formatted card string 

290 """ 

291 # Box-drawing characters 

292 h = "\u2500" # ─ 

293 v = "\u2502" # │ 

294 tl = "\u250c" # ┌ 

295 tr = "\u2510" # ┐ 

296 bl = "\u2514" # └ 

297 br = "\u2518" # ┘ 

298 ml = "\u251c" # ├ 

299 mr = "\u2524" # ┤ 

300 

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

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

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

304 

305 # Build metadata line (plain, for width calculation) 

306 priority = fields.get("priority") 

307 status = fields.get("status") 

308 effort = fields.get("effort") 

309 risk = fields.get("risk") 

310 

311 meta_parts: list[str] = [] 

312 if priority: 

313 meta_parts.append(f"Priority: {priority}") 

314 if status: 

315 meta_parts.append(f"Status: {status}") 

316 if effort: 

317 meta_parts.append(f"Effort: {effort}") 

318 if risk: 

319 meta_parts.append(f"Risk: {risk}") 

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

321 

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

323 score_parts: list[str] = [] 

324 if fields.get("confidence"): 

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

326 if fields.get("outcome"): 

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

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

329 

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

331 dim_parts: list[str] = [] 

332 if fields.get("score_complexity"): 

333 dim_parts.append(f"Cmplx: {fields['score_complexity']}") 

334 if fields.get("score_test_coverage"): 

335 dim_parts.append(f"Tcov: {fields['score_test_coverage']}") 

336 if fields.get("score_ambiguity"): 

337 dim_parts.append(f"Ambig: {fields['score_ambiguity']}") 

338 if fields.get("score_change_surface"): 

339 dim_parts.append(f"Chsrf: {fields['score_change_surface']}") 

340 dim_scores_line = " \u2502 ".join(dim_parts) if dim_parts else None 

341 

342 # Build detail lines (source/norm/fmt, integration+labels, history) 

343 detail_lines: list[str] = [] 

344 source_parts: list[str] = [] 

345 source_val = fields.get("source") 

346 if source_val and source_val != "\u2014": 

347 source_parts.append(f"Source: {source_val}") 

348 norm_val = fields.get("norm") 

349 if norm_val: 

350 source_parts.append(f"Norm: {norm_val}") 

351 fmt_val = fields.get("fmt") 

352 if fmt_val: 

353 source_parts.append(f"Fmt: {fmt_val}") 

354 if source_parts: 

355 detail_lines.append(" \u2502 ".join(source_parts)) 

356 detail_mid_parts: list[str] = [] 

357 if fields.get("integration_files"): 

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

359 if fields.get("labels"): 

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

361 if fields.get("milestone"): 

362 detail_mid_parts.append(f"Milestone: {fields['milestone']}") 

363 if detail_mid_parts: 

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

365 if fields.get("captured_at"): 

366 detail_lines.append(f"Captured at: {fields['captured_at']}") 

367 if fields.get("completed_at"): 

368 detail_lines.append(f"Completed at: {fields['completed_at']}") 

369 if fields.get("history"): 

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

371 

372 # Build path line 

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

374 

375 # Calculate structural width from non-summary content 

376 structural_lines = [header, meta_line, path_line] 

377 if scores_line: 

378 structural_lines.append(scores_line) 

379 if dim_scores_line: 

380 structural_lines.append(dim_scores_line) 

381 structural_lines.extend(detail_lines) 

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

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

384 

385 # Build summary lines — wrap to fit structural width 

386 summary_lines: list[str] = [] 

387 summary_text = fields.get("summary") 

388 if summary_text: 

389 for line in summary_text.splitlines(): 

390 if line.strip(): 

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

392 else: 

393 summary_lines.append("") 

394 

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

396 all_lines = structural_lines + summary_lines 

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

398 

399 # Cap width to terminal to prevent overflow 

400 width = min(width, terminal_width() - 4) 

401 

402 # Build colorized header 

403 if issue_id and "-" in issue_id: 

404 itype = issue_id.split("-")[0] 

405 colored_id = colorize(issue_id, TYPE_COLOR.get(itype, "0")) 

406 else: 

407 colored_id = issue_id 

408 colored_header = f"{colored_id}: {title}" 

409 

410 # Build colorized meta line 

411 colored_meta_parts: list[str] = [] 

412 if priority: 

413 colored_meta_parts.append( 

414 f"Priority: {colorize(priority, PRIORITY_COLOR.get(priority, '0'))}" 

415 ) 

416 if status: 

417 colored_status = colorize("Completed", "32") if status == "Completed" else status 

418 colored_meta_parts.append(f"Status: {colored_status}") 

419 if effort: 

420 colored_meta_parts.append(f"Effort: {effort}") 

421 if risk: 

422 risk_code = {"High": "38;5;208", "Medium": "33", "Low": "2"}.get(risk, "0") 

423 colored_meta_parts.append(f"Risk: {colorize(risk, risk_code)}") 

424 colored_meta_line = " \u2502 ".join(colored_meta_parts) 

425 

426 # Build card 

427 lines: list[str] = [] 

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

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

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

431 

432 lines.append(top_border) 

433 lines.append(f"{v} {_ljust(colored_header, width - 1)}{v}") 

434 lines.append(mid_border) 

435 lines.append(f"{v} {_ljust(colored_meta_line, width - 1)}{v}") 

436 if scores_line: 

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

438 if dim_scores_line: 

439 lines.append(f"{v} {dim_scores_line:<{width - 1}}{v}") 

440 if summary_lines: 

441 lines.append(mid_border) 

442 for sl in summary_lines: 

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

444 if detail_lines: 

445 lines.append(mid_border) 

446 for dl in detail_lines: 

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

448 lines.append(mid_border) 

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

450 lines.append(bot_border) 

451 

452 return "\n".join(lines) 

453 

454 

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

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

457 

458 Args: 

459 config: Project configuration 

460 args: Parsed arguments with .issue_id attribute 

461 

462 Returns: 

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

464 """ 

465 issue_id = args.issue_id 

466 path = _resolve_issue_id(config, issue_id) 

467 

468 if path is None: 

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

470 return 1 

471 

472 fields = _parse_card_fields(path, config) 

473 

474 if getattr(args, "json", False): 

475 print_json(fields) 

476 return 0 

477 

478 card = _render_card(fields) 

479 print(card) 

480 return 0