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

408 statements  

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

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

2 

3from __future__ import annotations 

4 

5import argparse 

6from collections import deque 

7from pathlib import Path 

8 

9from little_loops.cli.loop._helpers import ( 

10 get_builtin_loops_dir, 

11 load_loop_with_spec, 

12 resolve_loop_path, 

13) 

14from little_loops.fsm.schema import FSMLoop 

15from little_loops.logger import Logger 

16 

17 

18def cmd_list( 

19 args: argparse.Namespace, 

20 loops_dir: Path, 

21) -> int: 

22 """List loops.""" 

23 if getattr(args, "running", False): 

24 from little_loops.fsm.persistence import list_running_loops 

25 

26 states = list_running_loops(loops_dir) 

27 if not states: 

28 print("No running loops") 

29 return 0 

30 print("Running loops:") 

31 for state in states: 

32 print(f" {state.loop_name}: {state.current_state} (iteration {state.iteration})") 

33 return 0 

34 

35 # Collect project loops 

36 project_names: set[str] = set() 

37 yaml_files: list[Path] = [] 

38 if loops_dir.exists(): 

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

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

41 

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

43 builtin_dir = get_builtin_loops_dir() 

44 builtin_files: list[Path] = [] 

45 if builtin_dir.exists(): 

46 builtin_files = [ 

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

48 ] 

49 

50 if not yaml_files and not builtin_files: 

51 print("No loops available") 

52 return 0 

53 

54 print("Available loops:") 

55 for path in sorted(yaml_files): 

56 print(f" {path.stem}") 

57 for path in builtin_files: 

58 print(f" {path.stem} [built-in]") 

59 return 0 

60 

61 

62def cmd_history( 

63 loop_name: str, 

64 args: argparse.Namespace, 

65 loops_dir: Path, 

66) -> int: 

67 """Show loop history.""" 

68 from little_loops.fsm.persistence import get_loop_history 

69 

70 events = get_loop_history(loop_name, loops_dir) 

71 

72 if not events: 

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

74 return 0 

75 

76 # Show last N events 

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

78 for event in events[-tail:]: 

79 ts = event.get("ts", "")[:19] # Truncate to seconds 

80 event_type = event.get("event", "") 

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

82 print(f"{ts} {event_type}: {details}") 

83 

84 return 0 

85 

86 

87def _render_fsm_diagram(fsm: FSMLoop) -> str: 

88 """Render an improved text diagram of the FSM graph. 

89 

90 Produces three sections: 

91 - Main flow: the primary (happy-path) traversal with edge labels 

92 - Branches: alternate forward transitions not on the main path 

93 - Back-edges: transitions to states earlier in BFS order (cycles) 

94 """ 

95 # Build all edges: (from, to, label) 

96 edges: list[tuple[str, str, str]] = [] 

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

98 if state.on_success: 

99 edges.append((name, state.on_success, "success")) 

100 if state.on_failure: 

101 edges.append((name, state.on_failure, "fail")) 

102 if state.on_error: 

103 edges.append((name, state.on_error, "error")) 

104 if state.next: 

105 edges.append((name, state.next, "next")) 

106 if state.route: 

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

108 edges.append((name, target, verdict)) 

109 if state.route.default: 

110 edges.append((name, state.route.default, "_")) 

111 

112 # BFS to determine a canonical ordering (used for back-edge detection) 

113 bfs_order: list[str] = [] 

114 bfs_depth: dict[str, int] = {fsm.initial: 0} 

115 queue: deque[str] = deque([fsm.initial]) 

116 while queue: 

117 node = queue.popleft() 

118 bfs_order.append(node) 

119 for src, dst, _ in edges: 

120 if src == node and dst not in bfs_depth: 

121 bfs_depth[dst] = bfs_depth[node] + 1 

122 queue.append(dst) 

123 

124 # Trace main path: greedy walk following on_success > next > first route entry 

125 visited: set[str] = set() 

126 main_path: list[str] = [] 

127 main_edge_set: set[tuple[str, str]] = set() 

128 current = fsm.initial 

129 while current and current not in visited: 

130 visited.add(current) 

131 main_path.append(current) 

132 st = fsm.states.get(current) 

133 if not st or st.terminal: 

134 break 

135 nxt: str = st.on_success or st.next or "" 

136 if not nxt and st.route: 

137 nxt = next(iter(st.route.routes.values()), "") or st.route.default or "" 

138 if nxt: 

139 main_edge_set.add((current, nxt)) 

140 current = nxt 

141 else: 

142 break 

143 

144 # Classify remaining edges as branches or back-edges. 

145 # Only consume one edge per main-path (src, dst) pair so that duplicate 

146 # edges (e.g. route_state→done via "pass" AND "skip") are not all dropped. 

147 main_consumed: set[int] = set() 

148 for src, dst in main_edge_set: 

149 for i, (s, d, _) in enumerate(edges): 

150 if s == src and d == dst and i not in main_consumed: 

151 main_consumed.add(i) 

152 break 

153 

154 branches: list[tuple[str, str, str]] = [] 

155 back_edges: list[tuple[str, str, str]] = [] 

156 for i, (src, dst, label) in enumerate(edges): 

157 if i in main_consumed: 

158 continue 

159 src_pos = bfs_order.index(src) if src in bfs_order else len(bfs_order) 

160 dst_pos = bfs_order.index(dst) if dst in bfs_order else len(bfs_order) 

161 if dst == src or dst_pos < src_pos: 

162 back_edges.append((src, dst, label)) 

163 else: 

164 branches.append((src, dst, label)) 

165 

166 return _render_2d_diagram( 

167 main_path, 

168 edges, 

169 main_edge_set, 

170 branches, 

171 back_edges, 

172 bfs_order, 

173 ) 

174 

175 

176def _render_2d_diagram( 

177 main_path: list[str], 

178 edges: list[tuple[str, str, str]], 

179 main_edge_set: set[tuple[str, str]], 

180 branches: list[tuple[str, str, str]], 

181 back_edges: list[tuple[str, str, str]], 

182 bfs_order: list[str], 

183) -> str: 

184 """Render a 2D box-drawing diagram of the FSM graph.""" 

185 if not main_path: 

186 return "" 

187 

188 # Collect all state names (main path + off-path states) 

189 all_states = list(main_path) 

190 off_path: list[str] = [] 

191 for src, dst, _ in branches: 

192 for s in (src, dst): 

193 if s not in all_states: 

194 all_states.append(s) 

195 off_path.append(s) 

196 

197 # Box dimensions: 1 char padding each side 

198 box_width: dict[str, int] = {} 

199 for s in all_states: 

200 box_width[s] = len(s) + 4 # "│ name │" 

201 

202 # Compute column positions for main path boxes 

203 col_start: dict[str, int] = {} # left edge of each box 

204 col_center: dict[str, int] = {} # center column of each box 

205 x = 2 # left margin 

206 for i, sname in enumerate(main_path): 

207 col_start[sname] = x 

208 col_center[sname] = x + box_width[sname] // 2 

209 if i < len(main_path) - 1: 

210 nxt = main_path[i + 1] 

211 label = next( 

212 (lbl for s, d, lbl in edges if s == sname and d == nxt), 

213 "\u2192", 

214 ) 

215 gap = len(label) + 6 # "──label──▶" 

216 x += box_width[sname] + gap 

217 else: 

218 x += box_width[sname] 

219 

220 # Place off-path states below, centered under their first neighbor 

221 for s in off_path: 

222 # Find a neighbor on the main path 

223 neighbor = None 

224 for src, dst, _ in branches + back_edges: 

225 if dst == s and src in col_start: 

226 neighbor = src 

227 break 

228 if src == s and dst in col_start: 

229 neighbor = dst 

230 break 

231 if neighbor: 

232 nc = col_center[neighbor] 

233 col_start[s] = max(2, nc - box_width[s] // 2) 

234 else: 

235 col_start[s] = 2 

236 col_center[s] = col_start[s] + box_width[s] // 2 

237 

238 total_width = x + 4 # some right margin 

239 # Ensure off-path boxes fit within total_width 

240 for s in off_path: 

241 right_edge = col_start[s] + box_width[s] + 4 

242 if right_edge > total_width: 

243 total_width = right_edge 

244 

245 # --- Build main flow rows (3 rows: top border, name, bottom border) --- 

246 row_top = [" "] * total_width 

247 row_mid = [" "] * total_width 

248 row_bot = [" "] * total_width 

249 

250 for sname in main_path: 

251 cx = col_start[sname] 

252 w = box_width[sname] 

253 # Top border: ┌──...──┐ 

254 row_top[cx] = "\u250c" 

255 for j in range(1, w - 1): 

256 row_top[cx + j] = "\u2500" 

257 row_top[cx + w - 1] = "\u2510" 

258 # Middle: │ name │ 

259 row_mid[cx] = "\u2502" 

260 row_mid[cx + w - 1] = "\u2502" 

261 name_start = cx + 2 

262 for j, ch in enumerate(sname): 

263 row_mid[name_start + j] = ch 

264 # Bottom border: └──...──┘ 

265 row_bot[cx] = "\u2514" 

266 for j in range(1, w - 1): 

267 row_bot[cx + j] = "\u2500" 

268 row_bot[cx + w - 1] = "\u2518" 

269 

270 # Draw main-path edge labels on the middle row between boxes 

271 for i in range(len(main_path) - 1): 

272 src_name = main_path[i] 

273 dst_name = main_path[i + 1] 

274 label = next( 

275 (lbl for s, d, lbl in edges if s == src_name and d == dst_name), 

276 "\u2192", 

277 ) 

278 start = col_start[src_name] + box_width[src_name] 

279 end = col_start[dst_name] 

280 # Fill: ──label──▶ 

281 edge_text = "\u2500" + label + "\u2500\u2500\u25b6" 

282 # Right-align the edge_text, fill left side with ─ 

283 available = end - start 

284 left_dashes = available - len(edge_text) 

285 for j in range(left_dashes): 

286 row_mid[start + j] = "\u2500" 

287 for j, ch in enumerate(edge_text): 

288 row_mid[start + left_dashes + j] = ch 

289 

290 lines = [ 

291 "".join(row_top).rstrip(), 

292 "".join(row_mid).rstrip(), 

293 "".join(row_bot).rstrip(), 

294 ] 

295 

296 # --- Self-loops: add ↺ marker below the box --- 

297 self_loops = [(s, d, lbl) for s, d, lbl in back_edges if s == d] 

298 if self_loops: 

299 self_row = [" "] * total_width 

300 for src, _, label in self_loops: 

301 cx = col_center.get(src, 0) 

302 marker = f"\u21ba {label}" 

303 pos = max(0, cx - len(marker) // 2) 

304 for j, ch in enumerate(marker): 

305 if pos + j < total_width: 

306 self_row[pos + j] = ch 

307 lines.append("".join(self_row).rstrip()) 

308 

309 # --- 2D routing for non-main-path edges below the main flow --- 

310 non_self_branches = [(s, d, lbl) for s, d, lbl in branches if s != d] 

311 non_self_back = [(s, d, lbl) for s, d, lbl in back_edges if s != d] 

312 all_extra = non_self_branches + non_self_back 

313 

314 if not all_extra: 

315 return "\n".join(lines) 

316 

317 off_path_set = set(off_path) 

318 main_path_set = set(main_path) 

319 

320 # Categorize: main-to-main edges vs edges involving off-path states 

321 main_extra: list[tuple[str, str, str]] = [] 

322 off_state_edges: dict[str, list[tuple[str, str, str]]] = {s: [] for s in off_path} 

323 

324 for src, dst, label in all_extra: 

325 if src in off_path_set: 

326 off_state_edges[src].append((src, dst, label)) 

327 elif dst in off_path_set: 

328 off_state_edges[dst].append((src, dst, label)) 

329 else: 

330 main_extra.append((src, dst, label)) 

331 

332 # --- Main-to-main edges: U-route below --- 

333 for src, dst, label in main_extra: 

334 src_col = col_center.get(src, 0) 

335 dst_col = col_center.get(dst, 0) 

336 left = min(src_col, dst_col) 

337 right = max(src_col, dst_col) 

338 

339 # Connector row: \u25b2 at destination, \u2502 at source 

340 row = [" "] * total_width 

341 if 0 <= dst_col < total_width: 

342 row[dst_col] = "\u25b2" # \u25b2 

343 if 0 <= src_col < total_width: 

344 row[src_col] = "\u2502" # \u2502 

345 lines.append("".join(row).rstrip()) 

346 

347 # Horizontal route: \u2514\u2500\u2500\u2500label\u2500\u2500\u2500\u2518 

348 row = [" "] * total_width 

349 if left < total_width: 

350 row[left] = "\u2514" # \u2514 

351 if right < total_width: 

352 row[right] = "\u2518" # \u2518 

353 for j in range(left + 1, right): 

354 if j < total_width: 

355 row[j] = "\u2500" # \u2500 

356 # Center the label on the horizontal segment 

357 label_padded = f" {label} " 

358 lstart = (left + right) // 2 - len(label_padded) // 2 

359 for j, ch in enumerate(label_padded): 

360 pos = lstart + j 

361 if left < pos < right and 0 <= pos < total_width: 

362 row[pos] = ch 

363 lines.append("".join(row).rstrip()) 

364 

365 # --- Off-path states: render as boxes with vertical connectors --- 

366 for off_s in off_path: 

367 state_edges = off_state_edges.get(off_s, []) 

368 if not state_edges: 

369 continue 

370 

371 # Find anchor state on main path 

372 anchor = None 

373 for src, dst, _ in state_edges: 

374 other = dst if src == off_s else src 

375 if other in main_path_set: 

376 anchor = other 

377 break 

378 if not anchor: 

379 anchor = main_path[0] 

380 

381 # Classify edges relative to anchor 

382 down_labels: list[str] = [] # anchor \u2192 off_s 

383 up_labels: list[str] = [] # off_s \u2192 anchor 

384 outgoing: list[tuple[str, str, str]] = [] # edges to/from non-anchor states 

385 

386 for src, dst, label in state_edges: 

387 if src == anchor and dst == off_s: 

388 down_labels.append(label) 

389 elif src == off_s and dst == anchor: 

390 up_labels.append(label) 

391 else: 

392 outgoing.append((src, dst, label)) 

393 

394 anchor_cc = col_center[anchor] 

395 off_cs = col_start[off_s] 

396 off_w = box_width[off_s] 

397 

398 has_down = bool(down_labels) 

399 has_up = bool(up_labels) 

400 

401 if has_down and has_up: 

402 down_col = anchor_cc - 1 

403 up_col = anchor_cc + 1 

404 elif has_down: 

405 down_col = anchor_cc 

406 up_col = -1 

407 elif has_up: 

408 down_col = -1 

409 up_col = anchor_cc 

410 else: 

411 down_col = -1 

412 up_col = -1 

413 

414 # Vertical connector rows 

415 if has_down or has_up: 

416 # Row 1: vertical drops / rise arrow 

417 row = [" "] * total_width 

418 if has_down and 0 <= down_col < total_width: 

419 row[down_col] = "\u2502" # \u2502 

420 if has_up and 0 <= up_col < total_width: 

421 row[up_col] = "\u25b2" # \u25b2 

422 lines.append("".join(row).rstrip()) 

423 

424 # Row 2: labels alongside vertical lines 

425 row = [" "] * total_width 

426 if has_down and 0 <= down_col < total_width: 

427 row[down_col] = "\u2502" # \u2502 

428 dlabel = down_labels[0] 

429 dstart = down_col - len(dlabel) - 1 

430 for j, ch in enumerate(dlabel): 

431 if 0 <= dstart + j < total_width: 

432 row[dstart + j] = ch 

433 if has_up and 0 <= up_col < total_width: 

434 row[up_col] = "\u2502" # \u2502 

435 ulabel = up_labels[0] 

436 ustart = up_col + 2 

437 for j, ch in enumerate(ulabel): 

438 if 0 <= ustart + j < total_width: 

439 row[ustart + j] = ch 

440 lines.append("".join(row).rstrip()) 

441 

442 # Row 3: arrow tips 

443 row = [" "] * total_width 

444 if has_down and 0 <= down_col < total_width: 

445 row[down_col] = "\u25bc" # \u25bc 

446 if has_up and 0 <= up_col < total_width: 

447 row[up_col] = "\u2502" # \u2502 

448 lines.append("".join(row).rstrip()) 

449 

450 # Render off-path state box 

451 bx = off_cs 

452 bw = off_w 

453 box_top_r = [" "] * total_width 

454 box_mid_r = [" "] * total_width 

455 box_bot_r = [" "] * total_width 

456 

457 if bx + bw <= total_width: 

458 box_top_r[bx] = "\u250c" 

459 for j in range(1, bw - 1): 

460 box_top_r[bx + j] = "\u2500" 

461 box_top_r[bx + bw - 1] = "\u2510" 

462 

463 box_mid_r[bx] = "\u2502" 

464 box_mid_r[bx + bw - 1] = "\u2502" 

465 for j, ch in enumerate(off_s): 

466 box_mid_r[bx + 2 + j] = ch 

467 

468 box_bot_r[bx] = "\u2514" 

469 for j in range(1, bw - 1): 

470 box_bot_r[bx + j] = "\u2500" 

471 box_bot_r[bx + bw - 1] = "\u2518" 

472 

473 # Draw outgoing edges from off-path box on its middle row 

474 for src, dst, label in outgoing: 

475 if src == off_s: 

476 start_col = bx + bw 

477 target_col = col_center.get(dst, start_col + len(label) + 4) 

478 edge_text = "\u2500" + label + "\u2500\u2500\u25b6" 

479 available = target_col - start_col 

480 if available > len(edge_text): 

481 left_dashes = available - len(edge_text) 

482 for j in range(left_dashes): 

483 if start_col + j < total_width: 

484 box_mid_r[start_col + j] = "\u2500" 

485 for j, ch in enumerate(edge_text): 

486 pos = start_col + left_dashes + j 

487 if pos < total_width: 

488 box_mid_r[pos] = ch 

489 else: 

490 for j, ch in enumerate(edge_text): 

491 if start_col + j < total_width: 

492 box_mid_r[start_col + j] = ch 

493 

494 lines.append("".join(box_top_r).rstrip()) 

495 lines.append("".join(box_mid_r).rstrip()) 

496 lines.append("".join(box_bot_r).rstrip()) 

497 

498 return "\n".join(lines) 

499 

500 

501def cmd_show( 

502 loop_name: str, 

503 loops_dir: Path, 

504 logger: Logger, 

505) -> int: 

506 """Show loop details and structure.""" 

507 try: 

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

509 path = resolve_loop_path(loop_name, loops_dir) 

510 except FileNotFoundError as e: 

511 logger.error(str(e)) 

512 return 1 

513 except ValueError as e: 

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

515 return 1 

516 

517 # --- Metadata --- 

518 print(f"Loop: {fsm.name}") 

519 if fsm.paradigm: 

520 print(f"Paradigm: {fsm.paradigm}") 

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

522 if description: 

523 print(f"Description: {description}") 

524 print(f"Max iterations: {fsm.max_iterations}") 

525 if fsm.timeout: 

526 print(f"Timeout: {fsm.timeout}s") 

527 if fsm.backoff: 

528 print(f"Backoff: {fsm.backoff}s") 

529 if fsm.maintain: 

530 print("Maintain: yes (restarts after completion)") 

531 if fsm.context: 

532 print(f"Context variables: {', '.join(fsm.context.keys())}") 

533 if fsm.scope: 

534 print(f"Scope: {', '.join(fsm.scope)}") 

535 print(f"Source: {path}") 

536 

537 # --- States & Transitions --- 

538 print() 

539 print("States:") 

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

541 terminal_marker = " [TERMINAL]" if state.terminal else "" 

542 initial_marker = " [INITIAL]" if name == fsm.initial else "" 

543 print(f" [{name}]{initial_marker}{terminal_marker}") 

544 if state.action: 

545 action_display = state.action[:70] + "..." if len(state.action) > 70 else state.action 

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

547 if state.action_type: 

548 print(f" type: {state.action_type}") 

549 if state.evaluate: 

550 print(f" evaluate: {state.evaluate.type}") 

551 if state.on_success: 

552 print(f" on_success \u2500\u2500\u2192 {state.on_success}") 

553 if state.on_failure: 

554 print(f" on_failure \u2500\u2500\u2192 {state.on_failure}") 

555 if state.on_error: 

556 print(f" on_error \u2500\u2500\u2192 {state.on_error}") 

557 if state.next: 

558 print(f" next \u2500\u2500\u2192 {state.next}") 

559 if state.route: 

560 print(" route:") 

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

562 print(f" {verdict} \u2500\u2500\u2192 {target}") 

563 if state.route.default: 

564 print(f" _ \u2500\u2500\u2192 {state.route.default}") 

565 

566 # --- ASCII FSM Diagram --- 

567 print() 

568 print("Diagram:") 

569 diagram = _render_fsm_diagram(fsm) 

570 if diagram: 

571 print(diagram) 

572 

573 # --- Run Command --- 

574 print() 

575 print("Run command:") 

576 print(f" ll-loop run {loop_name}") 

577 

578 return 0