Coverage for little_loops / cli / loop / layout.py: 91%

984 statements  

« prev     ^ index     » next       coverage.py v7.12.0, created at 2026-04-02 13:03 -0500

1"""FSM diagram layout engine. 

2 

3Implements adaptive layout for FSM diagrams using a Sugiyama-inspired 

4layered graph drawing approach. Supports topology detection, vertical 

5linear chains, side-by-side branching, and margin back-edge rendering. 

6 

7Extracted from info.py and extended with adaptive layout capabilities. 

8""" 

9 

10from __future__ import annotations 

11 

12import re 

13from collections import deque 

14 

15from wcwidth import wcswidth as _wcswidth 

16from wcwidth import wcwidth as _wcwidth 

17 

18from little_loops.cli.output import colorize, terminal_width 

19from little_loops.fsm.schema import FSMLoop, StateConfig 

20 

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

22 

23# --------------------------------------------------------------------------- 

24# Edge label colorization 

25# --------------------------------------------------------------------------- 

26 

27_EDGE_LABEL_COLORS: dict[str, str] = { 

28 "yes": "32", 

29 "no": "38;5;208", 

30 "error": "31", 

31 "partial": "33", 

32 "next": "2", 

33 "_": "2", 

34 "blocked": "31", 

35 "retry_exhausted": "38;5;208", 

36} 

37 

38 

39def _colorize_label(label: str) -> str: 

40 """Colorize a (possibly compound) edge label like 'no/error'.""" 

41 parts = label.split("/") 

42 code = "" 

43 for part in parts: 

44 if part in ("no", "error"): 

45 code = _EDGE_LABEL_COLORS["no"] 

46 break 

47 if part == "partial" and not code: 

48 code = _EDGE_LABEL_COLORS["partial"] 

49 elif part == "yes" and not code: 

50 code = _EDGE_LABEL_COLORS["yes"] 

51 elif part in ("next", "_") and not code: 

52 code = _EDGE_LABEL_COLORS["next"] 

53 return colorize(label, code) if code else label 

54 

55 

56def _edge_line_color(label: str) -> str: 

57 """Return the ANSI SGR code to use for connector characters of an edge. 

58 

59 Applies the same priority cascade as ``_colorize_label`` so that line 

60 characters (│, ─, ▼, ▶, corners) match the semantic color of their label. 

61 Returns an empty string when no color applies (callers treat this as "no-op"). 

62 """ 

63 parts = label.split("/") 

64 code = "" 

65 for part in parts: 

66 if part in ("no", "error", "blocked", "retry_exhausted"): 

67 return _EDGE_LABEL_COLORS.get(part, "31") 

68 if part == "partial" and not code: 

69 code = _EDGE_LABEL_COLORS["partial"] 

70 elif part == "yes" and not code: 

71 code = _EDGE_LABEL_COLORS["yes"] 

72 elif part in ("next", "_") and not code: 

73 code = _EDGE_LABEL_COLORS["next"] 

74 return code 

75 

76 

77def _colorize_diagram_labels(diagram: str, colors: dict[str, str] | None = None) -> str: 

78 """Apply ANSI color to known edge labels in a rendered diagram string. 

79 

80 Labels are colorized only when bounded by box-drawing or whitespace chars 

81 to avoid coloring partial matches inside state names. 

82 

83 Args: 

84 colors: Optional label→SGR-code mapping; falls back to _EDGE_LABEL_COLORS if None. 

85 """ 

86 label_colors = colors if colors is not None else _EDGE_LABEL_COLORS 

87 for label, code in label_colors.items(): 

88 colored = colorize(label, code) 

89 diagram = re.sub( 

90 r"(?<=[─ │▶\n])" + re.escape(label) + r"(?=[─ │▶\n])", 

91 colored, 

92 diagram, 

93 ) 

94 return diagram 

95 

96 

97# --------------------------------------------------------------------------- 

98# State box badge definitions 

99# --------------------------------------------------------------------------- 

100 

101_ACTION_TYPE_BADGES: dict[str, str] = { 

102 "prompt": "\u2726", # ✦ 

103 "slash_command": "/\u2501\u25ba", # /━► 

104 "shell": "\u276f_", # ❯_ 

105 "mcp_tool": "\u26a1", # ⚡ 

106} 

107 

108_SUB_LOOP_BADGE = "\u21b3\u27f3" # ↳⟳ 

109_ROUTE_BADGE = "\u2443" # ⑃ 

110 

111 

112def _badge_display_width(badge: str) -> int: 

113 """Compute terminal display width of a badge string using wcwidth.""" 

114 w = _wcswidth(badge) 

115 return w if w >= 0 else len(badge) 

116 

117 

118def _get_state_badge(state: StateConfig | None, badges: dict[str, str] | None = None) -> str: 

119 """Return the unicode badge string for a state, or '' if none.""" 

120 if state is None: 

121 return "" 

122 effective = {**_ACTION_TYPE_BADGES, **(badges or {})} 

123 sub_loop_badge = (badges or {}).get("sub_loop", _SUB_LOOP_BADGE) 

124 route_badge = (badges or {}).get("route", _ROUTE_BADGE) 

125 if state.loop is not None: 

126 return sub_loop_badge 

127 if state.action_type: 

128 return effective.get(state.action_type, f"[{state.action_type}]") 

129 if state.action: 

130 return effective["shell"] 

131 if state.route is not None: 

132 return route_badge 

133 return "" 

134 

135 

136# --------------------------------------------------------------------------- 

137# Box content helpers for multi-row diagram boxes 

138# --------------------------------------------------------------------------- 

139 

140 

141def _box_inner_lines( 

142 state: StateConfig | None, 

143 display_label: str, 

144 verbose: bool, 

145 inner_width: int, 

146) -> list[str]: 

147 """Return interior lines for a state box (between top and bottom borders). 

148 

149 The first line is always ``display_label`` + type badge (if any). 

150 Subsequent lines are action content lines. All lines fit within 

151 ``inner_width`` characters (content is truncated or wrapped accordingly). 

152 """ 

153 # Badge is now rendered in the top-right corner by _draw_box; name row is label only 

154 name_line = display_label[:inner_width] 

155 

156 lines: list[str] = [name_line] 

157 

158 # Action lines 

159 if state and state.action: 

160 action_src = [ln.rstrip() for ln in state.action.strip().splitlines()] 

161 if verbose: 

162 for src in action_src: 

163 if not src: 

164 continue 

165 # Wrap long lines to inner_width 

166 while len(src) > inner_width: 

167 lines.append(src[:inner_width]) 

168 src = src[inner_width:] 

169 if src: 

170 lines.append(src) 

171 else: 

172 # Show first non-empty line, truncated 

173 first = next((ln for ln in action_src if ln), "") 

174 if len(first) > inner_width: 

175 first = first[: inner_width - 1] + "\u2026" 

176 if first: 

177 lines.append(first) 

178 

179 return lines 

180 

181 

182# --------------------------------------------------------------------------- 

183# Topology detection 

184# --------------------------------------------------------------------------- 

185 

186 

187def _collect_edges(fsm: FSMLoop) -> list[tuple[str, str, str]]: 

188 """Collect all (source, target, label) edges from an FSM.""" 

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

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

191 if state.on_yes: 

192 edges.append((name, state.on_yes, "yes")) 

193 if state.on_no: 

194 edges.append((name, state.on_no, "no")) 

195 if state.on_error: 

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

197 if state.on_partial: 

198 edges.append((name, state.on_partial, "partial")) 

199 if state.on_blocked: 

200 edges.append((name, state.on_blocked, "blocked")) 

201 if state.on_retry_exhausted: 

202 edges.append((name, state.on_retry_exhausted, "retry_exhausted")) 

203 if state.next: 

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

205 if state.route: 

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

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

208 if state.route.default: 

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

210 return edges 

211 

212 

213def _bfs_order(initial: str, edges: list[tuple[str, str, str]]) -> tuple[list[str], dict[str, int]]: 

214 """BFS from initial state. Returns (order, depth_map).""" 

215 order: list[str] = [] 

216 depth: dict[str, int] = {initial: 0} 

217 queue: deque[str] = deque([initial]) 

218 while queue: 

219 node = queue.popleft() 

220 order.append(node) 

221 for src, dst, _ in edges: 

222 if src == node and dst not in depth: 

223 depth[dst] = depth[node] + 1 

224 queue.append(dst) 

225 return order, depth 

226 

227 

228def _trace_main_path( 

229 fsm: FSMLoop, edges: list[tuple[str, str, str]] 

230) -> tuple[list[str], set[tuple[str, str]]]: 

231 """Trace the main (happy) path through the FSM.""" 

232 visited: set[str] = set() 

233 main_path: list[str] = [] 

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

235 current = fsm.initial 

236 while current and current not in visited: 

237 visited.add(current) 

238 main_path.append(current) 

239 st = fsm.states.get(current) 

240 if not st or st.terminal: 

241 break 

242 nxt: str = st.on_yes or st.next or "" 

243 if not nxt and st.route: 

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

245 if nxt: 

246 main_edge_set.add((current, nxt)) 

247 current = nxt 

248 else: 

249 break 

250 return main_path, main_edge_set 

251 

252 

253def _classify_edges( 

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

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

256 bfs_order: list[str], 

257) -> tuple[list[tuple[str, str, str]], list[tuple[str, str, str]]]: 

258 """Split non-main edges into branches and back_edges.""" 

259 main_consumed: set[int] = set() 

260 for src, dst in main_edge_set: 

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

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

263 main_consumed.add(i) 

264 break 

265 

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

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

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

269 if i in main_consumed: 

270 continue 

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

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

273 if dst == src or dst_pos < src_pos: 

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

275 else: 

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

277 return branches, back_edges 

278 

279 

280class TopologyDetector: 

281 """Classify FSM graph topology for layout strategy selection.""" 

282 

283 def __init__( 

284 self, 

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

286 main_path: list[str], 

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

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

289 ) -> None: 

290 self._edges = edges 

291 self._main_path = main_path 

292 self._branches = branches 

293 self._back_edges = back_edges 

294 

295 def classify(self) -> str: 

296 """Return 'linear', 'tree', or 'general'. 

297 

298 Linear: main path only, no non-self branches, only self-loop back-edges. 

299 Tree: branches exist but no fan-in (every non-initial state has ≤1 incoming). 

300 General: everything else (full Sugiyama needed). 

301 """ 

302 non_self_branches = [b for b in self._branches if b[0] != b[1]] 

303 non_self_back = [b for b in self._back_edges if b[0] != b[1]] 

304 

305 if not non_self_branches and not non_self_back: 

306 return "linear" 

307 

308 # Check for fan-in: any state with >1 incoming forward edge 

309 in_count: dict[str, int] = {} 

310 for _, dst, _ in self._edges: 

311 # Only count forward edges (not back-edges) 

312 in_count[dst] = in_count.get(dst, 0) + 1 

313 

314 if not non_self_back and all(v <= 1 for v in in_count.values()): 

315 return "tree" 

316 

317 return "general" 

318 

319 

320# --------------------------------------------------------------------------- 

321# Sugiyama layout pipeline 

322# --------------------------------------------------------------------------- 

323 

324 

325class LayerAssigner: 

326 """Assign nodes to layers using longest-path + width constraint.""" 

327 

328 def __init__( 

329 self, 

330 all_states: list[str], 

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

332 back_edge_set: set[tuple[str, str]], 

333 initial: str, 

334 max_width: int = 4, 

335 ) -> None: 

336 self._all_states = all_states 

337 self._edges = edges 

338 self._back_edge_set = back_edge_set 

339 self._initial = initial 

340 self._max_width = max_width 

341 

342 def assign(self) -> list[list[str]]: 

343 """Return list of layers, each a list of state names (top to bottom).""" 

344 # Build adjacency (forward edges only) 

345 forward: dict[str, list[str]] = {s: [] for s in self._all_states} 

346 reverse: dict[str, list[str]] = {s: [] for s in self._all_states} 

347 seen_edges: set[tuple[str, str]] = set() 

348 for src, dst, _ in self._edges: 

349 if (src, dst) in self._back_edge_set or src == dst: 

350 continue 

351 if src in forward and dst in forward and (src, dst) not in seen_edges: 

352 forward[src].append(dst) 

353 reverse[dst].append(src) 

354 seen_edges.add((src, dst)) 

355 

356 # Longest-path layer assignment (topological order) 

357 layer_of: dict[str, int] = {} 

358 

359 # Kahn's algorithm for topological order 

360 in_degree = {s: len(reverse[s]) for s in self._all_states} 

361 queue: deque[str] = deque() 

362 for s in self._all_states: 

363 if in_degree[s] == 0: 

364 queue.append(s) 

365 

366 topo_order: list[str] = [] 

367 while queue: 

368 node = queue.popleft() 

369 topo_order.append(node) 

370 for dst in forward[node]: 

371 in_degree[dst] -= 1 

372 if in_degree[dst] == 0: 

373 queue.append(dst) 

374 

375 # Handle nodes not reached by topo sort (cycles in forward graph) 

376 for s in self._all_states: 

377 if s not in set(topo_order): 

378 topo_order.append(s) 

379 

380 # Assign layers: longest path from root 

381 for node in topo_order: 

382 if not reverse[node]: 

383 layer_of[node] = 0 

384 else: 

385 layer_of[node] = max( 

386 (layer_of.get(p, 0) + 1 for p in reverse[node]), 

387 default=0, 

388 ) 

389 

390 # Ensure initial state is at layer 0 

391 if self._initial in layer_of and layer_of[self._initial] != 0: 

392 offset = layer_of[self._initial] 

393 for s in layer_of: 

394 layer_of[s] -= offset 

395 

396 # Build layers list 

397 max_layer = max(layer_of.values(), default=0) 

398 layers: list[list[str]] = [[] for _ in range(max_layer + 1)] 

399 for s in self._all_states: 

400 layer = layer_of.get(s, 0) 

401 layers[layer].append(s) 

402 

403 # Width constraint: if any layer exceeds max_width, split 

404 if self._max_width > 0: 

405 new_layers: list[list[str]] = [] 

406 for grp in layers: 

407 remaining = list(grp) 

408 while len(remaining) > self._max_width: 

409 new_layers.append(remaining[: self._max_width]) 

410 remaining = remaining[self._max_width :] 

411 if remaining: 

412 new_layers.append(remaining) 

413 layers = new_layers 

414 

415 return layers 

416 

417 

418class CrossingMinimizer: 

419 """Minimize edge crossings using barycenter heuristic.""" 

420 

421 def __init__( 

422 self, 

423 layers: list[list[str]], 

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

425 back_edge_set: set[tuple[str, str]], 

426 ) -> None: 

427 self._layers = layers 

428 self._edges = edges 

429 self._back_edge_set = back_edge_set 

430 

431 def minimize(self) -> list[list[str]]: 

432 """Return reordered layers with reduced crossings.""" 

433 # Build position lookup 

434 layer_of: dict[str, int] = {} 

435 for i, layer in enumerate(self._layers): 

436 for s in layer: 

437 layer_of[s] = i 

438 

439 # Forward adjacency (non-back, non-self) 

440 adj_down: dict[str, list[str]] = {} 

441 adj_up: dict[str, list[str]] = {} 

442 for src, dst, _ in self._edges: 

443 if (src, dst) in self._back_edge_set or src == dst: 

444 continue 

445 if src in layer_of and dst in layer_of: 

446 adj_down.setdefault(src, []).append(dst) 

447 adj_up.setdefault(dst, []).append(src) 

448 

449 layers = [list(layer) for layer in self._layers] 

450 

451 # 3 sweeps: down, up, down 

452 for sweep in range(3): 

453 if sweep % 2 == 0: 

454 # Top-down sweep 

455 for i in range(1, len(layers)): 

456 pos_above = {s: j for j, s in enumerate(layers[i - 1])} 

457 bary: dict[str, float] = {} 

458 for s in layers[i]: 

459 parents = [p for p in adj_up.get(s, []) if p in pos_above] 

460 if parents: 

461 bary[s] = sum(pos_above[p] for p in parents) / len(parents) 

462 else: 

463 bary[s] = float(layers[i].index(s)) 

464 layers[i].sort(key=lambda s: bary.get(s, 0)) 

465 else: 

466 # Bottom-up sweep 

467 for i in range(len(layers) - 2, -1, -1): 

468 pos_below = {s: j for j, s in enumerate(layers[i + 1])} 

469 bary_up: dict[str, float] = {} 

470 for s in layers[i]: 

471 children = [c for c in adj_down.get(s, []) if c in pos_below] 

472 if children: 

473 bary_up[s] = sum(pos_below[c] for c in children) / len(children) 

474 else: 

475 bary_up[s] = float(layers[i].index(s)) 

476 layers[i].sort(key=lambda s: bary_up.get(s, 0)) 

477 

478 return layers 

479 

480 

481# --------------------------------------------------------------------------- 

482# Rendering helpers 

483# --------------------------------------------------------------------------- 

484 

485 

486def _compute_display_labels( 

487 all_states: list[str], 

488 initial: str, 

489 terminal_states: set[str], 

490) -> dict[str, str]: 

491 """Compute display labels with → prefix and ◉ suffix.""" 

492 display_label: dict[str, str] = {} 

493 for s in all_states: 

494 label = s 

495 if s == initial: 

496 label = "\u2192 " + label 

497 if s in terminal_states: 

498 label = label + " \u25c9" 

499 display_label[s] = label 

500 return display_label 

501 

502 

503def _compute_box_sizes( 

504 all_states: list[str], 

505 display_label: dict[str, str], 

506 fsm_states: dict[str, StateConfig] | None, 

507 verbose: bool, 

508 max_box_inner: int, 

509 badges: dict[str, str] | None = None, 

510) -> tuple[dict[str, list[str]], dict[str, int], dict[str, int], dict[str, str]]: 

511 """Compute box content, widths, and heights for all states. 

512 

513 Returns (box_inner, box_width, box_height, box_badge). 

514 """ 

515 box_inner: dict[str, list[str]] = {} 

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

517 box_badge: dict[str, str] = {} 

518 

519 for s in all_states: 

520 state_obj = fsm_states.get(s) if fsm_states else None 

521 

522 badge = _get_state_badge(state_obj, badges) 

523 badge_w = _badge_display_width(badge) if badge else 0 

524 box_badge[s] = badge 

525 

526 # Width must fit: name label on content row, badge on top border (with one space 

527 # of padding on each side: " badge ") 

528 base_w = max(len(display_label[s]), badge_w + 2 if badge_w else 0) 

529 

530 inner_w = base_w 

531 if state_obj and state_obj.action and max_box_inner > 0: 

532 action_lines = state_obj.action.strip().splitlines() 

533 if verbose: 

534 max_action_w = max( 

535 (len(ln.rstrip()) for ln in action_lines if ln.rstrip()), default=0 

536 ) 

537 inner_w = max(base_w, min(max_action_w, max_box_inner)) 

538 else: 

539 first_action = next((ln.rstrip() for ln in action_lines if ln.rstrip()), "") 

540 inner_w = max(base_w, min(len(first_action), max_box_inner)) 

541 

542 content = _box_inner_lines(state_obj, display_label[s], verbose, inner_w) 

543 actual_w = max(len(ln) for ln in content) 

544 inner_w = max(inner_w, actual_w) 

545 box_inner[s] = content 

546 box_width[s] = inner_w + 4 # "│ " + content + " │" 

547 

548 box_height: dict[str, int] = {s: len(box_inner[s]) + 2 for s in all_states} 

549 return box_inner, box_width, box_height, box_badge 

550 

551 

552def _draw_box( 

553 grid: list[list[str]], 

554 row: int, 

555 col: int, 

556 width: int, 

557 height: int, 

558 content: list[str], 

559 is_highlighted: bool, 

560 highlight_color: str, 

561 badge: str = "", 

562) -> None: 

563 """Draw a state box onto a character grid at (row, col). 

564 

565 If *badge* is provided it is placed right-aligned in the top border row with 

566 one space of padding on each side (``─ badge ┐``), colorized via ``_bc()``. 

567 """ 

568 total_width = len(grid[0]) if grid else 0 

569 

570 def _bc(ch: str) -> str: 

571 return colorize(ch, highlight_color) if is_highlighted else ch 

572 

573 # Top border: ┌ ─ ─ … ─ ┐ 

574 if col < total_width: 

575 grid[row][col] = _bc("\u250c") 

576 for j in range(1, width - 1): 

577 if col + j < total_width: 

578 grid[row][col + j] = _bc("\u2500") 

579 if col + width - 1 < total_width: 

580 grid[row][col + width - 1] = _bc("\u2510") 

581 

582 # Overlay badge in top-right corner with one space of padding on each side: " badge ┐" 

583 if badge: 

584 badge_w = _badge_display_width(badge) 

585 # Trailing space between badge end and ┐ 

586 trail_pos = col + width - 2 

587 if col + 1 <= trail_pos < col + width - 1 and trail_pos < total_width: 

588 grid[row][trail_pos] = _bc(" ") 

589 # Leading space before badge 

590 lead_pos = col + width - badge_w - 3 

591 if col + 1 <= lead_pos < col + width - 1 and lead_pos < total_width: 

592 grid[row][lead_pos] = _bc(" ") 

593 # Badge characters (shifted left by 1 compared to no-padding placement) 

594 pos = col + width - 1 - badge_w - 1 

595 for ch in badge: 

596 ch_w = _wcwidth(ch) 

597 if ch_w < 1: 

598 ch_w = 1 

599 if col + 1 <= pos < col + width - 1 and pos < total_width: 

600 grid[row][pos] = _bc(ch) 

601 if ch_w == 2 and pos + 1 < col + width - 1 and pos + 1 < total_width: 

602 grid[row][pos + 1] = "" 

603 pos += ch_w 

604 

605 # Content rows 

606 for i, line in enumerate(content): 

607 r = row + i + 1 

608 if r >= len(grid): 

609 break 

610 if col < total_width: 

611 grid[r][col] = _bc("\u2502") 

612 if col + width - 1 < total_width: 

613 grid[r][col + width - 1] = _bc("\u2502") 

614 if is_highlighted and i == 0: 

615 colored_line = colorize(line, f"{highlight_color};1") 

616 if col + 2 < total_width: 

617 grid[r][col + 2] = colored_line 

618 for j in range(1, len(line)): 

619 if col + 2 + j < col + width - 1: 

620 grid[r][col + 2 + j] = "" 

621 elif i == 0: 

622 bold_line = colorize(line, "1") 

623 if col + 2 < total_width: 

624 grid[r][col + 2] = bold_line 

625 for j in range(1, len(line)): 

626 if col + 2 + j < col + width - 1: 

627 grid[r][col + 2 + j] = "" 

628 else: 

629 for j, ch in enumerate(line): 

630 if col + 2 + j < col + width - 1: 

631 grid[r][col + 2 + j] = ch 

632 

633 # Padding rows between content and bottom border 

634 for i in range(len(content) + 1, height - 1): 

635 r = row + i 

636 if r >= len(grid): 

637 break 

638 if col < total_width: 

639 grid[r][col] = _bc("\u2502") 

640 if col + width - 1 < total_width: 

641 grid[r][col + width - 1] = _bc("\u2502") 

642 

643 # Bottom border 

644 brow = row + height - 1 

645 if brow < len(grid): 

646 if col < total_width: 

647 grid[brow][col] = _bc("\u2514") 

648 for j in range(1, width - 1): 

649 if col + j < total_width: 

650 grid[brow][col + j] = _bc("\u2500") 

651 if col + width - 1 < total_width: 

652 grid[brow][col + width - 1] = _bc("\u2518") 

653 

654 

655# --------------------------------------------------------------------------- 

656# Layered (vertical) renderer 

657# --------------------------------------------------------------------------- 

658 

659 

660def _render_layered_diagram( 

661 layers: list[list[str]], 

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

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

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

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

666 initial: str, 

667 terminal_states: set[str] | None, 

668 fsm_states: dict[str, StateConfig] | None, 

669 verbose: bool, 

670 highlight_state: str | None, 

671 highlight_color: str, 

672 edge_label_colors: dict[str, str] | None = None, 

673 badges: dict[str, str] | None = None, 

674) -> str: 

675 """Render FSM using layered (Sugiyama-style) vertical layout.""" 

676 terminal_states = terminal_states or set() 

677 fsm_states = fsm_states or {} 

678 tw = terminal_width() 

679 

680 # Flatten layers to get all states 

681 all_states = [s for layer in layers for s in layer] 

682 if not all_states: 

683 return "" 

684 

685 display_label = _compute_display_labels(all_states, initial, terminal_states) 

686 

687 # Compute max_box_inner based on widest layer 

688 max_layer_size = max(len(layer) for layer in layers) 

689 if verbose: 

690 max_box_inner = max(20, min(60, (tw - 4) // max(1, max_layer_size) - 6)) 

691 else: 

692 max_box_inner = max(20, min(40, (tw - 4) // max(1, max_layer_size) - 6)) 

693 

694 box_inner, box_width, box_height, box_badge = _compute_box_sizes( 

695 all_states, display_label, fsm_states, verbose, max_box_inner, badges 

696 ) 

697 

698 # Post-hoc layer merge: re-merge adjacent single-state layers that were 

699 # over-split by the conservative max_width_per_layer estimate. Only merge 

700 # when both layers receive an edge from the same source state (indicating 

701 # they were originally one layer split by width constraint). 

702 available_w = tw - 20 # conservative content-area estimate 

703 gap_between = 6 

704 # Build edge target sets: for each state, which earlier states point to it 

705 _incoming: dict[str, set[str]] = {s: set() for layer in layers for s in layer} 

706 for src, dst, _ in edges: 

707 if src != dst and dst in _incoming: 

708 _incoming[dst].add(src) 

709 merged = True 

710 while merged: 

711 merged = False 

712 i = 0 

713 while i < len(layers) - 1: 

714 la, lb = layers[i], layers[i + 1] 

715 # Only merge single-state layers that share an incoming source 

716 if len(la) == 1 and len(lb) == 1: 

717 sources_a = _incoming.get(la[0], set()) 

718 sources_b = _incoming.get(lb[0], set()) 

719 shared_source = sources_a & sources_b 

720 else: 

721 shared_source = set() 

722 combined_w = ( 

723 sum(box_width[s] for s in la) 

724 + gap_between * (len(la) - 1) 

725 + gap_between 

726 + sum(box_width[s] for s in lb) 

727 + gap_between * (len(lb) - 1) 

728 ) 

729 if shared_source and combined_w <= available_w and len(la) + len(lb) <= 4: 

730 layers[i] = la + lb 

731 layers.pop(i + 1) 

732 merged = True 

733 else: 

734 i += 1 

735 

736 # Collect ALL non-self-loop forward edge labels (main + branches + same-depth back-edges) 

737 # Multiple edges between the same pair are combined as "label1/label2" 

738 forward_edge_labels: dict[tuple[str, str], str] = {} 

739 for src, dst, lbl in edges: 

740 if src == dst: 

741 continue 

742 if (src, dst) in main_edge_set or (src, dst, lbl) in branches: 

743 if (src, dst) in forward_edge_labels: 

744 forward_edge_labels[(src, dst)] += "/" + lbl 

745 else: 

746 forward_edge_labels[(src, dst)] = lbl 

747 

748 # True back-edges: only those going to an earlier layer (computed after layer assignment) 

749 # Will be finalized below after col positions are computed 

750 # Combine same-pair back-edges into single entries with merged labels (e.g. "error/fail") 

751 back_edge_labels_initial: dict[tuple[str, str], str] = {} 

752 for s, d, lbl in back_edges: 

753 if s != d: 

754 if (s, d) in back_edge_labels_initial: 

755 back_edge_labels_initial[(s, d)] += "/" + lbl 

756 else: 

757 back_edge_labels_initial[(s, d)] = lbl 

758 

759 # Pre-compute layer positions to detect main-path cycle edges early. 

760 # This ensures back_edge_margin accounts for ALL backward-pointing edges 

761 # (including main-path cycles like commit → initial_state) before column 

762 # positions are computed. 

763 prelim_layer_of: dict[str, int] = {} 

764 for li, layer in enumerate(layers): 

765 for s in layer: 

766 prelim_layer_of[s] = li 

767 

768 # Include main-path/branch edges that point backward in margin estimate 

769 all_back_labels: dict[tuple[str, str], str] = dict(back_edge_labels_initial) 

770 for (src, dst), lbl in forward_edge_labels.items(): 

771 src_layer = prelim_layer_of.get(src, -1) 

772 dst_layer = prelim_layer_of.get(dst, -1) 

773 if dst_layer < src_layer: 

774 if (src, dst) in all_back_labels: 

775 all_back_labels[(src, dst)] += "/" + lbl 

776 else: 

777 all_back_labels[(src, dst)] = lbl 

778 

779 non_self_back_initial = [(s, d, lbl) for (s, d), lbl in all_back_labels.items()] 

780 back_edge_margin = 0 

781 if non_self_back_initial: 

782 max_label_len = max(len(lbl) for _, _, lbl in non_self_back_initial) 

783 n_back_initial = len(non_self_back_initial) 

784 back_edge_margin = max_label_len + max(6, 2 * n_back_initial + 2) 

785 

786 content_left = 2 + back_edge_margin 

787 

788 # Self-loops per state 

789 self_loops: dict[str, list[str]] = {} 

790 for src, dst, lbl in back_edges: 

791 if src == dst: 

792 self_loops.setdefault(src, []).append(lbl) 

793 

794 # --- Compute a common center column for alignment --- 

795 # For layers with single boxes, we want vertical alignment through a 

796 # shared center column. Use the widest single-state layer's center. 

797 max_single_w = max((box_width[layer[0]] for layer in layers if len(layer) == 1), default=0) 

798 # The common center is at content_left + max_single_w // 2 

799 common_center = content_left + max_single_w // 2 

800 

801 # Compute column positions per layer 

802 col_start: dict[str, int] = {} 

803 col_center: dict[str, int] = {} 

804 layer_of: dict[str, int] = {} 

805 

806 for li, layer in enumerate(layers): 

807 if len(layer) == 1: 

808 # Single-state layer: center-align to common center 

809 sname = layer[0] 

810 col_start[sname] = common_center - box_width[sname] // 2 

811 col_center[sname] = common_center 

812 layer_of[sname] = li 

813 else: 

814 # Multi-state layer: place side-by-side, centered around common_center 

815 gap_between = 6 

816 total_layer_w = sum(box_width[s] for s in layer) + gap_between * (len(layer) - 1) 

817 x = common_center - total_layer_w // 2 

818 x = max(content_left, x) 

819 for i, sname in enumerate(layer): 

820 col_start[sname] = x 

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

822 layer_of[sname] = li 

823 if i < len(layer) - 1: 

824 next_s = layer[i + 1] 

825 # Check for edge labels in both directions between adjacent states 

826 label_fwd = forward_edge_labels.get((sname, next_s), "") 

827 label_rev = forward_edge_labels.get((next_s, sname), "") 

828 max_label = max(len(label_fwd), len(label_rev)) 

829 gap = max(gap_between, max_label + 6) if max_label > 0 else gap_between 

830 x += box_width[sname] + gap 

831 else: 

832 x += box_width[sname] 

833 

834 # Reclassify back-edges based on actual layer positions 

835 # Only edges going to an earlier layer are true margin back-edges 

836 # Combine same-pair edges into merged labels (e.g. "error/fail") 

837 back_edge_labels_reclass: dict[tuple[str, str], str] = {} 

838 same_layer_edges: list[tuple[str, str, str]] = [] 

839 for src, dst, lbl in back_edges: 

840 if src == dst: 

841 continue 

842 src_layer = layer_of.get(src, -1) 

843 dst_layer = layer_of.get(dst, -1) 

844 if dst_layer < src_layer: 

845 if (src, dst) in back_edge_labels_reclass: 

846 back_edge_labels_reclass[(src, dst)] += "/" + lbl 

847 else: 

848 back_edge_labels_reclass[(src, dst)] = lbl 

849 elif dst_layer == src_layer: 

850 same_layer_edges.append((src, dst, lbl)) 

851 else: # dst_layer > src_layer: actually forward edge 

852 if (src, dst) in forward_edge_labels: 

853 forward_edge_labels[(src, dst)] += "/" + lbl 

854 else: 

855 forward_edge_labels[(src, dst)] = lbl 

856 

857 # Also reclassify main/branch edges in forward_edge_labels that point backward 

858 # after layer assignment (e.g. main-path cycle edges like commit → initial_state) 

859 backward_in_fwd: list[tuple[str, str]] = [] 

860 for (src, dst), lbl in forward_edge_labels.items(): 

861 src_layer = layer_of.get(src, -1) 

862 dst_layer = layer_of.get(dst, -1) 

863 if dst_layer < src_layer: 

864 backward_in_fwd.append((src, dst)) 

865 if (src, dst) in back_edge_labels_reclass: 

866 back_edge_labels_reclass[(src, dst)] += "/" + lbl 

867 else: 

868 back_edge_labels_reclass[(src, dst)] = lbl 

869 elif dst_layer == src_layer and src != dst: 

870 backward_in_fwd.append((src, dst)) 

871 same_layer_edges.append((src, dst, lbl)) 

872 for key in backward_in_fwd: 

873 del forward_edge_labels[key] 

874 

875 # Add same-layer back-edges to forward_edge_labels so gap calculation accounts for them 

876 for src, dst, lbl in same_layer_edges: 

877 if (src, dst) in forward_edge_labels: 

878 forward_edge_labels[(src, dst)] += "/" + lbl 

879 else: 

880 forward_edge_labels[(src, dst)] = lbl 

881 

882 # Recalculate inter-box gaps for layers with newly discovered same-layer edges 

883 affected_layers: set[int] = set() 

884 for src, dst, _lbl in same_layer_edges: 

885 sl = layer_of.get(src, -1) 

886 dl = layer_of.get(dst, -1) 

887 if sl >= 0: 

888 affected_layers.add(sl) 

889 if dl >= 0: 

890 affected_layers.add(dl) 

891 for li in affected_layers: 

892 layer = layers[li] 

893 if len(layer) < 2: 

894 continue 

895 gap_between = 6 

896 total_layer_w = sum(box_width[s] for s in layer) 

897 # For non-adjacent same-layer edges the label lands in the gap immediately 

898 # adjacent to the source box (left of src for right-to-left, right of src 

899 # for left-to-right). Collect those requirements so the gap is wide enough. 

900 extra_gap_req: dict[tuple[str, str], int] = {} 

901 for src, dst, lbl in same_layer_edges: 

902 if layer_of.get(src) != li or layer_of.get(dst) != li: 

903 continue 

904 try: 

905 si, di = layer.index(src), layer.index(dst) 

906 except ValueError: 

907 continue 

908 if abs(si - di) <= 1: 

909 continue # adjacent — already handled by forward_edge_labels 

910 if si > di: 

911 key = (layer[si - 1], src) # gap to the left of src 

912 else: 

913 key = (src, layer[si + 1]) # gap to the right of src 

914 extra_gap_req[key] = max(extra_gap_req.get(key, 0), len(lbl)) 

915 # Recalculate gaps with label-aware spacing 

916 gaps: list[int] = [] 

917 for i in range(len(layer) - 1): 

918 sname, next_s = layer[i], layer[i + 1] 

919 label_fwd = forward_edge_labels.get((sname, next_s), "") 

920 label_rev = forward_edge_labels.get((next_s, sname), "") 

921 max_label = max(len(label_fwd), len(label_rev), extra_gap_req.get((sname, next_s), 0)) 

922 gap = max(gap_between, max_label + 6) if max_label > 0 else gap_between 

923 gaps.append(gap) 

924 total_layer_w += sum(gaps) 

925 x = common_center - total_layer_w // 2 

926 x = max(content_left, x) 

927 for i, sname in enumerate(layer): 

928 col_start[sname] = x 

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

930 if i < len(layer) - 1: 

931 x += box_width[sname] + gaps[i] 

932 else: 

933 x += box_width[sname] 

934 

935 non_self_back = [(s, d, lbl) for (s, d), lbl in back_edge_labels_reclass.items()] 

936 

937 # Recalculate back-edge margin if it changed 

938 if non_self_back: 

939 max_label_len = max(len(lbl) for _, _, lbl in non_self_back) 

940 n_back = len(non_self_back) 

941 actual_margin = max_label_len + max(6, 2 * n_back + 2) 

942 if actual_margin != back_edge_margin: 

943 # Need to recalculate positions (rare case - usually matches) 

944 back_edge_margin = actual_margin 

945 content_left = 2 + back_edge_margin 

946 

947 # Identify forward skip-layer edges (span > 1 layer, not handled by consecutive renderer) 

948 skip_forward_edges: list[tuple[str, str, str]] = [] 

949 for (src, dst), lbl in forward_edge_labels.items(): 

950 src_layer = layer_of.get(src, -1) 

951 dst_layer = layer_of.get(dst, -1) 

952 if dst_layer > src_layer + 1: 

953 skip_forward_edges.append((src, dst, lbl)) 

954 

955 # Pre-compute right margin width for forward skip-layer edges 

956 right_edge_margin = 0 

957 if skip_forward_edges: 

958 max_fwd_label_len = max(len(lbl) for _, _, lbl in skip_forward_edges) 

959 right_edge_margin = max_fwd_label_len + 6 

960 

961 # Compute total width needed 

962 total_content_w = 0 

963 for s in all_states: 

964 right = col_start[s] + box_width[s] 

965 total_content_w = max(total_content_w, right) 

966 total_width = max(total_content_w + right_edge_margin + 4, tw) 

967 

968 # Compute vertical positions with space for self-loops and inter-layer arrows 

969 row_start: dict[str, int] = {} 

970 y = 0 

971 for li, layer in enumerate(layers): 

972 layer_h = max(box_height[s] for s in layer) 

973 for sname in layer: 

974 row_start[sname] = y 

975 y += layer_h 

976 

977 # Add self-loop row if any state in this layer has self-loops 

978 has_self_loop = any(s in self_loops for s in layer) 

979 if has_self_loop: 

980 y += 1 # self-loop marker row 

981 

982 if li < len(layers) - 1: 

983 y += 3 # arrow gap: │, label, ▼ 

984 

985 total_height = y 

986 

987 # Build character grid 

988 grid: list[list[str]] = [[" "] * total_width for _ in range(total_height)] 

989 

990 # Draw boxes 

991 for sname in all_states: 

992 is_highlighted = highlight_state is not None and sname == highlight_state 

993 _draw_box( 

994 grid, 

995 row_start[sname], 

996 col_start[sname], 

997 box_width[sname], 

998 box_height[sname], 

999 box_inner[sname], 

1000 is_highlighted, 

1001 highlight_color, 

1002 badge=box_badge[sname], 

1003 ) 

1004 

1005 # Precompute box-occupied (row, col) pairs so connector lines can avoid overwriting box cells 

1006 _box_occ: dict[int, set[int]] = {} 

1007 for _s in all_states: 

1008 for _r in range(row_start[_s], row_start[_s] + box_height[_s]): 

1009 _row_set = _box_occ.setdefault(_r, set()) 

1010 for _c in range(col_start[_s], col_start[_s] + box_width[_s]): 

1011 _row_set.add(_c) 

1012 

1013 # Draw self-loop markers immediately below their boxes 

1014 for sname, labels in self_loops.items(): 

1015 marker = "\u21ba " + ", ".join(labels) 

1016 r = row_start[sname] + box_height[sname] 

1017 if r < total_height: 

1018 cx = col_center[sname] 

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

1020 for j, ch in enumerate(marker): 

1021 if pos + j < total_width: 

1022 grid[r][pos + j] = ch 

1023 

1024 # Draw forward edges between layers (vertical arrows with labels) 

1025 for li in range(len(layers) - 1): 

1026 layer_h = max(box_height[s] for s in layers[li]) 

1027 has_self_loop = any(s in self_loops for s in layers[li]) 

1028 self_loop_offset = 1 if has_self_loop else 0 

1029 

1030 # Arrow area starts after box bottom + self-loop row 

1031 arrow_start_row = row_start[layers[li][0]] + layer_h + self_loop_offset 

1032 arrow_end_row = row_start[layers[li + 1][0]] - 1 

1033 

1034 # Collect all inter-layer edges from this layer to the next 

1035 inter_edges: list[tuple[str, str, str]] = [] 

1036 for src in layers[li]: 

1037 for dst in layers[li + 1]: 

1038 label = forward_edge_labels.get((src, dst)) 

1039 if label is not None: 

1040 inter_edges.append((src, dst, label)) 

1041 

1042 # Draw each edge with its own vertical pipe to the target's center 

1043 for src, dst, label in inter_edges: 

1044 dst_cc = col_center[dst] 

1045 src_left = col_start[src] 

1046 src_right = src_left + box_width[src] 

1047 ec = _edge_line_color(label) # ANSI code for this edge's connector chars 

1048 

1049 def _lc(ch: str, _ec: str = ec) -> str: # noqa: E306 

1050 return colorize(ch, _ec) if _ec else ch 

1051 

1052 # Horizontal connector when pipe is outside source box range 

1053 if dst_cc >= src_right or dst_cc < src_left: 

1054 conn_row = arrow_start_row 

1055 if 0 <= conn_row < total_height: 

1056 if dst_cc >= src_right: 

1057 # Pipe right of source: └───┐ 

1058 src_cc = col_center[src] 

1059 if 0 <= src_cc < total_width and grid[conn_row][src_cc] == " ": 

1060 grid[conn_row][src_cc] = _lc("\u2514") # └ 

1061 start_c = src_cc + 1 

1062 else: 

1063 start_c = src_right 

1064 for c in range(start_c, dst_cc): 

1065 if 0 <= c < total_width: 

1066 grid[conn_row][c] = _lc("\u2500") 

1067 if 0 <= dst_cc < total_width: 

1068 grid[conn_row][dst_cc] = _lc("\u2510") # ┐ 

1069 else: 

1070 # Pipe left of source: ┌───┘ 

1071 src_cc = col_center[src] 

1072 if 0 <= src_cc < total_width and grid[conn_row][src_cc] == " ": 

1073 end_c = src_cc 

1074 grid[conn_row][src_cc] = _lc("\u2518") # ┘ 

1075 else: 

1076 end_c = src_left 

1077 for c in range(dst_cc + 1, end_c): 

1078 if 0 <= c < total_width: 

1079 grid[conn_row][c] = _lc("\u2500") 

1080 if 0 <= dst_cc < total_width: 

1081 grid[conn_row][dst_cc] = _lc("\u250c") # ┌ 

1082 pipe_start = arrow_start_row + 1 

1083 else: 

1084 pipe_start = arrow_start_row 

1085 

1086 # Draw vertical pipe at destination's center column 

1087 for r in range(pipe_start, arrow_end_row): 

1088 if 0 <= dst_cc < total_width and r < total_height: 

1089 grid[r][dst_cc] = _lc("\u2502") 

1090 

1091 # Arrow tip at destination center 

1092 if arrow_end_row < total_height and 0 <= dst_cc < total_width: 

1093 grid[arrow_end_row][dst_cc] = _lc("\u25bc") 

1094 

1095 # Label to the right of the pipe (or left if it would overlap) 

1096 label_row = arrow_start_row 

1097 if label_row < total_height: 

1098 label_start = dst_cc + 2 

1099 for j, ch in enumerate(label): 

1100 if label_start + j < total_width: 

1101 grid[label_row][label_start + j] = ch 

1102 

1103 # Post-pass: connect horizontal gaps for multi-branch sources 

1104 if len(inter_edges) >= 2 and 0 <= arrow_start_row < total_height: 

1105 src_targets: dict[str, list[int]] = {} 

1106 for src, dst, _ in inter_edges: 

1107 if dst in col_center: 

1108 src_targets.setdefault(src, []).append(col_center[dst]) 

1109 for _src, centers in src_targets.items(): 

1110 if len(centers) < 2: 

1111 continue 

1112 left = min(centers) 

1113 right = max(centers) 

1114 for c in range(left + 1, right): 

1115 if 0 <= c < total_width: 

1116 cell = grid[arrow_start_row][c] 

1117 if cell == " ": 

1118 grid[arrow_start_row][c] = "\u2500" # ─ 

1119 elif cell == "\u2502": # │ → ┼ 

1120 grid[arrow_start_row][c] = "\u253c" 

1121 elif cell == "\u2518": # ┘ → ┴ 

1122 grid[arrow_start_row][c] = "\u2534" 

1123 elif cell == "\u2514": # └ → ┴ 

1124 grid[arrow_start_row][c] = "\u2534" 

1125 elif cell == "\u2510": # ┐ → ┬ 

1126 grid[arrow_start_row][c] = "\u252c" 

1127 elif cell == "\u250c": # ┌ → ┬ 

1128 grid[arrow_start_row][c] = "\u252c" 

1129 # Update boundary junction chars where the horizontal bar meets a pipe 

1130 if 0 <= left < total_width and grid[arrow_start_row][left] == "\u2502": # │ → ├ 

1131 grid[arrow_start_row][left] = "\u251c" 

1132 if 0 <= right < total_width and grid[arrow_start_row][right] == "\u2502": # │ → ┤ 

1133 grid[arrow_start_row][right] = "\u2524" 

1134 

1135 # Draw same-layer edges (horizontal arrows between states on same layer) 

1136 # Includes both branches and reclassified back-edges within same layer 

1137 all_same_layer: list[tuple[str, str, str]] = list(same_layer_edges) 

1138 for _li, layer in enumerate(layers): 

1139 for i, src in enumerate(layer): 

1140 for j, dst in enumerate(layer): 

1141 if i == j: 

1142 continue 

1143 label = forward_edge_labels.get((src, dst)) 

1144 if label is not None and (src, dst, label) not in all_same_layer: 

1145 all_same_layer.append((src, dst, label)) 

1146 

1147 for src, dst, label in all_same_layer: 

1148 if src not in col_start or dst not in col_start: 

1149 continue 

1150 name_row = row_start[src] + 1 

1151 src_right = col_start[src] + box_width[src] 

1152 dst_right = col_start[dst] + box_width[dst] 

1153 dst_left = col_start[dst] 

1154 src_left = col_start[src] 

1155 _row_boxes = _box_occ.get(name_row, set()) 

1156 ec = _edge_line_color(label) 

1157 

1158 def _lc(ch: str, _ec: str = ec) -> str: # noqa: E306 

1159 return colorize(ch, _ec) if _ec else ch 

1160 

1161 if dst_left >= src_right: 

1162 # Left to right horizontal arrow: src ──label──▶ dst 

1163 start = src_right 

1164 end = dst_left 

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

1166 available = end - start 

1167 if available < len(edge_text): 

1168 edge_text = edge_text[: max(1, available)] 

1169 left_dashes = max(0, available - len(edge_text)) 

1170 for k in range(left_dashes): 

1171 pos = start + k 

1172 if pos < total_width and name_row < total_height and pos not in _row_boxes: 

1173 grid[name_row][pos] = _lc("\u2500") 

1174 for k, ch in enumerate(edge_text): 

1175 pos = start + left_dashes + k 

1176 if ( 

1177 0 <= pos < end 

1178 and pos < total_width 

1179 and name_row < total_height 

1180 and pos not in _row_boxes 

1181 ): 

1182 grid[name_row][pos] = _lc(ch) 

1183 elif dst_right <= src_left: 

1184 # Right to left: dst is left of src: src → dst drawn as dst ◀──label── src 

1185 start = dst_right 

1186 end = src_left 

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

1188 available = end - start 

1189 if available < len(edge_text): 

1190 edge_text = edge_text[: max(1, available)] 

1191 left_dashes = max(0, available - len(edge_text)) 

1192 for k in range(left_dashes): 

1193 pos = start + k 

1194 if pos < total_width and name_row < total_height and pos not in _row_boxes: 

1195 grid[name_row][pos] = _lc("\u2500") 

1196 for k, ch in enumerate(edge_text): 

1197 pos = start + left_dashes + k 

1198 if ( 

1199 0 <= pos < end 

1200 and pos < total_width 

1201 and name_row < total_height 

1202 and pos not in _row_boxes 

1203 ): 

1204 grid[name_row][pos] = _lc(ch) 

1205 

1206 # Back-edges: left-margin vertical arrows with labels 

1207 if non_self_back: 

1208 sorted_back = sorted( 

1209 non_self_back, 

1210 key=lambda e: abs(row_start.get(e[0], 0) - row_start.get(e[1], 0)), 

1211 reverse=True, 

1212 ) 

1213 used_cols: list[int] = [] 

1214 # Compute rightmost pipe column so labels go right of ALL pipes 

1215 rightmost_pipe_col = 1 + (len(sorted_back) - 1) * 2 

1216 

1217 for src, dst, label in sorted_back: 

1218 # Source: name row of source box; target: name row of target box 

1219 src_row = row_start.get(src, 0) + 1 # name row, not bottom border 

1220 dst_row = row_start.get(dst, 0) + 1 # name row 

1221 

1222 # Find a free column in the margin 

1223 col = 1 

1224 for uc in sorted(used_cols): 

1225 if uc == col: 

1226 col += 2 

1227 used_cols.append(col) 

1228 

1229 if col >= content_left - 1: 

1230 continue 

1231 

1232 top_row = min(src_row, dst_row) 

1233 bot_row = max(src_row, dst_row) 

1234 ec = _edge_line_color(label) 

1235 

1236 def _lc(ch: str, _ec: str = ec) -> str: # noqa: E306 

1237 return colorize(ch, _ec) if _ec else ch 

1238 

1239 # Draw vertical line in margin (exclude corner rows handled below) 

1240 for r in range(top_row + 1, bot_row): 

1241 if 0 <= r < total_height and col < total_width: 

1242 cell = grid[r][col] 

1243 if cell == "\u2500": # ─ → ┼ (junction, leave uncolored) 

1244 grid[r][col] = "\u253c" 

1245 elif cell == " ": 

1246 grid[r][col] = _lc("\u2502") 

1247 

1248 # Horizontal connector from source box to margin 

1249 # Draw right-to-left, crossing existing pipes with junction chars 

1250 if 0 <= src_row < total_height: 

1251 src_left = col_start.get(src, col + 1) 

1252 _src_row_boxes = _box_occ.get(src_row, set()) 

1253 for c in range(col + 1, src_left): 

1254 if c < total_width and c not in _src_row_boxes: 

1255 cell = grid[src_row][c] 

1256 if cell == " ": 

1257 grid[src_row][c] = _lc("\u2500") # ─ 

1258 elif cell == "\u2502": # │ → ┼ (junction) 

1259 grid[src_row][c] = "\u253c" 

1260 elif cell == "\u2514": # └ → ┴ (junction) 

1261 grid[src_row][c] = "\u2534" 

1262 elif cell == "\u250c": # ┌ → ┬ (junction) 

1263 grid[src_row][c] = "\u252c" 

1264 elif cell == "\u251c": # ├ → ┼ (junction) 

1265 grid[src_row][c] = "\u253c" 

1266 # Leave ─, ▶, box chars unchanged 

1267 

1268 # Horizontal connector from margin to target box 

1269 # Draw right-to-left, crossing existing pipes with junction chars 

1270 dst_left = col_start.get(dst, col + 1) 

1271 if 0 <= dst_row < total_height: 

1272 _dst_row_boxes = _box_occ.get(dst_row, set()) 

1273 for c in range(col + 1, dst_left): 

1274 if c < total_width and c not in _dst_row_boxes: 

1275 cell = grid[dst_row][c] 

1276 if cell == " ": 

1277 grid[dst_row][c] = _lc("\u2500") # ─ 

1278 elif cell == "\u2502": # │ → ┼ (junction) 

1279 grid[dst_row][c] = "\u253c" 

1280 elif cell == "\u2514": # └ → ┴ (junction) 

1281 grid[dst_row][c] = "\u2534" 

1282 elif cell == "\u250c": # ┌ → ┬ (junction) 

1283 grid[dst_row][c] = "\u252c" 

1284 elif cell == "\u251c": # ├ → ┼ (junction) 

1285 grid[dst_row][c] = "\u253c" 

1286 

1287 # Corner characters at pipe-to-horizontal turn points 

1288 for row in (src_row, dst_row): 

1289 if 0 <= row < total_height and col < total_width: 

1290 existing = grid[row][col] 

1291 if row == bot_row: 

1292 # Pipe ends, turns right: └; if horizontal already crosses here: ┴ 

1293 grid[row][col] = "\u2534" if existing == "\u2500" else _lc("\u2514") 

1294 else: # row == top_row 

1295 # Pipe starts going down, turns right: ┌; if horizontal already crosses here: ┬ 

1296 grid[row][col] = "\u252c" if existing == "\u2500" else _lc("\u250c") 

1297 

1298 # Arrow tip at target: place ▶ at end of horizontal connector (entering box from left) 

1299 if 0 <= dst_row < total_height and dst_left - 1 > col and dst_left - 1 < total_width: 

1300 grid[dst_row][dst_left - 1] = _lc("\u25b6") 

1301 

1302 # Label on the margin line (right of ALL pipes, not just this one) 

1303 label_row_pos = (top_row + bot_row) // 2 

1304 if 0 <= label_row_pos < total_height: 

1305 label_start = rightmost_pipe_col + 2 

1306 for j, ch in enumerate(label): 

1307 if label_start + j < content_left - 1 and label_start + j < total_width: 

1308 grid[label_row_pos][label_start + j] = _lc(ch) 

1309 

1310 # Forward skip-layer edges: right-margin vertical arrows with labels 

1311 # Symmetric to the left-margin back-edge renderer above 

1312 if skip_forward_edges: 

1313 sorted_fwd_skip = sorted( 

1314 skip_forward_edges, 

1315 key=lambda e: abs(row_start.get(e[0], 0) - row_start.get(e[1], 0)), 

1316 reverse=True, 

1317 ) 

1318 used_fwd_cols: list[int] = [] 

1319 # Rightmost pipe column (furthest from content) for label placement 

1320 rightmost_fwd_pipe_col = total_content_w + 2 + (len(sorted_fwd_skip) - 1) * 2 

1321 

1322 for src, dst, label in sorted_fwd_skip: 

1323 src_row = row_start.get(src, 0) + 1 # name row 

1324 dst_row = row_start.get(dst, 0) + 1 # name row 

1325 

1326 # Allocate column in right margin (starting from content edge, going right) 

1327 col = total_content_w + 2 

1328 for uc in sorted(used_fwd_cols): 

1329 if uc == col: 

1330 col += 2 

1331 used_fwd_cols.append(col) 

1332 

1333 if col >= total_width: 

1334 continue 

1335 

1336 top_row = min(src_row, dst_row) 

1337 bot_row = max(src_row, dst_row) 

1338 ec = _edge_line_color(label) 

1339 

1340 def _lc(ch: str, _ec: str = ec) -> str: # noqa: E306 

1341 return colorize(ch, _ec) if _ec else ch 

1342 

1343 # Draw vertical line in right margin (exclude corner rows handled below) 

1344 for r in range(top_row + 1, bot_row): 

1345 if 0 <= r < total_height and col < total_width: 

1346 cell = grid[r][col] 

1347 if cell == "\u2500": # ─ → ┼ (junction) 

1348 grid[r][col] = "\u253c" 

1349 elif cell == " ": 

1350 grid[r][col] = _lc("\u2502") 

1351 

1352 # Horizontal connector from source box right side to margin 

1353 # Draw left-to-right, crossing existing pipes with junction chars 

1354 src_right = col_start.get(src, 0) + box_width.get(src, 0) 

1355 _src_row_boxes = _box_occ.get(src_row, set()) 

1356 if 0 <= src_row < total_height: 

1357 for c in range(src_right, col): 

1358 if 0 <= c < total_width and c not in _src_row_boxes: 

1359 cell = grid[src_row][c] 

1360 if cell == " ": 

1361 grid[src_row][c] = _lc("\u2500") # ─ 

1362 elif cell == "\u2502": # │ → ┼ (junction) 

1363 grid[src_row][c] = "\u253c" 

1364 elif cell == "\u2518": # ┘ → ┴ (junction) 

1365 grid[src_row][c] = "\u2534" 

1366 elif cell == "\u2510": # ┐ → ┬ (junction) 

1367 grid[src_row][c] = "\u252c" 

1368 elif cell == "\u2524": # ┤ → ┼ (junction) 

1369 grid[src_row][c] = "\u253c" 

1370 # Leave ─, ◀, box chars unchanged 

1371 

1372 # Horizontal connector from margin to destination box right side 

1373 dst_right = col_start.get(dst, 0) + box_width.get(dst, 0) 

1374 _dst_row_boxes = _box_occ.get(dst_row, set()) 

1375 if 0 <= dst_row < total_height: 

1376 for c in range(dst_right, col): 

1377 if 0 <= c < total_width and c not in _dst_row_boxes: 

1378 cell = grid[dst_row][c] 

1379 if cell == " ": 

1380 grid[dst_row][c] = _lc("\u2500") # ─ 

1381 elif cell == "\u2502": # │ → ┼ (junction) 

1382 grid[dst_row][c] = "\u253c" 

1383 elif cell == "\u2518": # ┘ → ┴ (junction) 

1384 grid[dst_row][c] = "\u2534" 

1385 elif cell == "\u2510": # ┐ → ┬ (junction) 

1386 grid[dst_row][c] = "\u252c" 

1387 elif cell == "\u2524": # ┤ → ┼ (junction) 

1388 grid[dst_row][c] = "\u253c" 

1389 

1390 # Corner characters at pipe-to-horizontal turn points 

1391 for row in (src_row, dst_row): 

1392 if 0 <= row < total_height and col < total_width: 

1393 existing = grid[row][col] 

1394 if row == bot_row: 

1395 # Pipe ends, turns left: ┘; if horizontal crosses: ┤ 

1396 grid[row][col] = "\u2524" if existing == "\u2500" else _lc("\u2518") 

1397 else: # row == top_row 

1398 # Pipe starts going down, turns left: ┐; if horizontal crosses: ┤ 

1399 grid[row][col] = "\u2524" if existing == "\u2500" else _lc("\u2510") 

1400 

1401 # Arrow tip at target: ◀ entering box from right side 

1402 if 0 <= dst_row < total_height and dst_right < col and dst_right < total_width: 

1403 grid[dst_row][dst_right] = _lc("\u25c0") 

1404 

1405 # Label on the margin line (right of ALL pipes, mirroring left-margin approach) 

1406 label_row_pos = (top_row + bot_row) // 2 

1407 if 0 <= label_row_pos < total_height: 

1408 label_start = rightmost_fwd_pipe_col + 2 

1409 for j, ch in enumerate(label): 

1410 if label_start + j < total_width: 

1411 grid[label_row_pos][label_start + j] = _lc(ch) 

1412 

1413 # Convert grid to string 

1414 lines = ["".join(row).rstrip() for row in grid] 

1415 

1416 # Remove trailing empty lines 

1417 while lines and not lines[-1].strip(): 

1418 lines.pop() 

1419 

1420 # Center diagram 

1421 max_line_len = max((len(_ANSI_ESCAPE_RE.sub("", ln)) for ln in lines), default=0) 

1422 diagram_indent = max(0, (tw - max_line_len) // 2) 

1423 if diagram_indent > 0: 

1424 lines = [" " * diagram_indent + ln if ln.strip() else ln for ln in lines] 

1425 

1426 return _colorize_diagram_labels("\n".join(lines), edge_label_colors) 

1427 

1428 

1429# --------------------------------------------------------------------------- 

1430# FSM diagram renderer (main entry point) 

1431# --------------------------------------------------------------------------- 

1432 

1433 

1434def _render_fsm_diagram( 

1435 fsm: FSMLoop, 

1436 verbose: bool = False, 

1437 highlight_state: str | None = None, 

1438 highlight_color: str = "32", 

1439 edge_label_colors: dict[str, str] | None = None, 

1440 badges: dict[str, str] | None = None, 

1441) -> str: 

1442 """Render an adaptive text diagram of the FSM graph. 

1443 

1444 Detects FSM topology and selects appropriate layout: 

1445 - Linear chains: vertical top-to-bottom 

1446 - Branching/cyclic: layered Sugiyama-style 

1447 

1448 Args: 

1449 fsm: The FSM loop to render. 

1450 verbose: If True, show expanded action content in boxes. 

1451 highlight_state: If provided, render this state's box with the highlight color. 

1452 highlight_color: ANSI SGR code for the highlighted state (default: green). 

1453 edge_label_colors: Optional label→SGR-code mapping for transition labels. 

1454 Falls back to hardcoded defaults when None. 

1455 badges: Optional glyph-key→string mapping for state type badges. 

1456 Falls back to hardcoded defaults when None. 

1457 """ 

1458 edges = _collect_edges(fsm) 

1459 bfs_order_list, bfs_depth = _bfs_order(fsm.initial, edges) 

1460 main_path, main_edge_set = _trace_main_path(fsm, edges) 

1461 branches, back_edges = _classify_edges(edges, main_edge_set, bfs_order_list) 

1462 

1463 terminal_states = {name for name, state in fsm.states.items() if state.terminal} 

1464 

1465 # Collect all states 

1466 all_states = list(main_path) 

1467 for src, dst, _ in branches: 

1468 for s in (src, dst): 

1469 if s not in all_states: 

1470 all_states.append(s) 

1471 

1472 # Topology detection 

1473 detector = TopologyDetector(edges, main_path, branches, back_edges) 

1474 topology = detector.classify() 

1475 

1476 # Build back-edge set for layout pipeline 

1477 back_edge_set: set[tuple[str, str]] = set() 

1478 for src, dst, _ in back_edges: 

1479 if src != dst: 

1480 back_edge_set.add((src, dst)) 

1481 

1482 tw = terminal_width() 

1483 

1484 if topology == "linear" and len(all_states) <= 1: 

1485 # Single state or empty — use simple horizontal 

1486 return _render_horizontal_simple( 

1487 main_path, 

1488 edges, 

1489 main_edge_set, 

1490 branches, 

1491 back_edges, 

1492 bfs_order_list, 

1493 fsm.initial, 

1494 terminal_states, 

1495 fsm.states, 

1496 verbose, 

1497 highlight_state, 

1498 highlight_color, 

1499 edge_label_colors, 

1500 badges, 

1501 ) 

1502 

1503 # Compute max node width to determine width constraint 

1504 # Quick estimate: widest state name or badge + padding 

1505 max_node_w = 30 # reasonable default 

1506 for s in all_states: 

1507 st = fsm.states.get(s) 

1508 badge = _get_state_badge(st, badges) 

1509 badge_w = _badge_display_width(badge) if badge else 0 

1510 label = s 

1511 if s == fsm.initial: 

1512 label = "\u2192 " + label 

1513 if s in terminal_states: 

1514 label = label + " \u25c9" 

1515 w = max(len(label), badge_w) 

1516 max_node_w = max(max_node_w, w + 4 + 4) # inner + borders + padding 

1517 

1518 max_width_per_layer = max(1, (tw - 10) // (max_node_w + 4)) 

1519 

1520 # Layer assignment 

1521 assigner = LayerAssigner(all_states, edges, back_edge_set, fsm.initial, max_width_per_layer) 

1522 layers = assigner.assign() 

1523 

1524 # Crossing minimization 

1525 minimizer = CrossingMinimizer(layers, edges, back_edge_set) 

1526 layers = minimizer.minimize() 

1527 

1528 return _render_layered_diagram( 

1529 layers, 

1530 edges, 

1531 main_edge_set, 

1532 branches, 

1533 back_edges, 

1534 fsm.initial, 

1535 terminal_states, 

1536 fsm.states, 

1537 verbose, 

1538 highlight_state, 

1539 highlight_color, 

1540 edge_label_colors, 

1541 badges, 

1542 ) 

1543 

1544 

1545def _render_horizontal_simple( 

1546 main_path: list[str], 

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

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

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

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

1551 bfs_order: list[str], 

1552 initial: str, 

1553 terminal_states: set[str], 

1554 fsm_states: dict[str, StateConfig], 

1555 verbose: bool, 

1556 highlight_state: str | None, 

1557 highlight_color: str, 

1558 edge_label_colors: dict[str, str] | None = None, 

1559 badges: dict[str, str] | None = None, 

1560) -> str: 

1561 """Simple horizontal rendering for single-state or very simple FSMs.""" 

1562 if not main_path: 

1563 return "" 

1564 

1565 all_states = list(main_path) 

1566 display_label = _compute_display_labels(all_states, initial, terminal_states) 

1567 

1568 tw = terminal_width() 

1569 num_main = max(1, len(main_path)) 

1570 if verbose and fsm_states and main_path: 

1571 max_box_inner = max(20, min(60, (tw - 4) // num_main - 6)) 

1572 else: 

1573 max_box_inner = max(20, min(40, (tw - 4) // num_main - 6)) 

1574 

1575 box_inner, box_width, box_height, box_badge = _compute_box_sizes( 

1576 all_states, display_label, fsm_states, verbose, max_box_inner, badges 

1577 ) 

1578 

1579 main_height = max((box_height[s] for s in main_path), default=3) 

1580 total_width = tw 

1581 

1582 # Column positions 

1583 col_start: dict[str, int] = {} 

1584 col_center: dict[str, int] = {} 

1585 x = 2 

1586 for i, sname in enumerate(main_path): 

1587 col_start[sname] = x 

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

1589 x += box_width[sname] 

1590 if i < len(main_path) - 1: 

1591 x += 4 

1592 

1593 rows: list[list[str]] = [[" "] * total_width for _ in range(main_height)] 

1594 

1595 for sname in main_path: 

1596 is_highlighted = highlight_state is not None and sname == highlight_state 

1597 _draw_box( 

1598 rows, 

1599 0, 

1600 col_start[sname], 

1601 box_width[sname], 

1602 main_height, 

1603 box_inner[sname], 

1604 is_highlighted, 

1605 highlight_color, 

1606 badge=box_badge[sname], 

1607 ) 

1608 

1609 # Self-loops 

1610 self_loops_list = [(s, d, lbl) for s, d, lbl in back_edges if s == d] 

1611 lines = ["".join(row).rstrip() for row in rows] 

1612 if self_loops_list: 

1613 self_labels: dict[str, list[str]] = {} 

1614 for src, _, label in self_loops_list: 

1615 self_labels.setdefault(src, []).append(label) 

1616 for sname, labels in self_labels.items(): 

1617 marker = "\u21ba " + ", ".join(labels) 

1618 self_row = [" "] * total_width 

1619 cx = col_center.get(sname, 0) 

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

1621 for j, ch in enumerate(marker): 

1622 if pos + j < total_width: 

1623 self_row[pos + j] = ch 

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

1625 

1626 diagram_indent = max(0, (tw - (x + 4)) // 2) 

1627 if diagram_indent > 0: 

1628 lines = [" " * diagram_indent + ln if ln.strip() else ln for ln in lines] 

1629 

1630 return _colorize_diagram_labels("\n".join(lines), edge_label_colors)