Coverage for little_loops / cli / loop / info.py: 0%

500 statements  

« prev     ^ index     » next       coverage.py v7.12.0, created at 2026-03-14 23:20 -0500

1"""ll-loop info subcommands: list, history, show.""" 

2 

3from __future__ import annotations 

4 

5import argparse 

6import os 

7from datetime import datetime 

8from pathlib import Path 

9from typing import Any 

10 

11from little_loops.cli.loop._helpers import ( 

12 get_builtin_loops_dir, 

13 load_loop_with_spec, 

14 resolve_loop_path, 

15) 

16from little_loops.cli.loop.layout import ( # noqa: F401 

17 _EDGE_LABEL_COLORS, 

18 _box_inner_lines, 

19 _colorize_diagram_labels, 

20 _colorize_label, 

21 _render_fsm_diagram, 

22) 

23from little_loops.cli.output import colorize, print_json, terminal_width 

24from little_loops.fsm.schema import FSMLoop, StateConfig 

25from little_loops.logger import Logger 

26 

27 

28def _load_loop_meta(path: Path) -> str: 

29 """Return description from a loop YAML file.""" 

30 import yaml 

31 

32 try: 

33 with open(path) as f: 

34 spec = yaml.safe_load(f) or {} 

35 desc_raw = spec.get("description", "") or "" 

36 return desc_raw.splitlines()[0] if desc_raw.strip() else "" 

37 except Exception: 

38 return "" 

39 

40 

41def cmd_list( 

42 args: argparse.Namespace, 

43 loops_dir: Path, 

44) -> int: 

45 """List loops.""" 

46 status_filter = getattr(args, "status", None) 

47 if getattr(args, "running", False) or status_filter: 

48 from little_loops.fsm.persistence import list_running_loops 

49 

50 states = list_running_loops(loops_dir) 

51 if status_filter: 

52 states = [s for s in states if s.status == status_filter] 

53 if not states: 

54 if status_filter: 

55 print(f"No loops with status: {status_filter}") 

56 return 1 

57 print("No running loops") 

58 return 0 

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

60 print_json([s.to_dict() for s in states]) 

61 return 0 

62 print(colorize("Running loops:", "1")) 

63 _STATUS_COLORS = {"running": "32", "interrupted": "33", "stopped": "2"} 

64 for state in states: 

65 elapsed_s = (state.accumulated_ms or 0) // 1000 

66 elapsed_str = ( 

67 f"{elapsed_s}s" if elapsed_s < 60 else f"{elapsed_s // 60}m {elapsed_s % 60}s" 

68 ) 

69 name_str = colorize(state.loop_name, "1") 

70 state_str = colorize(state.current_state, "34") 

71 status_color = _STATUS_COLORS.get(state.status, "2") 

72 status_str = colorize(f"[{state.status}]", status_color) 

73 elapsed_colored = colorize(elapsed_str, "2") 

74 print( 

75 f" {name_str}: {state_str} (iteration {state.iteration})" 

76 f" {status_str} {elapsed_colored}" 

77 ) 

78 return 0 

79 

80 # Collect project loops 

81 project_names: set[str] = set() 

82 yaml_files: list[Path] = [] 

83 if loops_dir.exists(): 

84 yaml_files = list(loops_dir.glob("*.yaml")) 

85 project_names = {p.stem for p in yaml_files} 

86 

87 # Collect built-in loops (excluding those overridden by project) 

88 builtin_dir = get_builtin_loops_dir() 

89 builtin_files: list[Path] = [] 

90 if builtin_dir.exists(): 

91 builtin_files = [ 

92 f for f in sorted(builtin_dir.glob("*.yaml")) if f.stem not in project_names 

93 ] 

94 

95 if not yaml_files and not builtin_files: 

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

97 print_json([]) 

98 return 0 

99 print("No loops available") 

100 return 0 

101 

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

103 items: list[dict[str, Any]] = [{"name": p.stem, "path": str(p)} for p in sorted(yaml_files)] 

104 items += [{"name": p.stem, "path": str(p), "built_in": True} for p in builtin_files] 

105 print_json(items) 

106 return 0 

107 

108 if yaml_files and builtin_files: 

109 print(colorize(f"Project loops ({len(yaml_files)}):", "1")) 

110 for path in sorted(yaml_files): 

111 desc = _load_loop_meta(path) 

112 name_str = colorize(path.stem, "36;1") 

113 desc_str = f" {colorize(desc, '2')}" if desc else "" 

114 print(f" {name_str}{desc_str}") 

115 print() 

116 print(colorize(f"Built-in loops ({len(builtin_files)}):", "1")) 

117 for path in builtin_files: 

118 desc = _load_loop_meta(path) 

119 name_str = colorize(path.stem, "36;1") 

120 desc_str = f" {colorize(desc, '2')}" if desc else "" 

121 tag_str = colorize("[built-in]", "2") 

122 print(f" {name_str}{desc_str} {tag_str}") 

123 elif yaml_files: 

124 print(colorize("Available loops:", "1")) 

125 for path in sorted(yaml_files): 

126 desc = _load_loop_meta(path) 

127 name_str = colorize(path.stem, "36;1") 

128 desc_str = f" {colorize(desc, '2')}" if desc else "" 

129 print(f" {name_str}{desc_str}") 

130 else: 

131 print(colorize("Available loops:", "1")) 

132 for path in builtin_files: 

133 desc = _load_loop_meta(path) 

134 name_str = colorize(path.stem, "36;1") 

135 desc_str = f" {colorize(desc, '2')}" if desc else "" 

136 tag_str = colorize("[built-in]", "2") 

137 print(f" {name_str}{desc_str} {tag_str}") 

138 return 0 

139 

140 

141_EVENT_TYPE_WIDTH = 16 # width of "handoff_detected" 

142 

143 

144def _truncate(text: str, max_len: int) -> str: 

145 """Truncate text to max_len with ellipsis.""" 

146 if max_len < 1: 

147 return "" 

148 if len(text) <= max_len: 

149 return text 

150 return text[: max_len - 1] + "\u2026" 

151 

152 

153def _format_history_event( 

154 event: dict[str, Any], verbose: bool, width: int, full: bool = False 

155) -> str | None: 

156 """Format a single history event. Returns None to skip the event.""" 

157 raw_ts = event.get("ts", "") 

158 try: 

159 ts = datetime.fromisoformat(raw_ts).strftime("%H:%M:%S") 

160 except (ValueError, TypeError): 

161 ts = raw_ts[:8] if len(raw_ts) >= 8 else raw_ts.ljust(8) 

162 

163 event_type = event.get("event", "unknown") 

164 

165 if event_type == "action_output" and not verbose: 

166 return None 

167 

168 ts_str = colorize(ts, "2") 

169 etype_padded = event_type.ljust(_EVENT_TYPE_WIDTH) 

170 etype_color = "0" 

171 detail = "" 

172 extra_lines: list[str] = [] 

173 

174 # Indentation prefix for verbose sub-lines (aligns under event detail column) 

175 _indent = " " * (8 + 2 + _EVENT_TYPE_WIDTH + 2) 

176 

177 if event_type == "loop_start": 

178 etype_color = "1" 

179 detail = event.get("loop", "") 

180 

181 elif event_type == "loop_complete": 

182 etype_color = "1" 

183 final_state = event.get("final_state", "") 

184 iterations = event.get("iterations", "") 

185 terminated_by = event.get("terminated_by", "") 

186 detail = f"{final_state} {iterations} iter [{terminated_by}]" 

187 

188 elif event_type == "loop_resume": 

189 etype_color = "1" 

190 from_state = event.get("from_state", "") 

191 iteration = event.get("iteration", "") 

192 detail = f"from={from_state} iter={iteration}" 

193 

194 elif event_type == "state_enter": 

195 etype_color = "34" 

196 state = event.get("state", "") 

197 iteration = event.get("iteration", "") 

198 detail = f"{colorize(state, '1')} (iter {iteration})" 

199 

200 elif event_type == "action_start": 

201 action = event.get("action", "") 

202 is_prompt = event.get("is_prompt", False) 

203 kind_label = "prompt" if is_prompt else "shell" 

204 kind_str = colorize(f"[{kind_label}]", "2") 

205 first_line = ( 

206 next((ln.strip() for ln in action.splitlines() if ln.strip()), "") 

207 if is_prompt 

208 else action 

209 ) 

210 avail = width - 8 - 2 - _EVENT_TYPE_WIDTH - 2 - len(kind_label) - 2 - 2 

211 detail = f"{_truncate(first_line, max(avail, 20))} {kind_str}" 

212 

213 elif event_type == "action_output": 

214 # Only reached in verbose mode 

215 etype_color = "2" 

216 detail = colorize("\u2502 " + event.get("line", ""), "2") 

217 

218 elif event_type == "action_complete": 

219 exit_code = event.get("exit_code", 0) 

220 duration_ms = event.get("duration_ms", 0) 

221 if exit_code == 0: 

222 etype_color = "2" 

223 status_str = colorize("\u2713", "32") 

224 else: 

225 etype_color = "38;5;208" 

226 status_str = colorize(f"\u2717 exit={exit_code}", "38;5;208") 

227 detail = f"{status_str} {duration_ms}ms" 

228 is_prompt = event.get("is_prompt", False) 

229 session_jsonl = event.get("session_jsonl") if is_prompt else None 

230 if session_jsonl: 

231 session_display = session_jsonl if verbose else os.path.basename(session_jsonl) 

232 detail += f" session={colorize(session_display, '2')}" 

233 if verbose: 

234 output_preview = event.get("output_preview", "") 

235 if output_preview: 

236 avail_w = width - len(_indent) - 2 

237 preview_text = ( 

238 output_preview if full else _truncate(output_preview, max(avail_w, 40)) 

239 ) 

240 for preview_line in preview_text.splitlines()[:5]: 

241 extra_lines.append(colorize(_indent + "\u2502 " + preview_line, "2")) 

242 

243 elif event_type == "evaluate": 

244 verdict = event.get("verdict", "") 

245 confidence = event.get("confidence", "") 

246 reason = event.get("reason", "") 

247 if verdict == "yes": 

248 etype_color = "32" 

249 verdict_str = colorize("\u2713 yes", "32") 

250 else: 

251 etype_color = "38;5;208" 

252 verdict_str = colorize(f"\u2717 {verdict}", "38;5;208") 

253 conf_part = f" confidence={confidence}" if confidence != "" else "" 

254 avail = width - 8 - 2 - _EVENT_TYPE_WIDTH - 2 - len("\u2713 yes") - len(conf_part) - 2 

255 reason_part = f" {_truncate(reason, max(avail, 20))}" if reason else "" 

256 detail = f"{verdict_str}{conf_part}{reason_part}" 

257 if verbose: 

258 llm_model = event.get("llm_model", "") 

259 llm_latency_ms = event.get("llm_latency_ms", "") 

260 llm_prompt = event.get("llm_prompt", "") 

261 llm_raw_output = event.get("llm_raw_output", "") 

262 if llm_model or llm_prompt: 

263 meta_parts = [] 

264 if llm_model: 

265 meta_parts.append(f"model={llm_model}") 

266 if llm_latency_ms != "": 

267 meta_parts.append(f"latency={llm_latency_ms}ms") 

268 meta_str = " ".join(meta_parts) 

269 extra_lines.append( 

270 colorize(_indent + colorize("LLM Call", "2") + " " + meta_str, "2") 

271 ) 

272 avail_w = width - len(_indent) - len("Prompt: ") - 2 

273 if llm_prompt: 

274 prompt_text = llm_prompt if full else _truncate(llm_prompt, max(avail_w, 40)) 

275 extra_lines.append(colorize(_indent + "Prompt: " + prompt_text, "2")) 

276 if llm_raw_output: 

277 resp_text = ( 

278 llm_raw_output if full else _truncate(llm_raw_output, max(avail_w, 40)) 

279 ) 

280 extra_lines.append(colorize(_indent + "Response: " + resp_text, "2")) 

281 

282 elif event_type == "route": 

283 etype_color = "2" 

284 from_state = event.get("from", "") 

285 to_state = event.get("to", "") 

286 detail = f"{from_state} \u2192 {colorize(to_state, '34')}" 

287 

288 elif event_type == "handoff_detected": 

289 etype_color = "33" 

290 detail = f"state={event.get('state', '')} iter={event.get('iteration', '')}" 

291 

292 else: 

293 details = {k: v for k, v in event.items() if k not in ("event", "ts")} 

294 detail = " ".join(f"{k}={v}" for k, v in details.items()) 

295 

296 etype_str = colorize(etype_padded, etype_color) 

297 main_line = f"{ts_str} {etype_str} {detail}" 

298 if extra_lines: 

299 return "\n".join([main_line] + extra_lines) 

300 return main_line 

301 

302 

303def _format_duration(ms: int) -> str: 

304 """Format milliseconds as a human-readable duration.""" 

305 if ms < 1000: 

306 return f"{ms}ms" 

307 s = ms // 1000 

308 if s < 60: 

309 return f"{s}s" 

310 m, s = divmod(s, 60) 

311 if m < 60: 

312 return f"{m}m{s:02d}s" 

313 h, m = divmod(m, 60) 

314 return f"{h}h{m:02d}m{s:02d}s" 

315 

316 

317def _list_archived_runs(loop_name: str, loops_dir: Path, as_json: bool) -> int: 

318 """List archived runs for a loop.""" 

319 import json as _json 

320 

321 from little_loops.fsm.persistence import HISTORY_DIR, LoopState 

322 

323 history_base = loops_dir / HISTORY_DIR / loop_name 

324 if not history_base.exists(): 

325 print(f"No history for: {loop_name}") 

326 return 0 

327 

328 # Collect (run_id, state_or_None) pairs sorted newest first by run_id 

329 runs: list[tuple[str, LoopState | None]] = [] 

330 for run_dir in sorted(history_base.iterdir(), key=lambda d: d.name, reverse=True): 

331 if not run_dir.is_dir(): 

332 continue 

333 state_file = run_dir / "state.json" 

334 state: LoopState | None = None 

335 if state_file.exists(): 

336 try: 

337 data = _json.loads(state_file.read_text()) 

338 state = LoopState.from_dict(data) 

339 except (ValueError, KeyError): 

340 pass 

341 runs.append((run_dir.name, state)) 

342 

343 if not runs: 

344 print(f"No history for: {loop_name}") 

345 return 0 

346 

347 if as_json: 

348 print( 

349 _json.dumps( 

350 [ 

351 { 

352 "run_id": rid, 

353 "status": s.status if s else None, 

354 "started_at": s.started_at if s else None, 

355 "iterations": s.iteration if s else None, 

356 "duration_ms": s.accumulated_ms if s else None, 

357 } 

358 for rid, s in runs 

359 ], 

360 indent=2, 

361 ) 

362 ) 

363 return 0 

364 

365 status_colors = { 

366 "completed": "\033[32m", 

367 "failed": "\033[31m", 

368 "interrupted": "\033[33m", 

369 "awaiting_continuation": "\033[36m", 

370 "timed_out": "\033[33m", 

371 "running": "\033[34m", 

372 } 

373 reset = "\033[0m" 

374 

375 print(f"Archived runs for: {loop_name} ({len(runs)} total)") 

376 print() 

377 

378 for run_id, state in runs: 

379 if state is not None: 

380 color = status_colors.get(state.status, "") 

381 status_str = f"{color}{state.status}{reset}" 

382 duration_str = _format_duration(state.accumulated_ms) if state.accumulated_ms else "?" 

383 started = state.started_at[:19].replace("T", " ") if state.started_at else "?" 

384 iters = f"{state.iteration} iters" 

385 else: 

386 status_str = "unknown" 

387 duration_str = "?" 

388 started = "?" 

389 iters = "?" 

390 print(f" {run_id} {status_str} {started} {iters} {duration_str}") 

391 

392 print() 

393 print(f"To view events: ll-loop history {loop_name} <run-id>") 

394 return 0 

395 

396 

397def cmd_history( 

398 loop_name: str, 

399 run_id: str | None, 

400 args: argparse.Namespace, 

401 loops_dir: Path, 

402) -> int: 

403 """Show loop history. 

404 

405 Without run_id: lists all archived runs with status and duration. 

406 With run_id: shows events for that specific archived run. 

407 """ 

408 tail = getattr(args, "tail", 50) 

409 full = getattr(args, "full", False) 

410 verbose = getattr(args, "verbose", False) or full 

411 as_json = getattr(args, "json", False) 

412 

413 if run_id is None: 

414 return _list_archived_runs(loop_name, loops_dir, as_json) 

415 

416 # Show events for a specific archived run 

417 from little_loops.fsm.persistence import get_archived_events 

418 

419 events = get_archived_events(loop_name, run_id, loops_dir) 

420 

421 if not events: 

422 print(f"No events found for run: {loop_name}/{run_id}") 

423 return 1 

424 

425 w = terminal_width() 

426 if not verbose: 

427 events = [e for e in events if e.get("event") != "action_output"] 

428 if as_json: 

429 print_json(events[-tail:]) 

430 return 0 

431 for event in events[-tail:]: 

432 line = _format_history_event(event, verbose, w, full=full) 

433 if line is not None: 

434 print(line) 

435 

436 return 0 

437 

438 

439# --------------------------------------------------------------------------- 

440# FSM diagram renderer — delegated to layout module (re-exported above) 

441# --------------------------------------------------------------------------- 

442 

443 

444# --------------------------------------------------------------------------- 

445# State overview table 

446# --------------------------------------------------------------------------- 

447 

448 

449def _compact_transitions(state: StateConfig) -> str: 

450 """Return a compact transition string for the overview table.""" 

451 raw: list[tuple[str, str]] = [] 

452 for label, target in [ 

453 ("yes", state.on_yes), 

454 ("no", state.on_no), 

455 ("error", state.on_error), 

456 ("partial", state.on_partial), 

457 ("next", state.next), 

458 ]: 

459 if target: 

460 raw.append((label, target)) 

461 if state.route: 

462 for verdict, target in state.route.routes.items(): 

463 raw.append((verdict, target)) 

464 if state.route.default: 

465 raw.append(("_", state.route.default)) 

466 if not raw: 

467 return "\u2014" 

468 # Group by target, preserving first-seen order 

469 seen: list[str] = [] 

470 by_target: dict[str, list[str]] = {} 

471 for label, target in raw: 

472 if target not in by_target: 

473 seen.append(target) 

474 by_target[target] = [] 

475 by_target[target].append(label) 

476 return ", ".join(f"{'/'.join(by_target[t])}\u2192{t}" for t in seen) 

477 

478 

479def _print_state_overview_table(fsm: FSMLoop) -> None: 

480 """Print a compact summary table of all states.""" 

481 rows: list[tuple[str, str, str, str]] = [] 

482 for name, state in fsm.states.items(): 

483 # State name column 

484 state_col = f"\u2192 {name}" if name == fsm.initial else f" {name}" 

485 

486 # Type column 

487 if state.terminal: 

488 type_col = "\u2014" 

489 elif state.action_type: 

490 type_col = state.action_type 

491 elif state.action: 

492 type_col = "shell" 

493 else: 

494 type_col = "\u2014" 

495 

496 # Action preview column 

497 if state.terminal: 

498 action_col = "(terminal)" 

499 elif state.action: 

500 src_lines = [ln.rstrip() for ln in state.action.strip().splitlines() if ln.rstrip()] 

501 action_col = src_lines[0] if src_lines else "\u2014" 

502 else: 

503 action_col = "\u2014" 

504 

505 # Transitions column 

506 trans_col = _compact_transitions(state) 

507 rows.append((state_col, type_col, action_col, trans_col)) 

508 

509 if not rows: 

510 return 

511 

512 tw = terminal_width() 

513 headers = ("State", "Type", "Action Preview", "Transitions") 

514 col0_w = max(len(headers[0]), max(len(r[0]) for r in rows)) 

515 col1_w = max(len(headers[1]), max(len(r[1]) for r in rows)) 

516 # Remaining width split between action preview and transitions 

517 fixed = col0_w + col1_w + 10 # margins + separators 

518 remaining = max(20, tw - fixed) 

519 col2_w = min(50, max(len(headers[2]), max(len(r[2]) for r in rows)), remaining * 3 // 5) 

520 col2_w = max(10, col2_w) 

521 col3_w = max(10, remaining - col2_w) 

522 

523 print(f" {headers[0]:<{col0_w}} {headers[1]:<{col1_w}} {headers[2]:<{col2_w}} {headers[3]}") 

524 dash = "\u2500" 

525 print(f" {dash * col0_w} {dash * col1_w} {dash * col2_w} {dash * col3_w}") 

526 for state_col, type_col, action_col, trans_col in rows: 

527 if len(action_col) > col2_w: 

528 action_col = action_col[: col2_w - 1] + "\u2026" 

529 if len(trans_col) > col3_w: 

530 trans_col = trans_col[: col3_w - 1] + "\u2026" 

531 colored_type = colorize(type_col, "2") if type_col == "\u2014" else type_col 

532 print( 

533 f" {state_col:<{col0_w}} {colored_type:<{col1_w}} " 

534 f"{action_col:<{col2_w}} {trans_col}" 

535 ) 

536 

537 

538# --------------------------------------------------------------------------- 

539# cmd_show 

540# --------------------------------------------------------------------------- 

541 

542_EVALUATE_TYPE_DISPLAY: dict[str, str] = { 

543 "llm": "LLM", 

544 "llm_structured": "LLM (structured)", 

545 "exit_code": "exit code", 

546 "output_numeric": "numeric", 

547 "output_contains": "contains", 

548 "output_json": "JSON", 

549 "convergence": "convergence", 

550} 

551 

552 

553def _humanize_evaluate_type(ev_type: str) -> str: 

554 return _EVALUATE_TYPE_DISPLAY.get(ev_type, ev_type) 

555 

556 

557def cmd_show( 

558 loop_name: str, 

559 args: argparse.Namespace, 

560 loops_dir: Path, 

561 logger: Logger, 

562) -> int: 

563 """Show loop details and structure.""" 

564 try: 

565 path = resolve_loop_path(loop_name, loops_dir) 

566 fsm, spec = load_loop_with_spec(loop_name, loops_dir, logger) 

567 except FileNotFoundError as e: 

568 logger.error(str(e)) 

569 return 1 

570 except ValueError as e: 

571 logger.error(f"Invalid loop: {e}") 

572 return 1 

573 

574 tw = terminal_width() 

575 

576 # Compute stats for header 

577 n_states = len(fsm.states) 

578 n_transitions = sum( 

579 bool(s.on_yes) 

580 + bool(s.on_no) 

581 + bool(s.on_error) 

582 + bool(s.on_partial) 

583 + bool(s.next) 

584 + bool(s.on_maintain) 

585 + (len(s.route.routes) + bool(s.route.default) if s.route else 0) 

586 for s in fsm.states.values() 

587 ) 

588 

589 # --- Compact metadata header --- 

590 # Line 1: ── name ───────── N states · M transitions ── 

591 stats_parts: list[str] = [] 

592 stats_parts.append(f"{n_states} states") 

593 stats_parts.append(f"{n_transitions} transitions") 

594 stats_str = " \u00b7 ".join(stats_parts) 

595 

596 header_left = f"\u2500\u2500 {loop_name} " 

597 header_right = f" {stats_str} \u2500\u2500" 

598 dashes = "\u2500" * max(0, tw - len(header_left) - len(header_right)) 

599 print(f"{header_left}{dashes}{header_right}") 

600 

601 # Line 2: source · max: N iter · handoff: X [· optional fields] 

602 config_parts: list[str] = [str(path), f"max: {fsm.max_iterations} iter"] 

603 config_parts.append(f"handoff: {fsm.on_handoff}") 

604 if fsm.timeout: 

605 config_parts.append(f"timeout: {fsm.timeout}s") 

606 if fsm.backoff: 

607 config_parts.append(f"backoff: {fsm.backoff}s") 

608 if fsm.maintain: 

609 config_parts.append("maintain: yes") 

610 if fsm.context: 

611 config_parts.append(f"context: {', '.join(fsm.context.keys())}") 

612 if fsm.scope: 

613 config_parts.append(f"scope: {', '.join(fsm.scope)}") 

614 llm = fsm.llm 

615 llm_parts = [] 

616 if llm.model != "sonnet": 

617 llm_parts.append(f"model={llm.model}") 

618 if llm.max_tokens != 256: 

619 llm_parts.append(f"max_tokens={llm.max_tokens}") 

620 if llm.timeout != 30: 

621 llm_parts.append(f"timeout={llm.timeout}s") 

622 if llm_parts: 

623 config_parts.append(f"llm: {', '.join(llm_parts)}") 

624 print(" " + " \u00b7 ".join(config_parts)) 

625 

626 # --- Description --- 

627 description = spec.get("description", "").strip() 

628 if description: 

629 print() 

630 print("Description:") 

631 for line in description.splitlines(): 

632 print(f" {line}") 

633 

634 # --- ASCII FSM Diagram --- 

635 verbose = getattr(args, "verbose", False) 

636 print() 

637 print("Diagram:") 

638 diagram = _render_fsm_diagram(fsm, verbose=verbose) 

639 if diagram: 

640 print(diagram) 

641 

642 # --- State overview table --- 

643 print() 

644 _print_state_overview_table(fsm) 

645 

646 # --- States & Transitions (verbose only) --- 

647 if verbose: 

648 print() 

649 print("States:") 

650 first_state = True 

651 for name, state in fsm.states.items(): 

652 if not first_state: 

653 print() 

654 first_state = False 

655 

656 # Improved state section header: ── name ──── MARKERS · type ── 

657 right_parts = [] 

658 if name == fsm.initial: 

659 right_parts.append("INITIAL") 

660 if state.terminal: 

661 right_parts.append("TERMINAL") 

662 if state.action_type: 

663 right_parts.append(state.action_type) 

664 right_info = " \u00b7 ".join(right_parts) 

665 inner_left = f"\u2500\u2500 {name} " 

666 inner_right = f" {right_info} \u2500\u2500" if right_info else " \u2500\u2500" 

667 fill = "\u2500" * max(0, tw - 2 - len(inner_left) - len(inner_right)) 

668 print(f" {inner_left}{fill}{inner_right}") 

669 

670 if state.action: 

671 if verbose: 

672 indented = "\n ".join(state.action.strip().splitlines()) 

673 print(f" action:\n {indented}") 

674 elif state.action_type == "prompt": 

675 lines_act = state.action.strip().splitlines() 

676 preview = "\n ".join(lines_act[:3]) 

677 if len(lines_act) > 3 or len(state.action) > 200: 

678 preview += " ..." 

679 print(f" action:\n {preview}") 

680 else: # shell, slash_command, or None 

681 action_display = ( 

682 state.action[:70] + "..." if len(state.action) > 70 else state.action 

683 ) 

684 print(f" action: {action_display}") 

685 if state.evaluate: 

686 ev = state.evaluate 

687 print(f" evaluate: {_humanize_evaluate_type(ev.type)}") 

688 if ev.prompt: 

689 if verbose: 

690 print(" prompt:") 

691 for line in ev.prompt.strip().splitlines(): 

692 print(f" \u2502 {line}") 

693 else: 

694 ev_lines = ev.prompt.strip().splitlines() 

695 preview = ev_lines[0][:100] + ( 

696 " ..." if len(ev_lines) > 1 or len(ev_lines[0]) > 100 else "" 

697 ) 

698 print(f" prompt: {preview}") 

699 if ev.min_confidence != 0.5: 

700 print(f" min_confidence: {ev.min_confidence}") 

701 if ev.operator: 

702 print(f" operator: {ev.operator} {ev.target}") 

703 if ev.pattern: 

704 print(f" pattern: {ev.pattern}") 

705 if state.capture: 

706 print(f" capture: {state.capture}") 

707 if state.timeout: 

708 print(f" timeout: {state.timeout}s") 

709 # Collect (label, target) pairs 

710 raw_transitions: list[tuple[str, str]] = [] 

711 for label, target in [ 

712 ("yes", state.on_yes), 

713 ("no", state.on_no), 

714 ("error", state.on_error), 

715 ("partial", state.on_partial), 

716 ("next", state.next), 

717 ("maintain", state.on_maintain), 

718 ]: 

719 if target: 

720 raw_transitions.append((label, target)) 

721 if state.route: 

722 for verdict, target in state.route.routes.items(): 

723 raw_transitions.append((verdict, target)) 

724 if state.route.default: 

725 raw_transitions.append(("_", state.route.default)) 

726 # Group by target, preserving first-seen order 

727 target_labels: dict[str, list[str]] = {} 

728 seen_targets: list[str] = [] 

729 for label, target in raw_transitions: 

730 if target not in target_labels: 

731 target_labels[target] = [] 

732 seen_targets.append(target) 

733 target_labels[target].append(label) 

734 transitions = [ 

735 f"{_colorize_label('/'.join(target_labels[t]))} \u2500\u2500\u2192 {t}" 

736 for t in seen_targets 

737 ] 

738 if transitions: 

739 print(" Transitions:") 

740 for t in transitions: 

741 print(f" {t}") 

742 

743 # --- Commands --- 

744 print() 

745 print("Commands:") 

746 cmds = [ 

747 (f"ll-loop run {loop_name}", "run"), 

748 (f"ll-loop test {loop_name}", "single test iteration"), 

749 (f"ll-loop stop {loop_name}", "stop a running loop"), 

750 (f"ll-loop status {loop_name}", "check if running"), 

751 (f"ll-loop history {loop_name}", "execution history"), 

752 ] 

753 col_width = max(len(c) for c, _ in cmds) + 2 

754 for cmd, comment in cmds: 

755 print(f" {cmd:<{col_width}} # {comment}") 

756 

757 return 0