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

905 statements  

« prev     ^ index     » next       coverage.py v7.12.0, created at 2026-03-14 23:20 -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 little_loops.cli.output import colorize, terminal_width 

16from little_loops.fsm.schema import FSMLoop, StateConfig 

17 

18# --------------------------------------------------------------------------- 

19# Edge label colorization 

20# --------------------------------------------------------------------------- 

21 

22_EDGE_LABEL_COLORS: dict[str, str] = { 

23 "yes": "32", 

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

25 "error": "31", 

26 "partial": "33", 

27 "next": "2", 

28 "_": "2", 

29} 

30 

31 

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

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

34 parts = label.split("/") 

35 code = "" 

36 for part in parts: 

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

38 code = _EDGE_LABEL_COLORS["no"] 

39 break 

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

41 code = _EDGE_LABEL_COLORS["partial"] 

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

43 code = _EDGE_LABEL_COLORS["yes"] 

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

45 code = _EDGE_LABEL_COLORS["next"] 

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

47 

48 

49def _colorize_diagram_labels(diagram: str) -> str: 

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

51 

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

53 to avoid coloring partial matches inside state names. 

54 """ 

55 for label, code in _EDGE_LABEL_COLORS.items(): 

56 colored = colorize(label, code) 

57 diagram = re.sub( 

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

59 colored, 

60 diagram, 

61 ) 

62 return diagram 

63 

64 

65# --------------------------------------------------------------------------- 

66# Box content helpers for multi-row diagram boxes 

67# --------------------------------------------------------------------------- 

68 

69 

70def _box_inner_lines( 

71 state: StateConfig | None, 

72 display_label: str, 

73 verbose: bool, 

74 inner_width: int, 

75) -> list[str]: 

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

77 

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

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

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

81 """ 

82 # Determine type badge 

83 badge = "" 

84 if state and state.action_type: 

85 badge = f"[{state.action_type}]" 

86 elif state and state.action: 

87 badge = "[shell]" 

88 

89 # Name + badge on first line 

90 if badge: 

91 candidate = f"{display_label} {badge}" 

92 if len(candidate) <= inner_width: 

93 name_line = candidate 

94 else: 

95 # Fit badge at the expense of name truncation 

96 avail = inner_width - len(badge) - 2 

97 name_line = ( 

98 (display_label[:avail] + " " + badge) if avail > 0 else candidate[:inner_width] 

99 ) 

100 else: 

101 name_line = display_label[:inner_width] 

102 

103 lines: list[str] = [name_line] 

104 

105 # Action lines 

106 if state and state.action: 

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

108 if verbose: 

109 for src in action_src: 

110 if not src: 

111 continue 

112 # Wrap long lines to inner_width 

113 while len(src) > inner_width: 

114 lines.append(src[:inner_width]) 

115 src = src[inner_width:] 

116 if src: 

117 lines.append(src) 

118 else: 

119 # Show first non-empty line, truncated 

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

121 if len(first) > inner_width: 

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

123 if first: 

124 lines.append(first) 

125 

126 return lines 

127 

128 

129# --------------------------------------------------------------------------- 

130# Topology detection 

131# --------------------------------------------------------------------------- 

132 

133 

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

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

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

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

138 if state.on_yes: 

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

140 if state.on_no: 

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

142 if state.on_error: 

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

144 if state.on_partial: 

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

146 if state.next: 

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

148 if state.route: 

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

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

151 if state.route.default: 

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

153 return edges 

154 

155 

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

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

158 order: list[str] = [] 

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

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

161 while queue: 

162 node = queue.popleft() 

163 order.append(node) 

164 for src, dst, _ in edges: 

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

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

167 queue.append(dst) 

168 return order, depth 

169 

170 

171def _trace_main_path( 

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

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

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

175 visited: set[str] = set() 

176 main_path: list[str] = [] 

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

178 current = fsm.initial 

179 while current and current not in visited: 

180 visited.add(current) 

181 main_path.append(current) 

182 st = fsm.states.get(current) 

183 if not st or st.terminal: 

184 break 

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

186 if not nxt and st.route: 

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

188 if nxt: 

189 main_edge_set.add((current, nxt)) 

190 current = nxt 

191 else: 

192 break 

193 return main_path, main_edge_set 

194 

195 

196def _classify_edges( 

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

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

199 bfs_order: list[str], 

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

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

202 main_consumed: set[int] = set() 

203 for src, dst in main_edge_set: 

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

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

206 main_consumed.add(i) 

207 break 

208 

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

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

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

212 if i in main_consumed: 

213 continue 

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

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

216 if dst == src or dst_pos < src_pos: 

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

218 else: 

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

220 return branches, back_edges 

221 

222 

223class TopologyDetector: 

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

225 

226 def __init__( 

227 self, 

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

229 main_path: list[str], 

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

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

232 ) -> None: 

233 self._edges = edges 

234 self._main_path = main_path 

235 self._branches = branches 

236 self._back_edges = back_edges 

237 

238 def classify(self) -> str: 

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

240 

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

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

243 General: everything else (full Sugiyama needed). 

244 """ 

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

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

247 

248 if not non_self_branches and not non_self_back: 

249 return "linear" 

250 

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

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

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

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

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

256 

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

258 return "tree" 

259 

260 return "general" 

261 

262 

263# --------------------------------------------------------------------------- 

264# Sugiyama layout pipeline 

265# --------------------------------------------------------------------------- 

266 

267 

268class LayerAssigner: 

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

270 

271 def __init__( 

272 self, 

273 all_states: list[str], 

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

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

276 initial: str, 

277 max_width: int = 4, 

278 ) -> None: 

279 self._all_states = all_states 

280 self._edges = edges 

281 self._back_edge_set = back_edge_set 

282 self._initial = initial 

283 self._max_width = max_width 

284 

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

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

287 # Build adjacency (forward edges only) 

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

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

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

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

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

293 continue 

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

295 forward[src].append(dst) 

296 reverse[dst].append(src) 

297 seen_edges.add((src, dst)) 

298 

299 # Longest-path layer assignment (topological order) 

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

301 

302 # Kahn's algorithm for topological order 

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

304 queue: deque[str] = deque() 

305 for s in self._all_states: 

306 if in_degree[s] == 0: 

307 queue.append(s) 

308 

309 topo_order: list[str] = [] 

310 while queue: 

311 node = queue.popleft() 

312 topo_order.append(node) 

313 for dst in forward[node]: 

314 in_degree[dst] -= 1 

315 if in_degree[dst] == 0: 

316 queue.append(dst) 

317 

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

319 for s in self._all_states: 

320 if s not in set(topo_order): 

321 topo_order.append(s) 

322 

323 # Assign layers: longest path from root 

324 for node in topo_order: 

325 if not reverse[node]: 

326 layer_of[node] = 0 

327 else: 

328 layer_of[node] = max( 

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

330 default=0, 

331 ) 

332 

333 # Ensure initial state is at layer 0 

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

335 offset = layer_of[self._initial] 

336 for s in layer_of: 

337 layer_of[s] -= offset 

338 

339 # Build layers list 

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

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

342 for s in self._all_states: 

343 layer = layer_of.get(s, 0) 

344 layers[layer].append(s) 

345 

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

347 if self._max_width > 0: 

348 new_layers: list[list[str]] = [] 

349 for grp in layers: 

350 remaining = list(grp) 

351 while len(remaining) > self._max_width: 

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

353 remaining = remaining[self._max_width :] 

354 if remaining: 

355 new_layers.append(remaining) 

356 layers = new_layers 

357 

358 return layers 

359 

360 

361class CrossingMinimizer: 

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

363 

364 def __init__( 

365 self, 

366 layers: list[list[str]], 

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

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

369 ) -> None: 

370 self._layers = layers 

371 self._edges = edges 

372 self._back_edge_set = back_edge_set 

373 

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

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

376 # Build position lookup 

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

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

379 for s in layer: 

380 layer_of[s] = i 

381 

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

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

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

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

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

387 continue 

388 if src in layer_of and dst in layer_of: 

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

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

391 

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

393 

394 # 3 sweeps: down, up, down 

395 for sweep in range(3): 

396 if sweep % 2 == 0: 

397 # Top-down sweep 

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

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

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

401 for s in layers[i]: 

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

403 if parents: 

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

405 else: 

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

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

408 else: 

409 # Bottom-up sweep 

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

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

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

413 for s in layers[i]: 

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

415 if children: 

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

417 else: 

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

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

420 

421 return layers 

422 

423 

424# --------------------------------------------------------------------------- 

425# Rendering helpers 

426# --------------------------------------------------------------------------- 

427 

428 

429def _compute_display_labels( 

430 all_states: list[str], 

431 initial: str, 

432 terminal_states: set[str], 

433) -> dict[str, str]: 

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

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

436 for s in all_states: 

437 label = s 

438 if s == initial: 

439 label = "\u2192 " + label 

440 if s in terminal_states: 

441 label = label + " \u25c9" 

442 display_label[s] = label 

443 return display_label 

444 

445 

446def _compute_box_sizes( 

447 all_states: list[str], 

448 display_label: dict[str, str], 

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

450 verbose: bool, 

451 max_box_inner: int, 

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

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

454 

455 Returns (box_inner, box_width, box_height). 

456 """ 

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

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

459 

460 for s in all_states: 

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

462 

463 badge = "" 

464 if state_obj and state_obj.action_type: 

465 badge = f"[{state_obj.action_type}]" 

466 elif state_obj and state_obj.action: 

467 badge = "[shell]" 

468 

469 base_w = len(f"{display_label[s]} {badge}") if badge else len(display_label[s]) 

470 base_w = max(base_w, len(display_label[s])) 

471 

472 inner_w = base_w 

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

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

475 if verbose: 

476 max_action_w = max( 

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

478 ) 

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

480 else: 

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

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

483 

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

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

486 inner_w = max(inner_w, actual_w) 

487 box_inner[s] = content 

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

489 

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

491 return box_inner, box_width, box_height 

492 

493 

494def _draw_box( 

495 grid: list[list[str]], 

496 row: int, 

497 col: int, 

498 width: int, 

499 height: int, 

500 content: list[str], 

501 is_highlighted: bool, 

502 highlight_color: str, 

503) -> None: 

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

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

506 

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

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

509 

510 # Top border 

511 if col < total_width: 

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

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

514 if col + j < total_width: 

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

516 if col + width - 1 < total_width: 

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

518 

519 # Content rows 

520 for i, line in enumerate(content): 

521 r = row + i + 1 

522 if r >= len(grid): 

523 break 

524 if col < total_width: 

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

526 if col + width - 1 < total_width: 

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

528 if is_highlighted and i == 0: 

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

530 if col + 2 < total_width: 

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

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

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

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

535 else: 

536 for j, ch in enumerate(line): 

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

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

539 

540 # Padding rows between content and bottom border 

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

542 r = row + i 

543 if r >= len(grid): 

544 break 

545 if col < total_width: 

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

547 if col + width - 1 < total_width: 

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

549 

550 # Bottom border 

551 brow = row + height - 1 

552 if brow < len(grid): 

553 if col < total_width: 

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

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

556 if col + j < total_width: 

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

558 if col + width - 1 < total_width: 

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

560 

561 

562# --------------------------------------------------------------------------- 

563# Layered (vertical) renderer 

564# --------------------------------------------------------------------------- 

565 

566 

567def _render_layered_diagram( 

568 layers: list[list[str]], 

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

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

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

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

573 initial: str, 

574 terminal_states: set[str] | None, 

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

576 verbose: bool, 

577 highlight_state: str | None, 

578 highlight_color: str, 

579) -> str: 

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

581 terminal_states = terminal_states or set() 

582 fsm_states = fsm_states or {} 

583 tw = terminal_width() 

584 

585 # Flatten layers to get all states 

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

587 if not all_states: 

588 return "" 

589 

590 display_label = _compute_display_labels(all_states, initial, terminal_states) 

591 

592 # Compute max_box_inner based on widest layer 

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

594 if verbose: 

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

596 else: 

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

598 

599 box_inner, box_width, box_height = _compute_box_sizes( 

600 all_states, display_label, fsm_states, verbose, max_box_inner 

601 ) 

602 

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

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

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

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

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

608 gap_between = 6 

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

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

611 for src, dst, _ in edges: 

612 if src != dst and dst in _incoming: 

613 _incoming[dst].add(src) 

614 merged = True 

615 while merged: 

616 merged = False 

617 i = 0 

618 while i < len(layers) - 1: 

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

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

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

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

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

624 shared_source = sources_a & sources_b 

625 else: 

626 shared_source = set() 

627 combined_w = ( 

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

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

630 + gap_between 

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

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

633 ) 

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

635 layers[i] = la + lb 

636 layers.pop(i + 1) 

637 merged = True 

638 else: 

639 i += 1 

640 

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

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

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

644 for src, dst, lbl in edges: 

645 if src == dst: 

646 continue 

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

648 if (src, dst) in forward_edge_labels: 

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

650 else: 

651 forward_edge_labels[(src, dst)] = lbl 

652 

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

654 # Will be finalized below after col positions are computed 

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

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

657 for s, d, lbl in back_edges: 

658 if s != d: 

659 if (s, d) in back_edge_labels_initial: 

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

661 else: 

662 back_edge_labels_initial[(s, d)] = lbl 

663 

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

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

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

667 # positions are computed. 

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

669 for li, layer in enumerate(layers): 

670 for s in layer: 

671 prelim_layer_of[s] = li 

672 

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

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

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

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

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

678 if dst_layer < src_layer: 

679 if (src, dst) in all_back_labels: 

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

681 else: 

682 all_back_labels[(src, dst)] = lbl 

683 

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

685 back_edge_margin = 0 

686 if non_self_back_initial: 

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

688 back_edge_margin = max_label_len + 6 

689 

690 content_left = 2 + back_edge_margin 

691 

692 # Self-loops per state 

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

694 for src, dst, lbl in back_edges: 

695 if src == dst: 

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

697 

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

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

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

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

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

703 common_center = content_left + max_single_w // 2 

704 

705 # Compute column positions per layer 

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

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

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

709 

710 for li, layer in enumerate(layers): 

711 if len(layer) == 1: 

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

713 sname = layer[0] 

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

715 col_center[sname] = common_center 

716 layer_of[sname] = li 

717 else: 

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

719 gap_between = 6 

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

721 x = common_center - total_layer_w // 2 

722 x = max(content_left, x) 

723 for i, sname in enumerate(layer): 

724 col_start[sname] = x 

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

726 layer_of[sname] = li 

727 if i < len(layer) - 1: 

728 next_s = layer[i + 1] 

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

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

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

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

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

734 x += box_width[sname] + gap 

735 else: 

736 x += box_width[sname] 

737 

738 # Reclassify back-edges based on actual layer positions 

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

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

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

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

743 for src, dst, lbl in back_edges: 

744 if src == dst: 

745 continue 

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

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

748 if dst_layer < src_layer: 

749 if (src, dst) in back_edge_labels_reclass: 

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

751 else: 

752 back_edge_labels_reclass[(src, dst)] = lbl 

753 elif dst_layer == src_layer: 

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

755 else: # dst_layer > src_layer: actually forward edge 

756 if (src, dst) in forward_edge_labels: 

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

758 else: 

759 forward_edge_labels[(src, dst)] = lbl 

760 

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

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

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

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

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

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

767 if dst_layer < src_layer: 

768 backward_in_fwd.append((src, dst)) 

769 if (src, dst) in back_edge_labels_reclass: 

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

771 else: 

772 back_edge_labels_reclass[(src, dst)] = lbl 

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

774 backward_in_fwd.append((src, dst)) 

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

776 for key in backward_in_fwd: 

777 del forward_edge_labels[key] 

778 

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

780 for src, dst, lbl in same_layer_edges: 

781 if (src, dst) in forward_edge_labels: 

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

783 else: 

784 forward_edge_labels[(src, dst)] = lbl 

785 

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

787 affected_layers: set[int] = set() 

788 for src, dst, _lbl in same_layer_edges: 

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

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

791 if sl >= 0: 

792 affected_layers.add(sl) 

793 if dl >= 0: 

794 affected_layers.add(dl) 

795 for li in affected_layers: 

796 layer = layers[li] 

797 if len(layer) < 2: 

798 continue 

799 gap_between = 6 

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

801 # Recalculate gaps with label-aware spacing 

802 gaps: list[int] = [] 

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

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

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

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

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

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

809 gaps.append(gap) 

810 total_layer_w += sum(gaps) 

811 x = common_center - total_layer_w // 2 

812 x = max(content_left, x) 

813 for i, sname in enumerate(layer): 

814 col_start[sname] = x 

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

816 if i < len(layer) - 1: 

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

818 else: 

819 x += box_width[sname] 

820 

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

822 

823 # Recalculate back-edge margin if it changed 

824 if non_self_back: 

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

826 actual_margin = max_label_len + 6 

827 if actual_margin != back_edge_margin: 

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

829 back_edge_margin = actual_margin 

830 content_left = 2 + back_edge_margin 

831 

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

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

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

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

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

837 if dst_layer > src_layer + 1: 

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

839 

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

841 right_edge_margin = 0 

842 if skip_forward_edges: 

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

844 right_edge_margin = max_fwd_label_len + 6 

845 

846 # Compute total width needed 

847 total_content_w = 0 

848 for s in all_states: 

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

850 total_content_w = max(total_content_w, right) 

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

852 

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

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

855 y = 0 

856 for li, layer in enumerate(layers): 

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

858 for sname in layer: 

859 row_start[sname] = y 

860 y += layer_h 

861 

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

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

864 if has_self_loop: 

865 y += 1 # self-loop marker row 

866 

867 if li < len(layers) - 1: 

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

869 

870 total_height = y 

871 

872 # Build character grid 

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

874 

875 # Draw boxes 

876 for sname in all_states: 

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

878 _draw_box( 

879 grid, 

880 row_start[sname], 

881 col_start[sname], 

882 box_width[sname], 

883 box_height[sname], 

884 box_inner[sname], 

885 is_highlighted, 

886 highlight_color, 

887 ) 

888 

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

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

891 for _s in all_states: 

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

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

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

895 _row_set.add(_c) 

896 

897 # Draw self-loop markers immediately below their boxes 

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

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

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

901 if r < total_height: 

902 cx = col_center[sname] 

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

904 for j, ch in enumerate(marker): 

905 if pos + j < total_width: 

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

907 

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

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

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

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

912 self_loop_offset = 1 if has_self_loop else 0 

913 

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

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

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

917 

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

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

920 for src in layers[li]: 

921 for dst in layers[li + 1]: 

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

923 if label is not None: 

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

925 

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

927 for src, dst, label in inter_edges: 

928 dst_cc = col_center[dst] 

929 src_left = col_start[src] 

930 src_right = src_left + box_width[src] 

931 

932 # Horizontal connector when pipe is outside source box range 

933 if dst_cc >= src_right or dst_cc < src_left: 

934 conn_row = arrow_start_row 

935 if 0 <= conn_row < total_height: 

936 if dst_cc >= src_right: 

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

938 src_cc = col_center[src] 

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

940 grid[conn_row][src_cc] = "\u2514" # └ 

941 start_c = src_cc + 1 

942 else: 

943 start_c = src_right 

944 for c in range(start_c, dst_cc): 

945 if 0 <= c < total_width: 

946 grid[conn_row][c] = "\u2500" 

947 if 0 <= dst_cc < total_width: 

948 grid[conn_row][dst_cc] = "\u2510" # ┐ 

949 else: 

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

951 src_cc = col_center[src] 

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

953 end_c = src_cc 

954 grid[conn_row][src_cc] = "\u2518" # ┘ 

955 else: 

956 end_c = src_left 

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

958 if 0 <= c < total_width: 

959 grid[conn_row][c] = "\u2500" 

960 if 0 <= dst_cc < total_width: 

961 grid[conn_row][dst_cc] = "\u250c" # ┌ 

962 pipe_start = arrow_start_row + 1 

963 else: 

964 pipe_start = arrow_start_row 

965 

966 # Draw vertical pipe at destination's center column 

967 for r in range(pipe_start, arrow_end_row): 

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

969 grid[r][dst_cc] = "\u2502" 

970 

971 # Arrow tip at destination center 

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

973 grid[arrow_end_row][dst_cc] = "\u25bc" 

974 

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

976 label_row = arrow_start_row 

977 if label_row < total_height: 

978 label_start = dst_cc + 2 

979 for j, ch in enumerate(label): 

980 if label_start + j < total_width: 

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

982 

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

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

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

986 for src, dst, _ in inter_edges: 

987 if dst in col_center: 

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

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

990 if len(centers) < 2: 

991 continue 

992 left = min(centers) 

993 right = max(centers) 

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

995 if 0 <= c < total_width: 

996 cell = grid[arrow_start_row][c] 

997 if cell == " ": 

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1014 

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

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

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

1018 for _li, layer in enumerate(layers): 

1019 for i, src in enumerate(layer): 

1020 for j, dst in enumerate(layer): 

1021 if i == j: 

1022 continue 

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

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

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

1026 

1027 for src, dst, label in all_same_layer: 

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

1029 continue 

1030 name_row = row_start[src] + 1 

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

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

1033 dst_left = col_start[dst] 

1034 src_left = col_start[src] 

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

1036 if dst_left >= src_right: 

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

1038 start = src_right 

1039 end = dst_left 

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

1041 available = end - start 

1042 if available < len(edge_text): 

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

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

1045 for k in range(left_dashes): 

1046 pos = start + k 

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

1048 grid[name_row][pos] = "\u2500" 

1049 for k, ch in enumerate(edge_text): 

1050 pos = start + left_dashes + k 

1051 if ( 

1052 0 <= pos < end 

1053 and pos < total_width 

1054 and name_row < total_height 

1055 and pos not in _row_boxes 

1056 ): 

1057 grid[name_row][pos] = ch 

1058 elif dst_right <= src_left: 

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

1060 start = dst_right 

1061 end = src_left 

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

1063 available = end - start 

1064 if available < len(edge_text): 

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

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

1067 for k in range(left_dashes): 

1068 pos = start + k 

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

1070 grid[name_row][pos] = "\u2500" 

1071 for k, ch in enumerate(edge_text): 

1072 pos = start + left_dashes + k 

1073 if ( 

1074 0 <= pos < end 

1075 and pos < total_width 

1076 and name_row < total_height 

1077 and pos not in _row_boxes 

1078 ): 

1079 grid[name_row][pos] = ch 

1080 

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

1082 if non_self_back: 

1083 sorted_back = sorted( 

1084 non_self_back, 

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

1086 reverse=True, 

1087 ) 

1088 used_cols: list[int] = [] 

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

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

1091 

1092 for src, dst, label in sorted_back: 

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

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

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

1096 

1097 # Find a free column in the margin 

1098 col = 1 

1099 for uc in sorted(used_cols): 

1100 if uc == col: 

1101 col += 2 

1102 used_cols.append(col) 

1103 

1104 if col >= content_left - 1: 

1105 continue 

1106 

1107 top_row = min(src_row, dst_row) 

1108 bot_row = max(src_row, dst_row) 

1109 

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

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

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

1113 cell = grid[r][col] 

1114 if cell == "\u2500": # ─ → ┼ 

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

1116 elif cell == " ": 

1117 grid[r][col] = "\u2502" 

1118 

1119 # Horizontal connector from source box to margin 

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

1121 if 0 <= src_row < total_height: 

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

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

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

1125 if c < total_width and c not in _src_row_boxes: 

1126 cell = grid[src_row][c] 

1127 if cell == " ": 

1128 grid[src_row][c] = "\u2500" # ─ 

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

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

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

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

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

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

1135 elif cell == "\u251c": # ├ → ┼ 

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

1137 # Leave ─, ▶, box chars unchanged 

1138 

1139 # Horizontal connector from margin to target box 

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

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

1142 if 0 <= dst_row < total_height: 

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

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

1145 if c < total_width and c not in _dst_row_boxes: 

1146 cell = grid[dst_row][c] 

1147 if cell == " ": 

1148 grid[dst_row][c] = "\u2500" # ─ 

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

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

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

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

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

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

1155 elif cell == "\u251c": # ├ → ┼ 

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

1157 

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

1159 for row in (src_row, dst_row): 

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

1161 existing = grid[row][col] 

1162 if row == bot_row: 

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

1164 grid[row][col] = "\u2534" if existing == "\u2500" else "\u2514" 

1165 else: # row == top_row 

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

1167 grid[row][col] = "\u252c" if existing == "\u2500" else "\u250c" 

1168 

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

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

1171 grid[dst_row][dst_left - 1] = "\u25b6" 

1172 

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

1174 label_row_pos = (top_row + bot_row) // 2 

1175 if 0 <= label_row_pos < total_height: 

1176 label_start = rightmost_pipe_col + 2 

1177 for j, ch in enumerate(label): 

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

1179 grid[label_row_pos][label_start + j] = ch 

1180 

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

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

1183 if skip_forward_edges: 

1184 sorted_fwd_skip = sorted( 

1185 skip_forward_edges, 

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

1187 reverse=True, 

1188 ) 

1189 used_fwd_cols: list[int] = [] 

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

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

1192 

1193 for src, dst, label in sorted_fwd_skip: 

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

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

1196 

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

1198 col = total_content_w + 2 

1199 for uc in sorted(used_fwd_cols): 

1200 if uc == col: 

1201 col += 2 

1202 used_fwd_cols.append(col) 

1203 

1204 if col >= total_width: 

1205 continue 

1206 

1207 top_row = min(src_row, dst_row) 

1208 bot_row = max(src_row, dst_row) 

1209 

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

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

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

1213 cell = grid[r][col] 

1214 if cell == "\u2500": # ─ → ┼ 

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

1216 elif cell == " ": 

1217 grid[r][col] = "\u2502" 

1218 

1219 # Horizontal connector from source box right side to margin 

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

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

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

1223 if 0 <= src_row < total_height: 

1224 for c in range(src_right, col): 

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

1226 cell = grid[src_row][c] 

1227 if cell == " ": 

1228 grid[src_row][c] = "\u2500" # ─ 

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

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

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

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

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

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

1235 elif cell == "\u2524": # ┤ → ┼ 

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

1237 # Leave ─, ◀, box chars unchanged 

1238 

1239 # Horizontal connector from margin to destination box right side 

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

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

1242 if 0 <= dst_row < total_height: 

1243 for c in range(dst_right, col): 

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

1245 cell = grid[dst_row][c] 

1246 if cell == " ": 

1247 grid[dst_row][c] = "\u2500" # ─ 

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

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

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

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

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

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

1254 elif cell == "\u2524": # ┤ → ┼ 

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

1256 

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

1258 for row in (src_row, dst_row): 

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

1260 existing = grid[row][col] 

1261 if row == bot_row: 

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

1263 grid[row][col] = "\u2524" if existing == "\u2500" else "\u2518" 

1264 else: # row == top_row 

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

1266 grid[row][col] = "\u2524" if existing == "\u2500" else "\u2510" 

1267 

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

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

1270 grid[dst_row][dst_right] = "\u25c0" 

1271 

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

1273 label_row_pos = (top_row + bot_row) // 2 

1274 if 0 <= label_row_pos < total_height: 

1275 label_start = rightmost_fwd_pipe_col + 2 

1276 for j, ch in enumerate(label): 

1277 if label_start + j < total_width: 

1278 grid[label_row_pos][label_start + j] = ch 

1279 

1280 # Convert grid to string 

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

1282 

1283 # Remove trailing empty lines 

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

1285 lines.pop() 

1286 

1287 # Center diagram 

1288 max_line_len = max((len(ln) for ln in lines), default=0) 

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

1290 if diagram_indent > 0: 

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

1292 

1293 return _colorize_diagram_labels("\n".join(lines)) 

1294 

1295 

1296# --------------------------------------------------------------------------- 

1297# FSM diagram renderer (main entry point) 

1298# --------------------------------------------------------------------------- 

1299 

1300 

1301def _render_fsm_diagram( 

1302 fsm: FSMLoop, 

1303 verbose: bool = False, 

1304 highlight_state: str | None = None, 

1305 highlight_color: str = "32", 

1306) -> str: 

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

1308 

1309 Detects FSM topology and selects appropriate layout: 

1310 - Linear chains: vertical top-to-bottom 

1311 - Branching/cyclic: layered Sugiyama-style 

1312 

1313 Args: 

1314 fsm: The FSM loop to render. 

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

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

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

1318 """ 

1319 edges = _collect_edges(fsm) 

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

1321 main_path, main_edge_set = _trace_main_path(fsm, edges) 

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

1323 

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

1325 

1326 # Collect all states 

1327 all_states = list(main_path) 

1328 for src, dst, _ in branches: 

1329 for s in (src, dst): 

1330 if s not in all_states: 

1331 all_states.append(s) 

1332 

1333 # Topology detection 

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

1335 topology = detector.classify() 

1336 

1337 # Build back-edge set for layout pipeline 

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

1339 for src, dst, _ in back_edges: 

1340 if src != dst: 

1341 back_edge_set.add((src, dst)) 

1342 

1343 tw = terminal_width() 

1344 

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

1346 # Single state or empty — use simple horizontal 

1347 return _render_horizontal_simple( 

1348 main_path, 

1349 edges, 

1350 main_edge_set, 

1351 branches, 

1352 back_edges, 

1353 bfs_order_list, 

1354 fsm.initial, 

1355 terminal_states, 

1356 fsm.states, 

1357 verbose, 

1358 highlight_state, 

1359 highlight_color, 

1360 ) 

1361 

1362 # Compute max node width to determine width constraint 

1363 # Quick estimate: widest state name + badge + padding 

1364 max_node_w = 30 # reasonable default 

1365 for s in all_states: 

1366 st = fsm.states.get(s) 

1367 badge = "" 

1368 if st and st.action_type: 

1369 badge = f"[{st.action_type}]" 

1370 elif st and st.action: 

1371 badge = "[shell]" 

1372 label = s 

1373 if s == fsm.initial: 

1374 label = "\u2192 " + label 

1375 if s in terminal_states: 

1376 label = label + " \u25c9" 

1377 w = len(f"{label} {badge}") if badge else len(label) 

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

1379 

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

1381 

1382 # Layer assignment 

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

1384 layers = assigner.assign() 

1385 

1386 # Crossing minimization 

1387 minimizer = CrossingMinimizer(layers, edges, back_edge_set) 

1388 layers = minimizer.minimize() 

1389 

1390 return _render_layered_diagram( 

1391 layers, 

1392 edges, 

1393 main_edge_set, 

1394 branches, 

1395 back_edges, 

1396 fsm.initial, 

1397 terminal_states, 

1398 fsm.states, 

1399 verbose, 

1400 highlight_state, 

1401 highlight_color, 

1402 ) 

1403 

1404 

1405def _render_horizontal_simple( 

1406 main_path: list[str], 

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

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

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

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

1411 bfs_order: list[str], 

1412 initial: str, 

1413 terminal_states: set[str], 

1414 fsm_states: dict[str, StateConfig], 

1415 verbose: bool, 

1416 highlight_state: str | None, 

1417 highlight_color: str, 

1418) -> str: 

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

1420 if not main_path: 

1421 return "" 

1422 

1423 all_states = list(main_path) 

1424 display_label = _compute_display_labels(all_states, initial, terminal_states) 

1425 

1426 tw = terminal_width() 

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

1428 if verbose and fsm_states and main_path: 

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

1430 else: 

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

1432 

1433 box_inner, box_width, box_height = _compute_box_sizes( 

1434 all_states, display_label, fsm_states, verbose, max_box_inner 

1435 ) 

1436 

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

1438 total_width = tw 

1439 

1440 # Column positions 

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

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

1443 x = 2 

1444 for i, sname in enumerate(main_path): 

1445 col_start[sname] = x 

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

1447 x += box_width[sname] 

1448 if i < len(main_path) - 1: 

1449 x += 4 

1450 

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

1452 

1453 for sname in main_path: 

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

1455 _draw_box( 

1456 rows, 

1457 0, 

1458 col_start[sname], 

1459 box_width[sname], 

1460 main_height, 

1461 box_inner[sname], 

1462 is_highlighted, 

1463 highlight_color, 

1464 ) 

1465 

1466 # Self-loops 

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

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

1469 if self_loops_list: 

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

1471 for src, _, label in self_loops_list: 

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

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

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

1475 self_row = [" "] * total_width 

1476 cx = col_center.get(sname, 0) 

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

1478 for j, ch in enumerate(marker): 

1479 if pos + j < total_width: 

1480 self_row[pos + j] = ch 

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

1482 

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

1484 if diagram_indent > 0: 

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

1486 

1487 return _colorize_diagram_labels("\n".join(lines))