Coverage for little_loops / cli / issues / show.py: 0%
275 statements
« prev ^ index » next coverage.py v7.12.0, created at 2026-06-04 12:21 -0500
« prev ^ index » next coverage.py v7.12.0, created at 2026-06-04 12:21 -0500
1"""ll-issues show: Display summary card for a single issue."""
3from __future__ import annotations
5import argparse
6import re
7import textwrap
8from pathlib import Path
9from typing import TYPE_CHECKING
11from little_loops.cli.output import (
12 PRIORITY_COLOR,
13 TYPE_COLOR,
14 colorize,
15 print_json,
16 strip_ansi,
17 terminal_width,
18)
20if TYPE_CHECKING:
21 from little_loops.config import BRConfig
24_SHOW_CMD_ALIASES: dict[str, str] = {
25 "/ll:capture-issue": "capture",
26 "/ll:scan-codebase": "scan",
27 "/ll:audit-architecture": "audit",
28 "/ll:format-issue": "format",
29}
32def _source_label(discovered_by: str | None) -> str:
33 """Return a short display label for the discovered_by frontmatter field."""
34 if not discovered_by:
35 return "\u2014"
36 return _SHOW_CMD_ALIASES.get(discovered_by, discovered_by[:7])
39def _resolve_issue_id(config: BRConfig, user_input: str) -> Path | None:
40 """Resolve user input to an issue file path.
42 Accepts three input formats:
43 - Numeric ID only: "518"
44 - Type + ID: "FEAT-518"
45 - Priority + Type + ID: "P3-FEAT-518"
47 Searches all active category directories, the completed directory, and the deferred directory.
49 Args:
50 config: Project configuration
51 user_input: Issue ID string in any supported format
53 Returns:
54 Path to the matched issue file, or None if not found
55 """
56 user_input = user_input.strip()
58 # Parse input to extract components
59 numeric_id: str | None = None
60 type_prefix: str | None = None
61 priority: str | None = None
63 # Try P-TYPE-NNN format (e.g., P3-FEAT-518)
64 m = re.match(r"^(P\d)-(BUG|FEAT|ENH|EPIC)-(\d+)$", user_input, re.IGNORECASE)
65 if m:
66 priority = m.group(1).upper()
67 type_prefix = m.group(2).upper()
68 numeric_id = m.group(3)
69 else:
70 # Try TYPE-NNN format (e.g., FEAT-518)
71 m = re.match(r"^(BUG|FEAT|ENH|EPIC)-(\d+)$", user_input, re.IGNORECASE)
72 if m:
73 type_prefix = m.group(1).upper()
74 numeric_id = m.group(2)
75 else:
76 # Try numeric only (e.g., 518)
77 m = re.match(r"^(\d+)$", user_input)
78 if m:
79 numeric_id = m.group(1)
81 if numeric_id is None:
82 return None
84 # Build search directories: type-scoped dirs only
85 search_dirs: list[Path] = []
86 for category in config.issue_categories:
87 search_dirs.append(config.get_issue_dir(category))
89 # Search for matching files
90 for search_dir in search_dirs:
91 if not search_dir.is_dir():
92 continue
93 for path in search_dir.glob(f"*-{numeric_id}-*.md"):
94 filename = path.name
95 # Verify type prefix if provided
96 upper = filename.upper()
97 if (
98 type_prefix
99 and f"-{type_prefix}-" not in upper
100 and not upper.startswith(f"{type_prefix}-")
101 ):
102 continue
103 # Verify priority if provided
104 if priority and not filename.upper().startswith(f"{priority}-"):
105 continue
106 return path
108 return None
111def _parse_card_fields(path: Path, config: BRConfig) -> dict[str, str | None]:
112 """Parse issue file to extract summary card fields.
114 Args:
115 path: Path to the issue file
116 config: Project configuration (used for relative path computation)
118 Returns:
119 Dictionary of card fields
120 """
121 from little_loops.frontmatter import parse_frontmatter
123 content = path.read_text()
124 frontmatter = parse_frontmatter(content, coerce_types=True)
125 filename = path.name
127 # Extract priority from filename (e.g., P3-FEAT-518-...)
128 priority_match = re.match(r"^(P\d)-", filename)
129 priority = priority_match.group(1) if priority_match else None
131 # Extract type and ID from filename (e.g., FEAT-518)
132 type_id_match = re.search(r"(BUG|FEAT|ENH|EPIC)-(\d+)", filename)
133 issue_id = f"{type_id_match.group(1)}-{type_id_match.group(2)}" if type_id_match else None
135 # Extract title from content
136 title: str | None = None
137 title_match = re.search(r"^#\s+[\w-]+:\s*(.+)$", content, re.MULTILINE)
138 if title_match:
139 title = title_match.group(1).strip()
140 else:
141 header_match = re.search(r"^#\s+(.+)$", content, re.MULTILINE)
142 if header_match:
143 title = header_match.group(1).strip()
144 else:
145 title = path.stem
147 # Determine status from frontmatter field
148 raw_status = frontmatter.get("status", "open")
149 _STATUS_DISPLAY = {
150 "done": "Completed",
151 "cancelled": "Cancelled",
152 "deferred": "Deferred",
153 "in_progress": "In Progress",
154 "blocked": "Blocked",
155 "open": "Open",
156 }
157 status = _STATUS_DISPLAY.get(str(raw_status), str(raw_status).replace("_", " ").title())
159 # Extract optional frontmatter fields
160 confidence = frontmatter.get("confidence_score")
161 outcome = frontmatter.get("outcome_confidence")
162 score_complexity = frontmatter.get("score_complexity")
163 score_test_coverage = frontmatter.get("score_test_coverage")
164 score_ambiguity = frontmatter.get("score_ambiguity")
165 score_change_surface = frontmatter.get("score_change_surface")
166 effort = frontmatter.get("effort")
167 discovered_by = frontmatter.get("discovered_by")
168 captured_at = frontmatter.get("captured_at")
169 completed_at = frontmatter.get("completed_at")
170 decision_needed_raw = frontmatter.get("decision_needed")
171 missing_artifacts_raw = frontmatter.get("missing_artifacts")
172 implementation_order_risk_raw = frontmatter.get("implementation_order_risk")
173 learning_tests_raw = frontmatter.get("learning_tests_required")
175 # Source / norm / fmt fields
176 from little_loops.issue_parser import is_formatted, is_normalized
178 source = _source_label(discovered_by)
179 norm = "\u2713" if is_normalized(path.name) else "\u2717"
180 fmt = "\u2713" if is_formatted(path) else "\u2717"
182 # --- New fields ---
184 # Summary: full first paragraph from ## Summary section
185 summary: str | None = None
186 summary_match = re.search(
187 r"^## Summary\s*\n+(.*?)(?:\n\n|\n##|\Z)", content, re.MULTILINE | re.DOTALL
188 )
189 if summary_match:
190 text = summary_match.group(1).strip()
191 if text:
192 summary = text
194 # Integration file count: count items under ### Files to Modify
195 integration_files: int | None = None
196 ftm_match = re.search(r"^### Files to Modify\s*$", content, re.MULTILINE)
197 if ftm_match:
198 start = ftm_match.end()
199 next_header = re.search(r"^#{2,3}\s+", content[start:], re.MULTILINE)
200 section = content[start : start + next_header.start()] if next_header else content[start:]
201 count = len(re.findall(r"^- .+", section, re.MULTILINE))
202 if count > 0:
203 integration_files = count
205 # Risk: extract from ## Impact section
206 risk: str | None = None
207 risk_match = re.search(r"\*\*Risk\*\*:\s*(Low|Medium|High)", content, re.IGNORECASE)
208 if risk_match:
209 risk = risk_match.group(1).capitalize()
211 # Labels: prefer frontmatter labels: field; fall back to ## Labels body section
212 labels: str | None = None
213 fm_labels_raw = frontmatter.get("labels")
214 if fm_labels_raw:
215 if isinstance(fm_labels_raw, list):
216 fm_label_list = [str(lb) for lb in fm_labels_raw if lb]
217 else:
218 fm_label_list = [lb.strip() for lb in str(fm_labels_raw).split(",") if lb.strip()]
219 if fm_label_list:
220 labels = ", ".join(fm_label_list)
221 if not labels:
222 labels_match = re.search(
223 r"^## Labels\s*\n+(.*?)(?:\n\n|\n##|\Z)", content, re.MULTILINE | re.DOTALL
224 )
225 if labels_match:
226 found = re.findall(r"`([^`]+)`", labels_match.group(1))
227 if found:
228 labels = ", ".join(found)
230 # Session log: parse ## Session Log for unique /ll:* commands with counts
231 history: str | None = None
232 from little_loops.session_log import count_session_commands, parse_session_log
234 distinct = parse_session_log(content)
235 if distinct:
236 counts = count_session_commands(content)
237 parts = [f"{cmd} ({counts[cmd]})" if counts.get(cmd, 1) > 1 else cmd for cmd in distinct]
238 history = ", ".join(parts)
240 # Relative path
241 try:
242 rel_path = str(path.relative_to(config.project_root))
243 except ValueError:
244 rel_path = str(path)
246 return {
247 "issue_id": issue_id,
248 "title": title,
249 "priority": priority,
250 "status": status,
251 "effort": str(effort) if effort is not None else None,
252 "confidence": str(confidence) if confidence is not None else None,
253 "outcome": str(outcome) if outcome is not None else None,
254 "score_complexity": str(score_complexity) if score_complexity is not None else None,
255 "score_test_coverage": str(score_test_coverage)
256 if score_test_coverage is not None
257 else None,
258 "score_ambiguity": str(score_ambiguity) if score_ambiguity is not None else None,
259 "score_change_surface": str(score_change_surface)
260 if score_change_surface is not None
261 else None,
262 "summary": summary,
263 "integration_files": str(integration_files) if integration_files is not None else None,
264 "risk": risk,
265 "labels": labels,
266 "milestone": frontmatter.get("milestone") or None,
267 "history": history,
268 "path": rel_path,
269 "source": source,
270 "norm": norm,
271 "fmt": fmt,
272 "captured_at": str(captured_at) if captured_at is not None else None,
273 "completed_at": str(completed_at) if completed_at is not None else None,
274 "decision_needed": str(decision_needed_raw).lower()
275 if decision_needed_raw is not None
276 else None,
277 "missing_artifacts": str(missing_artifacts_raw).lower()
278 if missing_artifacts_raw is not None
279 else None,
280 "implementation_order_risk": str(implementation_order_risk_raw).lower()
281 if implementation_order_risk_raw is not None
282 else None,
283 "learning_tests_required": ", ".join(str(t) for t in learning_tests_raw)
284 if learning_tests_raw
285 else None,
286 }
289def _ljust(text: str, width: int) -> str:
290 """Left-justify text accounting for invisible ANSI escape codes."""
291 pad = max(0, width - len(strip_ansi(text)))
292 return text + " " * pad
295def _render_card(fields: dict[str, str | None]) -> str:
296 """Render a summary card using box-drawing characters.
298 Args:
299 fields: Dictionary of card fields from _parse_card_fields
301 Returns:
302 Formatted card string
303 """
304 # Box-drawing characters
305 h = "\u2500" # ─
306 v = "\u2502" # │
307 tl = "\u250c" # ┌
308 tr = "\u2510" # ┐
309 bl = "\u2514" # └
310 br = "\u2518" # ┘
311 ml = "\u251c" # ├
312 mr = "\u2524" # ┤
314 issue_id = fields.get("issue_id") or "???"
315 title = fields.get("title") or "Untitled"
316 header = f"{issue_id}: {title}"
318 # Build metadata line (plain, for width calculation)
319 priority = fields.get("priority")
320 status = fields.get("status")
321 effort = fields.get("effort")
322 risk = fields.get("risk")
324 meta_parts: list[str] = []
325 if priority:
326 meta_parts.append(f"Priority: {priority}")
327 if status:
328 meta_parts.append(f"Status: {status}")
329 if effort:
330 meta_parts.append(f"Effort: {effort}")
331 if risk:
332 meta_parts.append(f"Risk: {risk}")
333 meta_line = " \u2502 ".join(meta_parts)
335 # Build scores line (only if at least one score present)
336 score_parts: list[str] = []
337 if fields.get("confidence"):
338 score_parts.append(f"Confidence: {fields['confidence']}")
339 if fields.get("outcome"):
340 score_parts.append(f"Outcome: {fields['outcome']}")
341 scores_line = " \u2502 ".join(score_parts) if score_parts else None
343 # Build dimension scores line (only if at least one dimension score present)
344 dim_parts: list[str] = []
345 if fields.get("score_complexity"):
346 dim_parts.append(f"Cmplx: {fields['score_complexity']}")
347 if fields.get("score_test_coverage"):
348 dim_parts.append(f"Tcov: {fields['score_test_coverage']}")
349 if fields.get("score_ambiguity"):
350 dim_parts.append(f"Ambig: {fields['score_ambiguity']}")
351 if fields.get("score_change_surface"):
352 dim_parts.append(f"Chsrf: {fields['score_change_surface']}")
353 dim_scores_line = " \u2502 ".join(dim_parts) if dim_parts else None
355 # Build detail lines (source/norm/fmt, integration+labels, history)
356 detail_lines: list[str] = []
357 source_parts: list[str] = []
358 source_val = fields.get("source")
359 if source_val and source_val != "\u2014":
360 source_parts.append(f"Source: {source_val}")
361 norm_val = fields.get("norm")
362 if norm_val:
363 source_parts.append(f"Norm: {norm_val}")
364 fmt_val = fields.get("fmt")
365 if fmt_val:
366 source_parts.append(f"Fmt: {fmt_val}")
367 if source_parts:
368 detail_lines.append(" \u2502 ".join(source_parts))
369 detail_mid_parts: list[str] = []
370 if fields.get("integration_files"):
371 detail_mid_parts.append(f"Integration: {fields['integration_files']} files")
372 if fields.get("labels"):
373 detail_mid_parts.append(f"Labels: {fields['labels']}")
374 if fields.get("milestone"):
375 detail_mid_parts.append(f"Milestone: {fields['milestone']}")
376 if detail_mid_parts:
377 detail_lines.append(" \u2502 ".join(detail_mid_parts))
378 if fields.get("captured_at"):
379 detail_lines.append(f"Captured at: {fields['captured_at']}")
380 if fields.get("completed_at"):
381 detail_lines.append(f"Completed at: {fields['completed_at']}")
382 if fields.get("history"):
383 detail_lines.append(f"History: {fields['history']}")
385 # Build path line
386 path_line = f"Path: {fields.get('path', '???')}"
388 # Calculate structural width from non-summary content
389 structural_lines = [header, meta_line, path_line]
390 if scores_line:
391 structural_lines.append(scores_line)
392 if dim_scores_line:
393 structural_lines.append(dim_scores_line)
394 structural_lines.extend(detail_lines)
395 wrap_width = max((len(line) for line in structural_lines), default=60)
396 wrap_width = max(wrap_width, 60) # minimum content width
398 # Build summary lines — wrap to fit structural width
399 summary_lines: list[str] = []
400 summary_text = fields.get("summary")
401 if summary_text:
402 for line in summary_text.splitlines():
403 if line.strip():
404 summary_lines.extend(textwrap.wrap(line, width=wrap_width, break_long_words=False))
405 else:
406 summary_lines.append("")
408 # Final width includes wrapped summary (may exceed wrap_width for unbreakable tokens)
409 all_lines = structural_lines + summary_lines
410 width = max(len(line) for line in all_lines) + 2 # +2 for padding
412 # Cap width to terminal to prevent overflow
413 width = min(width, terminal_width() - 4)
415 # Build colorized header
416 if issue_id and "-" in issue_id:
417 itype = issue_id.split("-")[0]
418 colored_id = colorize(issue_id, TYPE_COLOR.get(itype, "0"))
419 else:
420 colored_id = issue_id
421 colored_header = f"{colored_id}: {title}"
423 # Build colorized meta line
424 colored_meta_parts: list[str] = []
425 if priority:
426 colored_meta_parts.append(
427 f"Priority: {colorize(priority, PRIORITY_COLOR.get(priority, '0'))}"
428 )
429 if status:
430 colored_status = colorize("Completed", "32") if status == "Completed" else status
431 colored_meta_parts.append(f"Status: {colored_status}")
432 if effort:
433 colored_meta_parts.append(f"Effort: {effort}")
434 if risk:
435 risk_code = {"High": "38;5;208", "Medium": "33", "Low": "2"}.get(risk, "0")
436 colored_meta_parts.append(f"Risk: {colorize(risk, risk_code)}")
437 colored_meta_line = " \u2502 ".join(colored_meta_parts)
439 # Build card
440 lines: list[str] = []
441 top_border = f"{tl}{h * width}{tr}"
442 mid_border = f"{ml}{h * width}{mr}"
443 bot_border = f"{bl}{h * width}{br}"
445 lines.append(top_border)
446 lines.append(f"{v} {_ljust(colored_header, width - 1)}{v}")
447 lines.append(mid_border)
448 lines.append(f"{v} {_ljust(colored_meta_line, width - 1)}{v}")
449 if scores_line:
450 lines.append(f"{v} {scores_line:<{width - 1}}{v}")
451 if dim_scores_line:
452 lines.append(f"{v} {dim_scores_line:<{width - 1}}{v}")
453 if summary_lines:
454 lines.append(mid_border)
455 for sl in summary_lines:
456 lines.append(f"{v} {sl:<{width - 1}}{v}")
457 if detail_lines:
458 lines.append(mid_border)
459 for dl in detail_lines:
460 lines.append(f"{v} {dl:<{width - 1}}{v}")
461 lines.append(mid_border)
462 lines.append(f"{v} {path_line:<{width - 1}}{v}")
463 lines.append(bot_border)
465 return "\n".join(lines)
468def cmd_show(config: BRConfig, args: argparse.Namespace) -> int:
469 """Display summary card for a single issue.
471 Args:
472 config: Project configuration
473 args: Parsed arguments with .issue_id attribute
475 Returns:
476 Exit code (0 = success, 1 = not found)
477 """
478 issue_id = args.issue_id
479 path = _resolve_issue_id(config, issue_id)
481 if path is None:
482 print(f"Error: Issue '{issue_id}' not found.")
483 return 1
485 fields = _parse_card_fields(path, config)
487 if getattr(args, "json", False):
488 print_json(fields)
489 return 0
491 card = _render_card(fields)
492 print(card)
493 return 0