Coverage for little_loops / cli / issues / refine_status.py: 0%
190 statements
« prev ^ index » next coverage.py v7.12.0, created at 2026-03-14 23:20 -0500
« prev ^ index » next coverage.py v7.12.0, created at 2026-03-14 23:20 -0500
1"""ll-issues refine-status: Refinement depth table for active issues."""
3from __future__ import annotations
5import argparse
6import json
7from typing import TYPE_CHECKING
9from little_loops.cli.output import PRIORITY_COLOR, TYPE_COLOR, colorize, print_json, terminal_width
11if TYPE_CHECKING:
12 from little_loops.config import BRConfig
13 from little_loops.issue_parser import IssueInfo
15# Minimum width for the title column (before terminal-width trimming)
16_MIN_TITLE_WIDTH = 20
17# Fixed column widths for non-title columns
18_ID_WIDTH = 8 # "BUG-525 "
19_PRI_WIDTH = 4 # "P2 "
20_SCORE_WIDTH = 5 # "ready" col
21_CONF_WIDTH = 5 # "conf" col
22_TOTAL_WIDTH = 5 # "total"
23# Width of each command column
24_CMD_WIDTH = 6
25_NORM_WIDTH = 4 # "norm" / "✓" / "✗"
26_FMT_WIDTH = 4 # "fmt" / "✓" / "✗"
27_SOURCE_WIDTH = 7 # "source" header / "capture" value max
29# Commands that are excluded from dynamic columns (shown as static columns instead)
30_SOURCE_CMDS = {
31 "/ll:capture-issue",
32 "/ll:scan-codebase",
33 "/ll:audit-architecture",
34 "/ll:format-issue",
35}
37# Canonical workflow order for command columns
38_CANONICAL_CMD_ORDER = [
39 "/ll:capture-issue",
40 "/ll:scan-codebase",
41 "/ll:audit-architecture",
42 "/ll:format-issue",
43 "/ll:verify-issues",
44 "/ll:refine-issue",
45 "/ll:tradeoff-review-issues",
46 "/ll:map-dependencies",
47]
49_CMD_ALIASES: dict[str, str] = {
50 "/ll:capture-issue": "capture",
51 "/ll:scan-codebase": "scan",
52 "/ll:audit-architecture": "audit",
53 "/ll:format-issue": "format",
54 "/ll:verify-issues": "verify",
55 "/ll:refine-issue": "refine",
56 "/ll:tradeoff-review-issues": "tradeoff",
57 "/ll:map-dependencies": "map",
58}
60# Static column metadata: name -> (fixed_width, header_text, right_justify)
61# width=0 is a sentinel meaning the column width is computed dynamically (title only)
62_STATIC_COLUMN_SPECS: dict[str, tuple[int, str, bool]] = {
63 "id": (_ID_WIDTH, "ID", False),
64 "priority": (_PRI_WIDTH, "Pri", False),
65 "title": (0, "Title", False),
66 "source": (_SOURCE_WIDTH, "source", False),
67 "norm": (_NORM_WIDTH, "norm", False),
68 "fmt": (_FMT_WIDTH, "fmt", False),
69 "ready": (_SCORE_WIDTH, "ready", True),
70 "confidence": (_CONF_WIDTH, "conf", True),
71 "total": (_TOTAL_WIDTH, "total", True),
72}
74# Default column order when no config is provided
75_DEFAULT_STATIC_COLUMNS: list[str] = [
76 "id",
77 "priority",
78 "title",
79 "source",
80 "norm",
81 "fmt",
82 "ready",
83 "confidence",
84 "total",
85]
87# Columns that belong after the dynamic command block (all others go before)
88_POST_CMD_STATIC: frozenset[str] = frozenset(["ready", "confidence", "total"])
91def _cmd_label(cmd: str) -> str:
92 """Return display label for a command column header."""
93 if cmd in _CMD_ALIASES:
94 return _CMD_ALIASES[cmd]
95 # Fallback: strip /ll: prefix and truncate
96 short = cmd[4:] if cmd.startswith("/ll:") else cmd
97 return _truncate(short, _CMD_WIDTH)
100def _source_label(discovered_by: str | None) -> str:
101 """Return short display label for an issue's origin source."""
102 if not discovered_by:
103 return "\u2014" # em-dash
104 if discovered_by in _CMD_ALIASES:
105 return _CMD_ALIASES[discovered_by]
106 # Non-/ll: values like "github_sync" — truncate to fit
107 return _truncate(discovered_by, _SOURCE_WIDTH)
110def _truncate(text: str, width: int) -> str:
111 """Truncate text to width, replacing last char with ellipsis if needed."""
112 if len(text) <= width:
113 return text
114 return text[: width - 1].rstrip() + "\u2026"
117def _col(text: str, width: int) -> str:
118 """Left-justify text in a fixed-width column."""
119 return text.ljust(width)[:width]
122def _rcol(text: str, width: int) -> str:
123 """Right-justify text in a fixed-width column."""
124 return text.rjust(width)[:width]
127def _apply_cell_color(col: str, padded: str, plain: str) -> str:
128 """Colorize the visible content of a padded cell, preserving surrounding whitespace."""
129 if col == "id":
130 issue_type = plain.split("-")[0]
131 code = TYPE_COLOR.get(issue_type, "")
132 elif col == "priority":
133 code = PRIORITY_COLOR.get(plain, "")
134 elif col in ("norm", "fmt"):
135 if plain == "\u2713": # ✓
136 code = "32" # green
137 elif plain == "\u2717": # ✗
138 code = "31" # red
139 else:
140 code = ""
141 else:
142 return padded
144 if not code:
145 return padded
147 # Preserve leading spaces (rjust cells) and trailing spaces (ljust cells)
148 lstripped = padded.lstrip()
149 leading = padded[: len(padded) - len(lstripped)]
150 content = lstripped.rstrip()
151 trailing = lstripped[len(content) :]
152 return leading + colorize(content, code) + trailing
155def cmd_refine_status(config: BRConfig, args: argparse.Namespace) -> int:
156 """Render a refinement depth table for all active issues.
158 Each column represents a distinct /ll:* command found across Session Log
159 sections. Issues are sorted descending by refinement depth (Total), then
160 ascending by priority as a tiebreaker.
162 Args:
163 config: Project configuration.
164 args: Parsed arguments with optional .type and .format attributes.
166 Returns:
167 Exit code (0 = success).
168 """
169 from little_loops.issue_parser import find_issues, is_formatted, is_normalized
171 type_prefixes = {args.type} if getattr(args, "type", None) else None
172 issues = find_issues(config, type_prefixes=type_prefixes)
174 if not issues:
175 print("No active issues found.")
176 return 0
178 # Derive dynamic column set: all distinct commands across all issues
179 seen: dict[str, None] = {}
180 for issue in issues:
181 for cmd in issue.session_commands:
182 seen[cmd] = None
184 def _canonical_sort_key(cmd: str) -> tuple[int, str]:
185 try:
186 return (_CANONICAL_CMD_ORDER.index(cmd), cmd)
187 except ValueError:
188 return (len(_CANONICAL_CMD_ORDER), cmd)
190 all_cmds: list[str] = [
191 cmd for cmd in sorted(seen.keys(), key=_canonical_sort_key) if cmd not in _SOURCE_CMDS
192 ]
194 # Sort issues: descending by total commands touched, then ascending priority
195 def _sort_key(issue: IssueInfo) -> tuple[int, int]:
196 return (-len(issue.session_commands), issue.priority_int)
198 sorted_issues = sorted(issues, key=_sort_key)
200 # Dynamic ID column width: size to the longest issue_id present, minimum 8
201 id_width = max((len(issue.issue_id) for issue in sorted_issues), default=7) + 1
203 use_json_array = getattr(args, "json", False)
204 fmt = getattr(args, "format", "table")
206 if use_json_array:
207 print_json(
208 [
209 {
210 "id": issue.issue_id,
211 "priority": issue.priority,
212 "title": issue.title,
213 "source": issue.discovered_by,
214 "commands": issue.session_commands,
215 "confidence_score": issue.confidence_score,
216 "outcome_confidence": issue.outcome_confidence,
217 "total": len(issue.session_commands),
218 "normalized": is_normalized(issue.path.name),
219 "formatted": is_formatted(issue.path),
220 "refine_count": issue.session_command_counts.get("/ll:refine-issue", 0),
221 }
222 for issue in sorted_issues
223 ]
224 )
225 return 0
227 if fmt == "json":
228 for issue in sorted_issues:
229 record = {
230 "id": issue.issue_id,
231 "priority": issue.priority,
232 "title": issue.title,
233 "source": issue.discovered_by,
234 "commands": issue.session_commands,
235 "confidence_score": issue.confidence_score,
236 "outcome_confidence": issue.outcome_confidence,
237 "total": len(issue.session_commands),
238 "normalized": is_normalized(issue.path.name),
239 "formatted": is_formatted(issue.path),
240 "refine_count": issue.session_command_counts.get("/ll:refine-issue", 0),
241 }
242 print(json.dumps(record))
243 return 0
245 # --- Table rendering ---
246 term_cols = terminal_width()
248 # Determine active static columns from config (empty list = use defaults)
249 config_cols = config.refine_status.columns
250 active_static = list(config_cols) if config_cols else list(_DEFAULT_STATIC_COLUMNS)
252 # Split active columns: pre-cmd (before dynamic command block) and post-cmd (after)
253 pre_cmd = [c for c in active_static if c not in _POST_CMD_STATIC]
254 post_cmd = [c for c in active_static if c in _POST_CMD_STATIC]
256 # Compute title column width based on active columns and terminal size
257 has_title = "title" in pre_cmd
258 title_w = _MIN_TITLE_WIDTH
259 if has_title:
260 n_parts = len(pre_cmd) + len(all_cmds) + len(post_cmd)
261 non_title_sum = (
262 sum(
263 (id_width if c == "id" else _STATIC_COLUMN_SPECS[c][0])
264 if c in _STATIC_COLUMN_SPECS
265 else _CMD_WIDTH
266 for c in pre_cmd
267 if c != "title"
268 )
269 + len(all_cmds) * _CMD_WIDTH
270 + sum(
271 _STATIC_COLUMN_SPECS[c][0] if c in _STATIC_COLUMN_SPECS else _CMD_WIDTH
272 for c in post_cmd
273 )
274 )
275 title_w = max(_MIN_TITLE_WIDTH, term_cols - non_title_sum - 2 * (n_parts - 1))
277 def _get_col_display_width(col: str) -> int:
278 if col == "id":
279 return id_width
280 if col == "title":
281 return title_w
282 if col in _STATIC_COLUMN_SPECS:
283 return _STATIC_COLUMN_SPECS[col][0]
284 return _CMD_WIDTH
286 def _render_cell(col: str, value: str) -> str:
287 w = _get_col_display_width(col)
288 if col in _STATIC_COLUMN_SPECS:
289 rjust = _STATIC_COLUMN_SPECS[col][2]
290 return _rcol(value, w) if rjust else _col(value, w)
291 return _col(value, w)
293 def _header_cell(col: str) -> str:
294 if col in _STATIC_COLUMN_SPECS:
295 hdr = _STATIC_COLUMN_SPECS[col][1]
296 else:
297 hdr = _truncate(col, _get_col_display_width(col))
298 return _render_cell(col, hdr)
300 def _cell_value(col: str, issue: IssueInfo) -> str:
301 if col == "id":
302 return issue.issue_id
303 if col == "priority":
304 return issue.priority
305 if col == "title":
306 return _truncate(issue.title, title_w)
307 if col == "source":
308 return _source_label(issue.discovered_by)
309 if col == "norm":
310 return "\u2713" if is_normalized(issue.path.name) else "\u2717"
311 if col == "fmt":
312 return "\u2713" if is_formatted(issue.path) else "\u2717"
313 if col == "ready":
314 return str(issue.confidence_score) if issue.confidence_score is not None else "\u2014"
315 if col == "confidence":
316 return (
317 str(issue.outcome_confidence) if issue.outcome_confidence is not None else "\u2014"
318 )
319 if col == "total":
320 return str(len(issue.session_commands))
321 return "\u2014" # unknown column: em-dash
323 def _build_row(issue: IssueInfo | None) -> str:
324 parts: list[str] = []
325 cmd_set = set(issue.session_commands) if issue is not None else set()
327 for c in pre_cmd:
328 if issue is None:
329 parts.append(_header_cell(c))
330 else:
331 plain = _cell_value(c, issue)
332 parts.append(_apply_cell_color(c, _render_cell(c, plain), plain))
334 for c in all_cmds:
335 if issue is None:
336 parts.append(_col(_cmd_label(c), _CMD_WIDTH))
337 else:
338 if c == "/ll:refine-issue":
339 cell = str(issue.session_command_counts.get(c, 0))
340 parts.append(_col(cell, _CMD_WIDTH))
341 else:
342 hit = c in cmd_set
343 raw = "\u2713" if hit else "\u2014"
344 padded = _col(raw, _CMD_WIDTH)
345 parts.append(
346 colorize(raw, "32") + padded[len(raw) :]
347 if hit
348 else colorize(raw, "2") + padded[len(raw) :]
349 )
351 for c in post_cmd:
352 if issue is None:
353 parts.append(_header_cell(c))
354 else:
355 plain = _cell_value(c, issue)
356 parts.append(_apply_cell_color(c, _render_cell(c, plain), plain))
358 return " ".join(parts)
360 header = _build_row(None)
361 separator = "-" * len(header)
363 rows: list[str] = [header, separator]
365 for issue in sorted_issues:
366 rows.append(_build_row(issue))
368 print("\n".join(rows))
370 issue_word = "issue" if len(sorted_issues) == 1 else "issues"
371 scored = sum(1 for i in sorted_issues if i.confidence_score is not None)
372 print(f"\n{len(sorted_issues)} {issue_word} ({scored} scored)")
374 if not getattr(args, "no_key", False):
375 _print_key(all_cmds)
377 return 0
380def _print_key(all_cmds: list[str]) -> None:
381 """Print a legend mapping column headers to their full command names."""
382 print("\nKey:")
383 print(f" {'source':<12} Origin command/workflow that created the issue")
384 print(f" {'norm':<12} Filename follows naming convention (P[0-5]-TYPE-NNN-desc.md)")
385 print(f" {'fmt':<12} Issue has all required sections per type template (structural check)")
386 for cmd in all_cmds:
387 label = _cmd_label(cmd)
388 if cmd == "/ll:refine-issue":
389 print(f" {label:<12} Times /ll:refine-issue was run")
390 else:
391 print(f" {label:<12} {cmd}")
392 print(f" {'ready':<12} Readiness score (0\u2013100)")
393 print(f" {'conf':<12} Outcome confidence score (0\u2013100)")
394 print(f" {'total':<12} Number of /ll:* skills applied")