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

1155 statements  

« prev     ^ index     » next       coverage.py v7.12.0, created at 2026-06-08 15:34 -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, strip_ansi, terminal_width 

19from little_loops.fsm.schema import FSMLoop, StateConfig 

20 

21# --------------------------------------------------------------------------- 

22# Edge label colorization 

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

24 

25_EDGE_LABEL_COLORS: dict[str, str] = { 

26 "yes": "32", 

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

28 "error": "31", 

29 "partial": "33", 

30 "next": "2", 

31 "_": "2", 

32 "blocked": "31", 

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

34 "rate_limit_exhausted": "38;5;214", 

35 "throttle_hard": "38;5;196", 

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 ( 

67 "no", 

68 "error", 

69 "blocked", 

70 "retry_exhausted", 

71 "rate_limit_exhausted", 

72 "throttle_hard", 

73 ): 

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

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

76 code = _EDGE_LABEL_COLORS["partial"] 

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

78 code = _EDGE_LABEL_COLORS["yes"] 

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

80 code = _EDGE_LABEL_COLORS["next"] 

81 return code 

82 

83 

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

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

86 

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

88 to avoid coloring partial matches inside state names. 

89 

90 Args: 

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

92 """ 

93 label_colors = colors if colors is not None else _EDGE_LABEL_COLORS 

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

95 colored = colorize(label, code) 

96 diagram = re.sub( 

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

98 colored, 

99 diagram, 

100 ) 

101 return diagram 

102 

103 

104# --------------------------------------------------------------------------- 

105# State box badge definitions 

106# --------------------------------------------------------------------------- 

107 

108_ACTION_TYPE_BADGES: dict[str, str] = { 

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

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

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

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

113} 

114 

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

116_ROUTE_BADGE = "\u2443" # ⑃ 

117 

118 

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

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

121 w = _wcswidth(badge) 

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

123 

124 

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

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

127 if state is None: 

128 return "" 

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

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

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

132 if state.loop is not None: 

133 return sub_loop_badge 

134 if state.action_type: 

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

136 if state.action: 

137 return effective["shell"] 

138 if state.route is not None: 

139 return route_badge 

140 return "" 

141 

142 

143# --------------------------------------------------------------------------- 

144# Box content helpers for multi-row diagram boxes 

145# --------------------------------------------------------------------------- 

146 

147 

148def _box_inner_lines( 

149 state: StateConfig | None, 

150 display_label: str, 

151 verbose: bool, 

152 inner_width: int, 

153 title_only: bool = False, 

154) -> list[str]: 

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

156 

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

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

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

160 

161 When ``title_only`` is True, only the name row is returned (used by 

162 ``--show-diagrams=mini`` for skeleton rendering). 

163 """ 

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

165 name_line = display_label[:inner_width] 

166 

167 lines: list[str] = [name_line] 

168 

169 if title_only: 

170 return lines 

171 

172 # Action lines 

173 if state and state.action: 

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

175 if verbose: 

176 for src in action_src: 

177 if not src: 

178 continue 

179 # Wrap long lines to inner_width 

180 while len(src) > inner_width: 

181 lines.append(src[:inner_width]) 

182 src = src[inner_width:] 

183 if src: 

184 lines.append(src) 

185 else: 

186 # Show first non-empty line, truncated 

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

188 if len(first) > inner_width: 

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

190 if first: 

191 lines.append(first) 

192 

193 return lines 

194 

195 

196# --------------------------------------------------------------------------- 

197# Topology detection 

198# --------------------------------------------------------------------------- 

199 

200 

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

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

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

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

205 if state.on_yes: 

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

207 if state.on_no: 

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

209 if state.on_error: 

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

211 if state.on_partial: 

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

213 if state.on_blocked: 

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

215 if state.on_retry_exhausted: 

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

217 if state.on_rate_limit_exhausted: 

218 edges.append((name, state.on_rate_limit_exhausted, "rate_limit_exhausted")) 

219 if state.on_throttle_hard: 

220 edges.append((name, state.on_throttle_hard, "throttle_hard")) 

221 if state.next: 

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

223 if state.route: 

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

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

226 if state.route.default: 

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

228 for verdict, target in state.extra_routes.items(): 

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

230 return edges 

231 

232 

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

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

235 order: list[str] = [] 

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

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

238 while queue: 

239 node = queue.popleft() 

240 order.append(node) 

241 for src, dst, _ in edges: 

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

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

244 queue.append(dst) 

245 return order, depth 

246 

247 

248def _trace_main_path( 

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

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

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

252 visited: set[str] = set() 

253 main_path: list[str] = [] 

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

255 current = fsm.initial 

256 while current and current not in visited: 

257 visited.add(current) 

258 main_path.append(current) 

259 st = fsm.states.get(current) 

260 if not st or st.terminal: 

261 break 

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

263 if not nxt and st.route: 

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

265 if nxt: 

266 main_edge_set.add((current, nxt)) 

267 current = nxt 

268 else: 

269 break 

270 return main_path, main_edge_set 

271 

272 

273def _classify_edges( 

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

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

276 bfs_order: list[str], 

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

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

279 main_consumed: set[int] = set() 

280 for src, dst in main_edge_set: 

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

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

283 main_consumed.add(i) 

284 break 

285 

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

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

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

289 if i in main_consumed: 

290 continue 

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

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

293 if dst == src or dst_pos < src_pos: 

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

295 else: 

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

297 return branches, back_edges 

298 

299 

300class TopologyDetector: 

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

302 

303 def __init__( 

304 self, 

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

306 main_path: list[str], 

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

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

309 ) -> None: 

310 self._edges = edges 

311 self._main_path = main_path 

312 self._branches = branches 

313 self._back_edges = back_edges 

314 

315 def classify(self) -> str: 

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

317 

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

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

320 General: everything else (full Sugiyama needed). 

321 """ 

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

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

324 

325 if not non_self_branches and not non_self_back: 

326 return "linear" 

327 

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

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

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

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

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

333 

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

335 return "tree" 

336 

337 return "general" 

338 

339 

340# --------------------------------------------------------------------------- 

341# Sugiyama layout pipeline 

342# --------------------------------------------------------------------------- 

343 

344 

345class LayerAssigner: 

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

347 

348 def __init__( 

349 self, 

350 all_states: list[str], 

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

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

353 initial: str, 

354 max_width: int = 4, 

355 ) -> None: 

356 self._all_states = all_states 

357 self._edges = edges 

358 self._back_edge_set = back_edge_set 

359 self._initial = initial 

360 self._max_width = max_width 

361 

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

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

364 # Build adjacency (forward edges only) 

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

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

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

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

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

370 continue 

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

372 forward[src].append(dst) 

373 reverse[dst].append(src) 

374 seen_edges.add((src, dst)) 

375 

376 # Longest-path layer assignment (topological order) 

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

378 

379 # Kahn's algorithm for topological order 

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

381 queue: deque[str] = deque() 

382 for s in self._all_states: 

383 if in_degree[s] == 0: 

384 queue.append(s) 

385 

386 topo_order: list[str] = [] 

387 while queue: 

388 node = queue.popleft() 

389 topo_order.append(node) 

390 for dst in forward[node]: 

391 in_degree[dst] -= 1 

392 if in_degree[dst] == 0: 

393 queue.append(dst) 

394 

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

396 for s in self._all_states: 

397 if s not in set(topo_order): 

398 topo_order.append(s) 

399 

400 # Assign layers: longest path from root 

401 for node in topo_order: 

402 if not reverse[node]: 

403 layer_of[node] = 0 

404 else: 

405 layer_of[node] = max( 

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

407 default=0, 

408 ) 

409 

410 # Ensure initial state is at layer 0 

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

412 offset = layer_of[self._initial] 

413 for s in layer_of: 

414 layer_of[s] -= offset 

415 

416 # Build layers list 

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

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

419 for s in self._all_states: 

420 layer = layer_of.get(s, 0) 

421 layers[layer].append(s) 

422 

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

424 if self._max_width > 0: 

425 new_layers: list[list[str]] = [] 

426 for grp in layers: 

427 remaining = list(grp) 

428 while len(remaining) > self._max_width: 

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

430 remaining = remaining[self._max_width :] 

431 if remaining: 

432 new_layers.append(remaining) 

433 layers = new_layers 

434 

435 return layers 

436 

437 

438class CrossingMinimizer: 

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

440 

441 def __init__( 

442 self, 

443 layers: list[list[str]], 

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

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

446 ) -> None: 

447 self._layers = layers 

448 self._edges = edges 

449 self._back_edge_set = back_edge_set 

450 

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

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

453 # Build position lookup 

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

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

456 for s in layer: 

457 layer_of[s] = i 

458 

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

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

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

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

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

464 continue 

465 if src in layer_of and dst in layer_of: 

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

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

468 

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

470 

471 # 3 sweeps: down, up, down 

472 for sweep in range(3): 

473 if sweep % 2 == 0: 

474 # Top-down sweep 

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

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

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

478 for s in layers[i]: 

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

480 if parents: 

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

482 else: 

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

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

485 else: 

486 # Bottom-up sweep 

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

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

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

490 for s in layers[i]: 

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

492 if children: 

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

494 else: 

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

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

497 

498 return layers 

499 

500 

501# --------------------------------------------------------------------------- 

502# Rendering helpers 

503# --------------------------------------------------------------------------- 

504 

505 

506def _compute_display_labels( 

507 all_states: list[str], 

508 initial: str, 

509 terminal_states: set[str], 

510) -> dict[str, str]: 

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

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

513 for s in all_states: 

514 label = s 

515 if s == initial: 

516 label = "\u2192 " + label 

517 if s in terminal_states: 

518 label = label + " \u25c9" 

519 display_label[s] = label 

520 return display_label 

521 

522 

523def _compute_box_sizes( 

524 all_states: list[str], 

525 display_label: dict[str, str], 

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

527 verbose: bool, 

528 max_box_inner: int, 

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

530 title_only: bool = False, 

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

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

533 

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

535 

536 When ``title_only`` is True, action body lines are suppressed (used by 

537 ``--show-diagrams=mini`` for skeleton rendering); box widths are computed 

538 from the name label / badge only. 

539 """ 

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

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

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

543 

544 for s in all_states: 

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

546 

547 badge = _get_state_badge(state_obj, badges) 

548 badge_w = _badge_display_width(badge) if badge else 0 

549 box_badge[s] = badge 

550 

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

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

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

554 

555 inner_w = base_w 

556 if not title_only and state_obj and state_obj.action and max_box_inner > 0: 

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

558 if verbose: 

559 max_action_w = max( 

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

561 ) 

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

563 else: 

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

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

566 

567 content = _box_inner_lines( 

568 state_obj, display_label[s], verbose, inner_w, title_only=title_only 

569 ) 

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

571 inner_w = max(inner_w, actual_w) 

572 box_inner[s] = content 

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

574 

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

576 return box_inner, box_width, box_height, box_badge 

577 

578 

579def _draw_box( 

580 grid: list[list[str]], 

581 row: int, 

582 col: int, 

583 width: int, 

584 height: int, 

585 content: list[str], 

586 is_highlighted: bool, 

587 highlight_color: str, 

588 badge: str = "", 

589) -> None: 

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

591 

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

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

594 """ 

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

596 try: 

597 bg_code: str | None = str(int(highlight_color) + 10) 

598 except (ValueError, TypeError): 

599 bg_code = None 

600 

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

602 if not is_highlighted: 

603 return ch 

604 if bg_code: 

605 return colorize(ch, f"{highlight_color};{bg_code}") 

606 return colorize(ch, highlight_color) 

607 

608 # Top border: ┌ ─ ─ … ─ ┐ 

609 if col < total_width: 

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

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

612 if col + j < total_width: 

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

614 if col + width - 1 < total_width: 

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

616 

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

618 if badge: 

619 badge_w = _badge_display_width(badge) 

620 # Trailing space between badge end and ┐ 

621 trail_pos = col + width - 2 

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

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

624 # Leading space before badge 

625 lead_pos = col + width - badge_w - 3 

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

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

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

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

630 for ch in badge: 

631 ch_w = _wcwidth(ch) 

632 if ch_w < 1: 

633 ch_w = 1 

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

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

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

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

638 pos += ch_w 

639 

640 # Pre-fill all interior cells with bg color so padding rows and gaps are filled 

641 if is_highlighted and bg_code: 

642 for ri in range(row + 1, row + height - 1): 

643 if ri >= len(grid): 

644 break 

645 for ci in range(col + 1, col + width - 1): 

646 if ci < total_width: 

647 grid[ri][ci] = colorize(" ", bg_code) 

648 

649 # Content rows 

650 for i, line in enumerate(content): 

651 r = row + i + 1 

652 if r >= len(grid): 

653 break 

654 if col < total_width: 

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

656 if col + width - 1 < total_width: 

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

658 if is_highlighted and i == 0: 

659 name_code = f"97;{bg_code};1" if bg_code else f"{highlight_color};1" 

660 colored_line = colorize(line, name_code) 

661 if col + 2 < total_width: 

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

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

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

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

666 elif i == 0: 

667 bold_line = colorize(line, "1") 

668 if col + 2 < total_width: 

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

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

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

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

673 else: 

674 for j, ch in enumerate(line): 

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

676 if is_highlighted and bg_code: 

677 grid[r][col + 2 + j] = colorize(ch, f"97;{bg_code}") 

678 else: 

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

680 

681 # Padding rows between content and bottom border 

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

683 r = row + i 

684 if r >= len(grid): 

685 break 

686 if col < total_width: 

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

688 if col + width - 1 < total_width: 

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

690 

691 # Bottom border 

692 brow = row + height - 1 

693 if brow < len(grid): 

694 if col < total_width: 

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

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

697 if col + j < total_width: 

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

699 if col + width - 1 < total_width: 

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

701 

702 

703# --------------------------------------------------------------------------- 

704# Layered (vertical) renderer 

705# --------------------------------------------------------------------------- 

706 

707 

708def _render_layered_diagram( 

709 layers: list[list[str]], 

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

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

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

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

714 initial: str, 

715 terminal_states: set[str] | None, 

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

717 verbose: bool, 

718 highlight_state: str | None, 

719 highlight_color: str, 

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

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

722 title_only: bool = False, 

723 suppress_labels: bool = False, 

724) -> str: 

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

726 

727 When ``title_only`` is True, per-state body lines are suppressed. 

728 When ``suppress_labels`` is True, inter-state edges render without labels. 

729 """ 

730 terminal_states = terminal_states or set() 

731 fsm_states = fsm_states or {} 

732 tw = terminal_width() 

733 

734 # Flatten layers to get all states 

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

736 if not all_states: 

737 return "" 

738 

739 display_label = _compute_display_labels(all_states, initial, terminal_states) 

740 

741 # Compute max_box_inner based on widest layer 

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

743 if verbose: 

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

745 else: 

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

747 

748 box_inner, box_width, box_height, box_badge = _compute_box_sizes( 

749 all_states, 

750 display_label, 

751 fsm_states, 

752 verbose, 

753 max_box_inner, 

754 badges, 

755 title_only=title_only, 

756 ) 

757 

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

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

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

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

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

763 gap_between = 6 

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

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

766 for src, dst, _ in edges: 

767 if src != dst and dst in _incoming: 

768 _incoming[dst].add(src) 

769 merged = True 

770 while merged: 

771 merged = False 

772 i = 0 

773 while i < len(layers) - 1: 

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

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

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

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

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

779 shared_source = sources_a & sources_b 

780 else: 

781 shared_source = set() 

782 combined_w = ( 

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

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

785 + gap_between 

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

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

788 ) 

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

790 layers[i] = la + lb 

791 layers.pop(i + 1) 

792 merged = True 

793 else: 

794 i += 1 

795 

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

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

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

799 for src, dst, lbl in edges: 

800 if src == dst: 

801 continue 

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

803 if (src, dst) in forward_edge_labels: 

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

805 else: 

806 forward_edge_labels[(src, dst)] = lbl 

807 

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

809 # Will be finalized below after col positions are computed 

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

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

812 for s, d, lbl in back_edges: 

813 if s != d: 

814 if (s, d) in back_edge_labels_initial: 

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

816 else: 

817 back_edge_labels_initial[(s, d)] = lbl 

818 

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

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

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

822 # positions are computed. 

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

824 for li, layer in enumerate(layers): 

825 for s in layer: 

826 prelim_layer_of[s] = li 

827 

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

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

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

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

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

833 if dst_layer < src_layer: 

834 if (src, dst) in all_back_labels: 

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

836 else: 

837 all_back_labels[(src, dst)] = lbl 

838 

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

840 back_edge_margin = 0 

841 if non_self_back_initial: 

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

843 n_back_initial = len(non_self_back_initial) 

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

845 

846 content_left = 2 + back_edge_margin 

847 

848 # Self-loops per state 

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

850 for src, dst, lbl in back_edges: 

851 if src == dst: 

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

853 

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

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

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

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

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

859 common_center = content_left + max_single_w // 2 

860 

861 # Compute column positions per layer 

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

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

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

865 

866 for li, layer in enumerate(layers): 

867 if len(layer) == 1: 

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

869 sname = layer[0] 

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

871 col_center[sname] = common_center 

872 layer_of[sname] = li 

873 else: 

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

875 gap_between = 6 

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

877 x = common_center - total_layer_w // 2 

878 x = max(content_left, x) 

879 for i, sname in enumerate(layer): 

880 col_start[sname] = x 

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

882 layer_of[sname] = li 

883 if i < len(layer) - 1: 

884 next_s = layer[i + 1] 

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

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

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

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

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

890 x += box_width[sname] + gap 

891 else: 

892 x += box_width[sname] 

893 

894 # Reclassify back-edges based on actual layer positions 

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

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

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

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

899 for src, dst, lbl in back_edges: 

900 if src == dst: 

901 continue 

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

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

904 if dst_layer < src_layer: 

905 if (src, dst) in back_edge_labels_reclass: 

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

907 else: 

908 back_edge_labels_reclass[(src, dst)] = lbl 

909 elif dst_layer == src_layer: 

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

911 else: # dst_layer > src_layer: actually forward edge 

912 if (src, dst) in forward_edge_labels: 

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

914 else: 

915 forward_edge_labels[(src, dst)] = lbl 

916 

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

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

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

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

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

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

923 if dst_layer < src_layer: 

924 backward_in_fwd.append((src, dst)) 

925 if (src, dst) in back_edge_labels_reclass: 

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

927 else: 

928 back_edge_labels_reclass[(src, dst)] = lbl 

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

930 backward_in_fwd.append((src, dst)) 

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

932 for key in backward_in_fwd: 

933 del forward_edge_labels[key] 

934 

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

936 for src, dst, lbl in same_layer_edges: 

937 if (src, dst) in forward_edge_labels: 

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

939 else: 

940 forward_edge_labels[(src, dst)] = lbl 

941 

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

943 affected_layers: set[int] = set() 

944 for src, dst, _lbl in same_layer_edges: 

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

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

947 if sl >= 0: 

948 affected_layers.add(sl) 

949 if dl >= 0: 

950 affected_layers.add(dl) 

951 for li in affected_layers: 

952 layer = layers[li] 

953 if len(layer) < 2: 

954 continue 

955 gap_between = 6 

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

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

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

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

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

961 for src, dst, lbl in same_layer_edges: 

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

963 continue 

964 try: 

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

966 except ValueError: 

967 continue 

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

969 continue # adjacent — already handled by forward_edge_labels 

970 if si > di: 

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

972 else: 

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

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

975 # Recalculate gaps with label-aware spacing 

976 gaps: list[int] = [] 

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

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

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

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

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

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

983 gaps.append(gap) 

984 total_layer_w += sum(gaps) 

985 x = common_center - total_layer_w // 2 

986 x = max(content_left, x) 

987 for i, sname in enumerate(layer): 

988 col_start[sname] = x 

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

990 if i < len(layer) - 1: 

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

992 else: 

993 x += box_width[sname] 

994 

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

996 

997 # Recalculate back-edge margin if it changed 

998 if non_self_back: 

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

1000 n_back = len(non_self_back) 

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

1002 if actual_margin != back_edge_margin: 

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

1004 back_edge_margin = actual_margin 

1005 content_left = 2 + back_edge_margin 

1006 

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

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

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

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

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

1012 if dst_layer > src_layer + 1: 

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

1014 

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

1016 right_edge_margin = 0 

1017 if skip_forward_edges: 

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

1019 right_edge_margin = max_fwd_label_len + 6 

1020 

1021 # Compute total width needed 

1022 total_content_w = 0 

1023 for s in all_states: 

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

1025 total_content_w = max(total_content_w, right) 

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

1027 

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

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

1030 y = 0 

1031 for li, layer in enumerate(layers): 

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

1033 for sname in layer: 

1034 row_start[sname] = y 

1035 y += layer_h 

1036 

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

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

1039 if has_self_loop: 

1040 y += 1 # self-loop marker row 

1041 

1042 if li < len(layers) - 1: 

1043 y += 2 if suppress_labels else 3 # arrow gap: suppress_labels skips label row 

1044 

1045 total_height = y 

1046 

1047 # Build character grid 

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

1049 

1050 # Draw boxes 

1051 for sname in all_states: 

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

1053 _draw_box( 

1054 grid, 

1055 row_start[sname], 

1056 col_start[sname], 

1057 box_width[sname], 

1058 box_height[sname], 

1059 box_inner[sname], 

1060 is_highlighted, 

1061 highlight_color, 

1062 badge=box_badge[sname], 

1063 ) 

1064 

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

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

1067 for _s in all_states: 

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

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

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

1071 _row_set.add(_c) 

1072 

1073 # Draw self-loop markers immediately below their boxes 

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

1075 marker = "\u21ba" if suppress_labels else "\u21ba " + ", ".join(labels) 

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

1077 if r < total_height: 

1078 cx = col_center[sname] 

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

1080 for j, ch in enumerate(marker): 

1081 if pos + j < total_width: 

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

1083 

1084 # Shared row tracker: prevents two labels (back-edge, skip-forward, or adjacent) 

1085 # landing on the same grid row, which would clobber the first label written there. 

1086 used_label_rows: set[int] = set() 

1087 

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

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

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

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

1092 self_loop_offset = 1 if has_self_loop else 0 

1093 

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

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

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

1097 

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

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

1100 for src in layers[li]: 

1101 for dst in layers[li + 1]: 

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

1103 if label is not None: 

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

1105 

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

1107 for src, dst, label in inter_edges: 

1108 dst_cc = col_center[dst] 

1109 src_left = col_start[src] 

1110 src_right = src_left + box_width[src] 

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

1112 

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

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

1115 

1116 # Horizontal connector when pipe is outside source box range 

1117 if dst_cc >= src_right or dst_cc < src_left: 

1118 conn_row = arrow_start_row 

1119 if 0 <= conn_row < total_height: 

1120 if dst_cc >= src_right: 

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

1122 src_cc = col_center[src] 

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

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

1125 start_c = src_cc + 1 

1126 else: 

1127 start_c = src_right 

1128 for c in range(start_c, dst_cc): 

1129 if 0 <= c < total_width: 

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

1131 if 0 <= dst_cc < total_width: 

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

1133 else: 

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

1135 src_cc = col_center[src] 

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

1137 end_c = src_cc 

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

1139 else: 

1140 end_c = src_left 

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

1142 if 0 <= c < total_width: 

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

1144 if 0 <= dst_cc < total_width: 

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

1146 pipe_start = arrow_start_row + 1 

1147 else: 

1148 pipe_start = arrow_start_row 

1149 

1150 # Draw vertical pipe at destination's center column 

1151 for r in range(pipe_start, arrow_end_row): 

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

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

1154 

1155 # Arrow tip at destination center 

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

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

1158 

1159 # Label to the right of the pipe. When skip-layer forward edges 

1160 # exist their vertical pipes occupy columns starting at 

1161 # total_content_w+2, so clamp to total_content_w to avoid 

1162 # overwriting them (BUG-1500). Without skip-layer edges the right 

1163 # margin is empty and the full total_width is available. 

1164 label_row = arrow_start_row 

1165 # Nudge if this row already has a label from another inter-layer edge 

1166 # (e.g., two edges from the same source go to states in the same layer). 

1167 # Try pipe rows (pipe_start..arrow_end_row) before giving up (BUG-1501). 

1168 if label_row in used_label_rows: 

1169 for _cand in range(pipe_start, arrow_end_row + 1): 

1170 if _cand not in used_label_rows: 

1171 label_row = _cand 

1172 break 

1173 if label_row < total_height and not suppress_labels: 

1174 used_label_rows.add(label_row) 

1175 label_start = dst_cc + 2 

1176 max_col = total_content_w if skip_forward_edges else total_width 

1177 max_label = max_col - label_start 

1178 if 0 < max_label < len(label): 

1179 label = label[: max_label - 1] + "…" 

1180 for j, ch in enumerate(label): 

1181 if label_start + j < max_col: 

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

1183 

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

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

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

1187 for src, dst, _ in inter_edges: 

1188 if dst in col_center: 

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

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

1191 if len(centers) < 2: 

1192 continue 

1193 left = min(centers) 

1194 right = max(centers) 

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

1196 if 0 <= c < total_width: 

1197 cell = grid[arrow_start_row][c] 

1198 if cell == " ": 

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1215 

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

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

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

1219 for _li, layer in enumerate(layers): 

1220 for i, src in enumerate(layer): 

1221 for j, dst in enumerate(layer): 

1222 if i == j: 

1223 continue 

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

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

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

1227 

1228 for src, dst, label in all_same_layer: 

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

1230 continue 

1231 if suppress_labels: 

1232 label = "" 

1233 name_row = row_start[src] + 1 

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

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

1236 dst_left = col_start[dst] 

1237 src_left = col_start[src] 

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

1239 ec = _edge_line_color(label) 

1240 

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

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

1243 

1244 if dst_left >= src_right: 

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

1246 start = src_right 

1247 end = dst_left 

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

1249 available = end - start 

1250 if available < len(edge_text): 

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

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

1253 for k in range(left_dashes): 

1254 pos = start + k 

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

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

1257 for k, ch in enumerate(edge_text): 

1258 pos = start + left_dashes + k 

1259 if ( 

1260 0 <= pos < end 

1261 and pos < total_width 

1262 and name_row < total_height 

1263 and pos not in _row_boxes 

1264 ): 

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

1266 elif dst_right <= src_left: 

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

1268 start = dst_right 

1269 end = src_left 

1270 edge_text = "\u25c4\u2500\u2500" + label + "\u2500" 

1271 available = end - start 

1272 if available < len(edge_text): 

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

1274 for k, ch in enumerate(edge_text): 

1275 pos = start + k 

1276 if ( 

1277 0 <= pos < end 

1278 and pos < total_width 

1279 and name_row < total_height 

1280 and pos not in _row_boxes 

1281 ): 

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

1283 for k in range(start + len(edge_text), end): 

1284 if k < total_width and name_row < total_height and k not in _row_boxes: 

1285 grid[name_row][k] = _lc("\u2500") 

1286 

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

1288 if non_self_back: 

1289 sorted_back = sorted( 

1290 non_self_back, 

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

1292 reverse=True, 

1293 ) 

1294 used_cols: list[int] = [] 

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

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

1297 

1298 for src, dst, label in sorted_back: 

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

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

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

1302 

1303 # Find a free column in the margin 

1304 col = 1 

1305 for uc in sorted(used_cols): 

1306 if uc == col: 

1307 col += 2 

1308 used_cols.append(col) 

1309 

1310 if col >= content_left - 1: 

1311 continue 

1312 

1313 top_row = min(src_row, dst_row) 

1314 bot_row = max(src_row, dst_row) 

1315 ec = _edge_line_color(label) 

1316 

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

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

1319 

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

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

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

1323 cell = grid[r][col] 

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

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

1326 elif cell == " ": 

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

1328 

1329 # Horizontal connector from source box to margin 

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

1331 if 0 <= src_row < total_height: 

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

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

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

1335 if c < total_width and c not in _src_row_boxes: 

1336 cell = grid[src_row][c] 

1337 if cell == " ": 

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

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

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

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

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

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

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

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

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

1347 # Leave ─, ▶, box chars unchanged 

1348 

1349 # Horizontal connector from margin to target box 

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

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

1352 if 0 <= dst_row < total_height: 

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

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

1355 if c < total_width and c not in _dst_row_boxes: 

1356 cell = grid[dst_row][c] 

1357 if cell == " ": 

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

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

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

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

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

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

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

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

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

1367 

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

1369 for row in (src_row, dst_row): 

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

1371 existing = grid[row][col] 

1372 if row == bot_row: 

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

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

1375 else: # row == top_row 

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

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

1378 

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

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

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

1382 

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

1384 label_row_pos = (top_row + bot_row) // 2 

1385 # Nudge away from already-used rows to prevent clobbering earlier labels 

1386 if label_row_pos in used_label_rows and top_row + 1 < bot_row: 

1387 midpoint = label_row_pos 

1388 found = False 

1389 for _off in range(1, bot_row - top_row): 

1390 for _cand in (midpoint - _off, midpoint + _off): 

1391 if top_row < _cand < bot_row and _cand not in used_label_rows: 

1392 label_row_pos = _cand 

1393 found = True 

1394 break 

1395 if found: 

1396 break 

1397 if not found: 

1398 label_row_pos = top_row + 1 

1399 used_label_rows.add(label_row_pos) 

1400 if 0 <= label_row_pos < total_height and not title_only: 

1401 label_start = rightmost_pipe_col + 2 

1402 for j, ch in enumerate(label): 

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

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

1405 

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

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

1408 if skip_forward_edges: 

1409 sorted_fwd_skip = sorted( 

1410 skip_forward_edges, 

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

1412 reverse=True, 

1413 ) 

1414 used_fwd_cols: list[int] = [] 

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

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

1417 

1418 for src, dst, label in sorted_fwd_skip: 

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

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

1421 

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

1423 col = total_content_w + 2 

1424 for uc in sorted(used_fwd_cols): 

1425 if uc == col: 

1426 col += 2 

1427 used_fwd_cols.append(col) 

1428 

1429 if col >= total_width: 

1430 continue 

1431 

1432 top_row = min(src_row, dst_row) 

1433 bot_row = max(src_row, dst_row) 

1434 ec = _edge_line_color(label) 

1435 

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

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

1438 

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

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

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

1442 cell = grid[r][col] 

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

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

1445 elif cell == " ": 

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

1447 

1448 # Horizontal connector from source box right side to margin 

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

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

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

1452 if 0 <= src_row < total_height: 

1453 for c in range(src_right, col): 

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

1455 cell = grid[src_row][c] 

1456 if cell == " ": 

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

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

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

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

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

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

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

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

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

1466 # Leave ─, ◀, box chars unchanged 

1467 

1468 # Horizontal connector from margin to destination box right side 

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

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

1471 if 0 <= dst_row < total_height: 

1472 for c in range(dst_right, col): 

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

1474 cell = grid[dst_row][c] 

1475 if cell == " ": 

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

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

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

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

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

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

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

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

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

1485 

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

1487 for row in (src_row, dst_row): 

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

1489 existing = grid[row][col] 

1490 if row == bot_row: 

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

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

1493 else: # row == top_row 

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

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

1496 

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

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

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

1500 

1501 # Label on the margin line (right of ALL pipes, mirroring left-margin 

1502 # approach). Truncate with … when label would exceed total_width 

1503 # to prevent extending diagram lines far past the content area (BUG-1500). 

1504 label_row_pos = (top_row + bot_row) // 2 

1505 # Nudge to avoid row collision with a previously-placed label (back- or fwd-edge) 

1506 if label_row_pos in used_label_rows and top_row + 1 < bot_row: 

1507 midpoint = label_row_pos 

1508 found = False 

1509 for _off in range(1, bot_row - top_row): 

1510 for _cand in (midpoint - _off, midpoint + _off): 

1511 if top_row < _cand < bot_row and _cand not in used_label_rows: 

1512 label_row_pos = _cand 

1513 found = True 

1514 break 

1515 if found: 

1516 break 

1517 if not found: 

1518 label_row_pos = top_row + 1 

1519 used_label_rows.add(label_row_pos) 

1520 if 0 <= label_row_pos < total_height and not title_only: 

1521 label_start = rightmost_fwd_pipe_col + 2 

1522 max_label = total_width - label_start 

1523 if 0 < max_label < len(label): 

1524 label = label[: max_label - 1] + "…" 

1525 for j, ch in enumerate(label): 

1526 if label_start + j < total_width: 

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

1528 

1529 # Convert grid to string 

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

1531 

1532 # Remove trailing empty lines 

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

1534 lines.pop() 

1535 

1536 # Center diagram 

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

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

1539 if diagram_indent > 0: 

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

1541 

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

1543 

1544 

1545# --------------------------------------------------------------------------- 

1546# FSM diagram renderer (main entry point) 

1547# --------------------------------------------------------------------------- 

1548 

1549 

1550_MAIN_PATH_EDGE_LABELS: frozenset[str] = frozenset({"yes", "no", "next", "_"}) 

1551 

1552 

1553def _filter_main_path_graph( 

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

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

1556 """Filter edges to the main happy-path subgraph and the states reachable through it. 

1557 

1558 Drops off-happy-path labels (anything not in ``_MAIN_PATH_EDGE_LABELS`` and not 

1559 a ``route``-verdict label) plus any state unreachable from ``fsm.initial`` once 

1560 those edges are gone. Route-verdict labels (everything emitted by ``state.route`` 

1561 other than the default ``_``) are kept since routes encode normal branching. 

1562 """ 

1563 route_verdicts: set[str] = set() 

1564 for _name, state in fsm.states.items(): 

1565 if state.route is not None: 

1566 route_verdicts.update(state.route.routes.keys()) 

1567 route_verdicts.update(state.extra_routes.keys()) 

1568 

1569 def _is_main_label(label: str) -> bool: 

1570 return label in _MAIN_PATH_EDGE_LABELS or label in route_verdicts 

1571 

1572 filtered_edges = [(s, t, lbl) for (s, t, lbl) in edges if _is_main_label(lbl)] 

1573 _bfs_visited_order, depth_map = _bfs_order(fsm.initial, filtered_edges) 

1574 reachable: set[str] = set(depth_map.keys()) 

1575 filtered_edges = [ 

1576 (s, t, lbl) for (s, t, lbl) in filtered_edges if s in reachable and t in reachable 

1577 ] 

1578 return filtered_edges, reachable 

1579 

1580 

1581def _render_fsm_diagram( 

1582 fsm: FSMLoop, 

1583 verbose: bool = False, 

1584 highlight_state: str | None = None, 

1585 highlight_color: str = "32", 

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

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

1588 mode: str = "full", 

1589 *, 

1590 suppress_labels: bool = False, 

1591 title_only: bool = False, 

1592) -> str: 

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

1594 

1595 Detects FSM topology and selects appropriate layout: 

1596 - Linear chains: vertical top-to-bottom 

1597 - Branching/cyclic: layered Sugiyama-style 

1598 

1599 Args: 

1600 fsm: The FSM loop to render. 

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

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

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

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

1605 Falls back to hardcoded defaults when None. 

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

1607 Falls back to hardcoded defaults when None. 

1608 mode: Controls edge scope: "main" (default when filtering active) hides 

1609 off-happy-path edges. "full" renders every edge and state. "mini" is 

1610 an alias for main-scope; use ``suppress_labels=True, title_only=True`` 

1611 instead. Callers that need full-detail dumps (e.g. ``ll-loop info``) 

1612 keep the default "full". 

1613 suppress_labels: If True, edge labels are omitted from all rendered edges. 

1614 title_only: If True, state boxes show only the state name (no action body). 

1615 """ 

1616 edges = _collect_edges(fsm) 

1617 if mode in ("main", "mini"): 

1618 edges, _reachable = _filter_main_path_graph(fsm, edges) 

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

1620 main_path, main_edge_set = _trace_main_path(fsm, edges) 

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

1622 

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

1624 

1625 # Collect all states 

1626 all_states = list(main_path) 

1627 for src, dst, _ in branches: 

1628 for s in (src, dst): 

1629 if s not in all_states: 

1630 all_states.append(s) 

1631 

1632 # Topology detection 

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

1634 topology = detector.classify() 

1635 

1636 # Build back-edge set for layout pipeline 

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

1638 for src, dst, _ in back_edges: 

1639 if src != dst: 

1640 back_edge_set.add((src, dst)) 

1641 

1642 tw = terminal_width() 

1643 

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

1645 # Single state or empty — use simple horizontal 

1646 return _render_horizontal_simple( 

1647 main_path, 

1648 edges, 

1649 main_edge_set, 

1650 branches, 

1651 back_edges, 

1652 bfs_order_list, 

1653 fsm.initial, 

1654 terminal_states, 

1655 fsm.states, 

1656 verbose, 

1657 highlight_state, 

1658 highlight_color, 

1659 edge_label_colors, 

1660 badges, 

1661 title_only=title_only or (mode == "mini"), 

1662 suppress_labels=suppress_labels or (mode == "mini"), 

1663 ) 

1664 

1665 # Compute max node width to determine width constraint 

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

1667 max_node_w = 30 # reasonable default 

1668 for s in all_states: 

1669 st = fsm.states.get(s) 

1670 badge = _get_state_badge(st, badges) 

1671 badge_w = _badge_display_width(badge) if badge else 0 

1672 label = s 

1673 if s == fsm.initial: 

1674 label = "\u2192 " + label 

1675 if s in terminal_states: 

1676 label = label + " \u25c9" 

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

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

1679 

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

1681 

1682 # Layer assignment 

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

1684 layers = assigner.assign() 

1685 

1686 # Crossing minimization 

1687 minimizer = CrossingMinimizer(layers, edges, back_edge_set) 

1688 layers = minimizer.minimize() 

1689 

1690 return _render_layered_diagram( 

1691 layers, 

1692 edges, 

1693 main_edge_set, 

1694 branches, 

1695 back_edges, 

1696 fsm.initial, 

1697 terminal_states, 

1698 fsm.states, 

1699 verbose, 

1700 highlight_state, 

1701 highlight_color, 

1702 edge_label_colors, 

1703 badges, 

1704 title_only=title_only or (mode == "mini"), 

1705 suppress_labels=suppress_labels or (mode == "mini"), 

1706 ) 

1707 

1708 

1709_PREV_STATE_COLOR = "33" # ANSI orange/yellow border for the just-prior FSM state. 

1710 

1711 

1712def _render_neighborhood_diagram( 

1713 fsm: FSMLoop, 

1714 active_state: str, 

1715 *, 

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

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

1718 highlight_color: str = "32", 

1719 mode: str = "full", 

1720 prev_state: str | None = None, 

1721) -> str: 

1722 """Render a compact 1-hop neighborhood: predecessors → [active] → successors. 

1723 

1724 Suitable as a fallback when the full FSM diagram does not fit the viewport. 

1725 Bounded: ``max(len(preds), len(succs), 1) * 3`` rows (each state box is 3 

1726 lines tall). Returns the empty string when ``active_state`` is not in 

1727 ``fsm.states``. 

1728 

1729 Self-loops are collapsed: a state that only points to itself contributes 

1730 neither predecessors nor successors here. 

1731 

1732 Args: 

1733 mode: ``"full"`` (default) includes every edge. ``"main"`` filters edges 

1734 through ``_filter_main_path_graph`` so off-happy-path predecessors 

1735 (e.g. those connected only via ``on_error``) are hidden. Falls back 

1736 to ``"full"`` if the active state would be filtered out. 

1737 prev_state: Name of the predecessor the FSM most recently transitioned 

1738 from. When that name appears in the rendered pred stack, its box is 

1739 drawn with the orange ``_PREV_STATE_COLOR`` border. Silently 

1740 skipped if the name is missing from the pred stack. 

1741 """ 

1742 if active_state not in fsm.states: 

1743 return "" 

1744 

1745 edges = _collect_edges(fsm) 

1746 if mode == "main": 

1747 filtered_edges, reachable = _filter_main_path_graph(fsm, edges) 

1748 if active_state in reachable: 

1749 edges = filtered_edges 

1750 preds = sorted({s for (s, t, _lbl) in edges if t == active_state and s != active_state}) 

1751 succs = sorted({t for (s, t, _lbl) in edges if s == active_state and t != active_state}) 

1752 

1753 terminal_states = {n for n, st in fsm.states.items() if st.terminal} 

1754 

1755 def _label(name: str) -> str: 

1756 label = name 

1757 if name == fsm.initial: 

1758 label = "→ " + label 

1759 if name in terminal_states: 

1760 label = label + " ◉" 

1761 return label 

1762 

1763 pred_labels = [_label(p) for p in preds] 

1764 active_label = _label(active_state) 

1765 succ_labels = [_label(s) for s in succs] 

1766 

1767 inner_pred = max((len(lbl) for lbl in pred_labels), default=0) 

1768 inner_active = len(active_label) 

1769 inner_succ = max((len(lbl) for lbl in succ_labels), default=0) 

1770 

1771 box_w_pred = inner_pred + 4 if pred_labels else 0 

1772 box_w_active = inner_active + 4 

1773 box_w_succ = inner_succ + 4 if succ_labels else 0 

1774 

1775 n_rows = max(len(pred_labels), len(succ_labels), 1) 

1776 try: 

1777 nd_bg_code: str | None = str(int(highlight_color) + 10) 

1778 except (ValueError, TypeError): 

1779 nd_bg_code = None 

1780 

1781 def _make_box( 

1782 label: str, 

1783 inner_w: int, 

1784 highlighted: bool, 

1785 *, 

1786 border_color: str | None = None, 

1787 ) -> list[str]: 

1788 top = "┌" + "─" * (inner_w + 2) + "┐" 

1789 bot = "└" + "─" * (inner_w + 2) + "┘" 

1790 padded = label.ljust(inner_w) 

1791 if highlighted: 

1792 border_code = f"{highlight_color};{nd_bg_code}" if nd_bg_code else highlight_color 

1793 top = colorize(top, border_code) 

1794 bot = colorize(bot, border_code) 

1795 if nd_bg_code: 

1796 mid = ( 

1797 colorize("│", border_code) 

1798 + colorize(" ", nd_bg_code) 

1799 + colorize(padded, f"97;{nd_bg_code};1") 

1800 + colorize(" ", nd_bg_code) 

1801 + colorize("│", border_code) 

1802 ) 

1803 else: 

1804 mid = ( 

1805 colorize("│", border_code) 

1806 + " " 

1807 + colorize(padded, f"{highlight_color};1") 

1808 + " " 

1809 + colorize("│", border_code) 

1810 ) 

1811 elif border_color is not None: 

1812 top = colorize(top, border_color) 

1813 bot = colorize(bot, border_color) 

1814 mid = ( 

1815 colorize("│", border_color) 

1816 + " " 

1817 + colorize(padded, "1") 

1818 + " " 

1819 + colorize("│", border_color) 

1820 ) 

1821 else: 

1822 mid = "│ " + colorize(padded, "1") + " │" 

1823 return [top, mid, bot] 

1824 

1825 center_idx = (n_rows - 1) // 2 

1826 

1827 def _build_stack( 

1828 labels: list[str], 

1829 box_w: int, 

1830 *, 

1831 color_for: dict[str, str] | None = None, 

1832 ) -> list[str]: 

1833 rows: list[str] = [] 

1834 # Align the stack to the arrow row (the active state's slot). Without 

1835 # this, a shorter stack always sits at row 0 and the single ``──▶`` 

1836 # arrow drawn at ``active_line_offset`` points into empty space. 

1837 # ``min(center_idx, n_rows - len(labels))`` caps the start so longer 

1838 # but still-smaller stacks (e.g. 4 succs vs. 5 preds) don't overflow. 

1839 start = max(0, min(center_idx, n_rows - len(labels))) 

1840 color_map = color_for or {} 

1841 for i in range(n_rows): 

1842 j = i - start 

1843 if 0 <= j < len(labels): 

1844 border = color_map.get(labels[j]) 

1845 rows.extend(_make_box(labels[j], box_w - 4, False, border_color=border)) 

1846 else: 

1847 rows.extend([" " * box_w] * 3) 

1848 return rows 

1849 

1850 pred_color_for: dict[str, str] = {} 

1851 if prev_state is not None and prev_state in preds: 

1852 pred_color_for[_label(prev_state)] = _PREV_STATE_COLOR 

1853 

1854 pred_col = ( 

1855 _build_stack(pred_labels, box_w_pred, color_for=pred_color_for) if pred_labels else None 

1856 ) 

1857 succ_col = _build_stack(succ_labels, box_w_succ) if succ_labels else None 

1858 active_rows: list[str] = [] 

1859 for i in range(n_rows): 

1860 if i == center_idx: 

1861 active_rows.extend(_make_box(active_label, inner_active, True)) 

1862 else: 

1863 active_rows.extend([" " * box_w_active] * 3) 

1864 

1865 arrow = " ──▶ " 

1866 arrow_blank = " " * len(arrow) 

1867 active_line_offset = center_idx * 3 + 1 

1868 

1869 total_lines = n_rows * 3 

1870 out_lines: list[str] = [] 

1871 for i in range(total_lines): 

1872 parts: list[str] = [] 

1873 if pred_col is not None: 

1874 parts.append(pred_col[i]) 

1875 parts.append(arrow if i == active_line_offset else arrow_blank) 

1876 parts.append(active_rows[i]) 

1877 if succ_col is not None: 

1878 parts.append(arrow if i == active_line_offset else arrow_blank) 

1879 parts.append(succ_col[i]) 

1880 out_lines.append("".join(parts).rstrip()) 

1881 

1882 return "\n".join(out_lines) 

1883 

1884 

1885def _render_horizontal_simple( 

1886 main_path: list[str], 

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

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

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

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

1891 bfs_order: list[str], 

1892 initial: str, 

1893 terminal_states: set[str], 

1894 fsm_states: dict[str, StateConfig], 

1895 verbose: bool, 

1896 highlight_state: str | None, 

1897 highlight_color: str, 

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

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

1900 title_only: bool = False, 

1901 suppress_labels: bool = False, 

1902) -> str: 

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

1904 

1905 When ``title_only`` is True, per-state body lines and self-loop labels are suppressed. 

1906 When ``suppress_labels`` is True, self-loop markers omit label text. 

1907 """ 

1908 if not main_path: 

1909 return "" 

1910 all_states = list(main_path) 

1911 display_label = _compute_display_labels(all_states, initial, terminal_states) 

1912 

1913 tw = terminal_width() 

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

1915 if verbose and fsm_states and main_path: 

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

1917 else: 

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

1919 

1920 box_inner, box_width, box_height, box_badge = _compute_box_sizes( 

1921 all_states, 

1922 display_label, 

1923 fsm_states, 

1924 verbose, 

1925 max_box_inner, 

1926 badges, 

1927 title_only=title_only, 

1928 ) 

1929 

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

1931 total_width = tw 

1932 

1933 # Column positions 

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

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

1936 x = 2 

1937 for i, sname in enumerate(main_path): 

1938 col_start[sname] = x 

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

1940 x += box_width[sname] 

1941 if i < len(main_path) - 1: 

1942 x += 4 

1943 

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

1945 

1946 for sname in main_path: 

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

1948 _draw_box( 

1949 rows, 

1950 0, 

1951 col_start[sname], 

1952 box_width[sname], 

1953 main_height, 

1954 box_inner[sname], 

1955 is_highlighted, 

1956 highlight_color, 

1957 badge=box_badge[sname], 

1958 ) 

1959 

1960 # Self-loops 

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

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

1963 if self_loops_list: 

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

1965 for src, _, label in self_loops_list: 

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

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

1968 marker = "\u21ba" if suppress_labels else "\u21ba " + ", ".join(labels) 

1969 self_row = [" "] * total_width 

1970 cx = col_center.get(sname, 0) 

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

1972 for j, ch in enumerate(marker): 

1973 if pos + j < total_width: 

1974 self_row[pos + j] = ch 

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

1976 

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

1978 if diagram_indent > 0: 

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

1980 

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