bat-cli 0.26.12

Blockchain Auditor Toolkit (BAT)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
//! Fully automatic deployment of an EVM entry point's dependency graph to Miro.
//!
//! One frame per entry point (public/external function). Inside it, every
//! function in the call graph is rendered, measured, laid out and uploaded
//! already positioned, and every call site gets a connector anchored to the
//! exact line of the caller that makes the call.
//!
//! Nothing is dragged by hand: the pipeline is
//!
//! ```text
//! metadata → graph → PNGs → measure → scale → layout → frame → images → connectors → persist
//! ```

use std::collections::{HashMap, HashSet, VecDeque};

use colored::Colorize;
use error_stack::{IntoReport, Report, ResultExt};
use indicatif::{ProgressBar, ProgressStyle};

use crate::batbelt::evm::metadata::bat_metadata::{
    AutoDeployedFrame, ContractMetadata, EvmBatMetadata, FunctionMetadata, ShelfState,
};
use crate::batbelt::evm::miro::EvmMiroError;
use crate::batbelt::evm::parser::call_resolver::{body_only, extract_call_sites_from_source};
use crate::batbelt::evm::types::EvmContractType;
use crate::batbelt::miro::client::{ArrowEnd, ConnectorStyle, MiroClient, RelativeAnchor};
use crate::batbelt::miro::layout::{
    layout_graph, GraphLayout, LayoutConfig, LayoutEdge, LayoutNode, ShelfAllocator,
};
use crate::batbelt::bat_dialoguer::BatDialoguer;
use crate::batbelt::path::BatFolder;
use crate::batbelt::silicon;
use rand::seq::SliceRandom;
use rayon::prelude::*;

type Result<T> = error_stack::Result<T, EvmMiroError>;

/// Gap left between the end of the code and the connector anchor, in characters.
const ANCHOR_GAP_CHARS: f64 = 1.0;
/// Vertical distance from the top of the callee where its signature sits: line
/// index 2 of the image, because `include_path` prepends `// path` plus a blank.
const SIGNATURE_LINE_INDEX: usize = 2;
/// Number of lines `include_path` prepends to the rendered content.
pub(crate) const PATH_HEADER_LINES: usize = 2;
/// Vertical margin left between the existing board content and the region we
/// reserve for automatic deployments.
const REGION_MARGIN: f64 = 5_000.0;


/// Side of the invisible square the connector attaches to, in board units.
/// Small enough that the arrow head reads as landing on the token itself.
const ANCHOR_MARKER_SIZE: f64 = 24.0;
/// Horizontal distance between two arrows' vertical lanes in a gutter: five times the
/// default 8dp stroke, so two arrows at full width still have four strokes of white
/// between them. Narrowed automatically when a gutter cannot fit them all.
const LANE_PITCH: f64 = 40.0;
/// A frame's background when something in it changes state, and when something in it
/// only might — the same red and amber as the per-node markings, several steps lighter.
/// The job is to be legible from far enough out that a whole cluster fits on screen;
/// up close the screenshots are what is being read, and a strong tint behind them
/// competes with the code. Miro's own "light red" (`#ffc6c6`) is already too much.
const FRAME_FILL_WRITES: &str = "#fff0ef";
const FRAME_FILL_MAY_WRITE: &str = "#fff7ec";
/// How many far callers may each get their OWN copy of a callee before it is given a
/// frame instead. Copying is what removes a crossing arrow, and for a leaf it is
/// cheap — but the cost is paid once per caller, so the same rule that keeps `sqrt`
/// beside its two callers puts nine copies of a helper on a frame when nine callers
/// reach it. Past this, one drawing in a frame of its own and a card beside each
/// caller is both smaller and easier to read.
const MAX_COPIES_OF_ONE_CALLEE: usize = 3;

/// A bar that shows what is happening and how far along it is.
///
/// Rendering and uploading are both long enough to look like a hang without
/// one: a deployment can render dozens of screenshots and then make a hundred
/// API calls, and the previous output went silent for the whole of each phase.
fn phase_bar(label: &str, total: usize) -> ProgressBar {
    let bar = ProgressBar::new(total as u64);
    bar.set_style(
        ProgressStyle::with_template("  {spinner:.blue} {msg} {pos}/{len} {wide_bar:.blue}")
            .unwrap()
            .tick_chars("⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏ "),
    );
    bar.set_message(label.to_string());
    bar.enable_steady_tick(std::time::Duration::from_millis(100));
    bar
}

/// Connector colors, cycled per depth so sibling levels stay distinguishable.
const DEPTH_COLORS: &[&str] = &[
    "#2d9bf0", "#f24726", "#8fd14f", "#fac710", "#a259ff", "#12cdd4", "#ff8c00", "#e6007a",
];

#[derive(Debug, Clone)]
pub struct AutoDeployOptions {
    /// Deploy only this entry point (`name` or `Contract.name`).
    pub entry_point: Option<String>,
    /// Compute and print the layout without touching Miro.
    pub dry_run: bool,
    /// Extend each screenshot upward to include the function's NatSpec block, so
    /// the diagram carries the documented intent next to the code.
    pub with_documentation: bool,
    /// Compose a local preview PNG of the frame at this path.
    pub preview: Option<String>,
    /// Connector thickness in dp, 1 to 24. Miro's UI snaps this to its own
    /// preset levels, so 12 lands on roughly "level 5".
    pub stroke_width: u32,
    /// Draw the partial graph even when interface calls in the tree are unresolved,
    /// instead of stopping to list them.
    pub allow_unresolved: bool,
    /// Contracts whose functions are never drawn: a name (`Math`) or any part of a
    /// path (`openzeppelin-contracts/contracts/utils/math`). The call is still shown
    /// in the caller's screenshot — it is the callee's box that is left out.
    pub ignore_contracts: Vec<String>,
    /// Draw the ENTIRE call graph inline in one frame: no branch is cut to its own
    /// frame, and no already-deployed frame is linked — every function is a
    /// screenshot. Lets you see how big a large function is with screenshots only
    /// (and how Miro copes), and gives a step-through-able single frame.
    pub inline_all: bool,
}

impl Default for AutoDeployOptions {
    fn default() -> Self {
        Self {
            entry_point: None,
            dry_run: false,
            with_documentation: false,
            preview: None,
            stroke_width: 8,
            allow_unresolved: false,
            ignore_contracts: Vec::new(),
            inline_all: false,
        }
    }
}

/// Shared context for a deploy: the entry point that owns the whole cluster, and
/// the ids of the PREVIOUS cluster's frames, so a still-live old frame is never
/// reused (every deploy is fresh) and can be reported for manual deletion
/// afterwards. Threaded through the recursive deploy.
#[derive(Clone)]
struct ClusterCtx {
    root: String,
    stale_ids: HashSet<String>,
}

/// What a node stands for.
#[derive(Debug, Clone, PartialEq)]
enum NodeKind {
    /// A screenshot of the function's source.
    Screenshot,
    /// A card standing in for a function drawn in its own frame, holding a link
    /// that navigates there.
    Link {
        target: String,
        /// File of the contract the card stands for, so the frame deployed for it is the
        /// same copy that was drawn here and not another contract with the same name.
        file: String,
    },
}

/// A card is small and fixed: it carries a name and a link, nothing to measure.
const LINK_CARD_WIDTH: f64 = 900.0;
const LINK_CARD_HEIGHT: f64 = 240.0;

/// One function in the graph.
#[derive(Debug, Clone)]
struct GraphNode {
    id: String,
    label: String,
    kind: NodeKind,
    file_path: String,
    /// 1-based, inclusive, in the source file.
    start_line: usize,
    end_line: usize,
    depth: usize,
    font_size: usize,
    /// Filled in during the render phase.
    png_path: String,
    png_width: u32,
    png_height: u32,
    /// Text of every line rendered in the image, including the path header.
    rendered_lines: Vec<String>,
    /// `line_offset` handed to silicon, needed to reproduce the line-number gutter.
    line_offset: usize,
    /// This function writes contract storage — drawn with a colored border so an
    /// auditor can spot the state-mutating nodes at a glance.
    writes_storage: bool,
    /// File lines (1-based) inside this node's slice that write storage, each with
    /// the lvalue path — used to highlight the exact mutating statements.
    write_lines: Vec<(usize, String)>,
    /// File lines (1-based) that call an external contract with no in-scope source
    /// (an interface-typed receiver nothing in the repo implements) via a non-view
    /// method — an unverified external state-change boundary, flagged distinctly.
    external_call_lines: Vec<usize>,
    /// This function writes no storage itself, but something it calls does.
    ///
    /// Without this a pass-through reads as inert: `DebtToken.mint` exists only to reach
    /// `ERC20._update`, and in OpenZeppelin v5 neither `mint` nor `_mint` assigns anything
    /// — the write is three hops down. The chain was drawn correctly and looked like it
    /// changed nothing.
    leads_to_write: bool,
    /// Call lines (1-based, file) that reach a storage write, as
    /// `(line, symbol, callee node id)`. The id is empty when the callee never entered
    /// the graph at all.
    ///
    /// These are CANDIDATES. One state change must produce exactly ONE mark, so a line is
    /// only drawn when its callee is not itself a screenshot on this frame — otherwise the
    /// callee carries the mark, nearer to where the write really happens. The filter runs
    /// at draw time because framing can turn a screenshot into a link card after the graph
    /// is built.
    write_call_lines: Vec<(usize, String, String)>,
    /// Display scale for this placement. Every function is rendered ONCE at the
    /// reference font (`REFERENCE_FONT`, the depth-0 size); a deeper node shows the
    /// same image shrunk by this factor (< 1), so the source is rendered once and
    /// reused across depths and duplicate placements instead of re-rendered. Line
    /// fractions are scale-invariant, so only the board size and upload width use it.
    scale: f64,
}

impl GraphNode {
    fn board_width(&self) -> f64 {
        self.png_width as f64 * BOARD_UNITS_PER_PIXEL * self.scale
    }

    fn board_height(&self) -> f64 {
        self.png_height as f64 * BOARD_UNITS_PER_PIXEL * self.scale
    }
}

/// One call site: caller, callee, and the line of the caller it happens on.
#[derive(Debug, Clone)]
struct GraphEdge {
    from: String,
    to: String,
    /// 1-based line inside the caller's captured slice.
    line_in_slice: usize,
    /// 0-based column where the called name starts on that line.
    column: usize,
    /// The token the connector should point at, e.g. `wadMul` in
    /// `MathLib.wadMul(...)`.
    symbol: String,
}

/// How many board units one rendered pixel becomes.
///
/// Constant on purpose. Forcing every screenshot to a fixed board width instead
/// would blow up a narrow capture and shrink a wide one — a 530 px image
/// stretched to 1200 and a 1468 px image squeezed to 1200 end up with nearly 3x
/// difference in text size inside the same layer. Keeping the ratio fixed means
/// the only thing that changes the text size is the font used to render it.
pub(crate) const BOARD_UNITS_PER_PIXEL: f64 = 1.0;

/// Font per depth: the entry point is rendered biggest and leaves smallest, so a
/// deep graph stays readable. Width now follows from the code itself.
/// The one font every screenshot is rendered at (the largest, depth-0 size). A
/// deeper node reuses that render shrunk via `scale_for_depth`, so a function is
/// rendered once and reused across depths and duplicate placements.
pub(crate) const REFERENCE_FONT: usize = 32;

fn font_for_depth(depth: usize) -> usize {
    match depth {
        0 => 32,
        1 => 26,
        _ => 22,
    }
}

/// How much to shrink a node's (reference-font) render for its depth. Always ≤ 1,
/// so text is only ever scaled DOWN and stays crisp.
fn scale_for_depth(depth: usize) -> f64 {
    font_for_depth(depth) as f64 / REFERENCE_FONT as f64
}


pub async fn run(options: AutoDeployOptions) -> Result<()> {
    let metadata = EvmBatMetadata::read_metadata().change_context(EvmMiroError)?;

    let targets = select_targets(&metadata, &options)?;
    if targets.is_empty() {
        return Err(Report::new(EvmMiroError)
            .attach_printable("no entry point matched; run `bat-cli sonar` first"));
    }

    println!(
        "Auto-deploying {} entry point(s){}",
        targets.len().to_string().green(),
        if options.dry_run {
            " (dry run, nothing is sent to Miro)".yellow().to_string()
        } else {
            String::new()
        }
    );

    // One client for the whole batch, so the credit budget is shared.
    let client = if options.dry_run {
        None
    } else {
        Some(
            MiroClient::new_refreshed()
                .await
                .change_context(EvmMiroError)?,
        )
    };

    // A fresh deploy draws into a CLEAN zone: forget the cached region so the allocator
    // re-scans and places the fresh cluster below everything currently on the board.
    if !options.dry_run {
        EvmBatMetadata::update_metadata(|m| m.miro.auto.region = None)
            .change_context(EvmMiroError)?;
    }

    // The board is scanned at most once, to pick the region origin.
    let metadata = EvmBatMetadata::read_metadata().change_context(EvmMiroError)?;
    // What a deploy leaves out is the union of the saved list and this run's flags.
    let mut options = options;
    for pattern in &metadata.ignored_contracts {
        if !options.ignore_contracts.contains(pattern) {
            options.ignore_contracts.push(pattern.clone());
        }
    }
    let options = options;
    if !options.ignore_contracts.is_empty() {
        println!(
            "  {} not drawing: {}",
            "note:".yellow(),
            options.ignore_contracts.join(", ")
        );
    }
    let mut allocator = if options.dry_run {
        ShelfAllocator::new(0.0, 0.0)
    } else {
        resolve_allocator(client.as_ref().unwrap(), &metadata).await?
    };

    for (contract_name, function_name, root_file) in targets {
        let title = format!("{contract_name}.{function_name}");

        // A fresh deploy finds the PREVIOUS cluster (this entry point's frame + every
        // dependency frame its last deploy spawned), keeps only the ones still on the
        // board, so we can (a) never reuse them and (b) hand you their URLs to delete.
        let mut stale: Vec<(String, String)> = Vec::new(); // (entry_point, url)
        if !options.dry_run {
            if let Some(client) = client.as_ref() {
                let meta = EvmBatMetadata::read_metadata().change_context(EvmMiroError)?;
                for f in &meta.miro.auto.frames {
                    if f.cluster_root == title || f.entry_point == title {
                        if client.item_exists(&f.frame_id).await {
                            stale.push((f.entry_point.clone(), f.frame_url.clone()));
                        }
                    }
                }
            }
        }
        let stale_ids: HashSet<String> = {
            let meta = EvmBatMetadata::read_metadata().change_context(EvmMiroError)?;
            meta.miro
                .auto
                .frames
                .iter()
                .filter(|f| f.cluster_root == title || f.entry_point == title)
                .map(|f| f.frame_id.clone())
                .collect()
        };
        let cluster = ClusterCtx {
            root: title.clone(),
            stale_ids,
        };

        let root_options = options.clone();

        deploy_one(
            &metadata,
            &contract_name,
            &function_name,
            &root_file,
            &root_options,
            client.as_ref(),
            &mut allocator,
            true,
            &cluster,
        )
        .await?;

        // A fresh deploy drops the old cluster's now-orphaned records and prints their
        // URLs for one-click manual deletion (a frame + its contents delete together
        // in Miro's web UI; the API can't, and one-by-one deletion is slow).
        if !options.dry_run {
            let owner = title.clone();
            let old_ids: HashSet<String> = cluster.stale_ids.clone();
            EvmBatMetadata::update_metadata(move |m| {
                m.miro.auto.frames.retain(|f| {
                    !((f.cluster_root == owner || f.entry_point == owner)
                        && old_ids.contains(&f.frame_id))
                });
            })
            .change_context(EvmMiroError)?;
            if !stale.is_empty() {
                println!(
                    "\n  {} {} old frame(s) from the previous deploy — delete them in Miro (one click each; the frame takes its contents with it):",
                    "⚠".yellow(),
                    stale.len()
                );
                for (ep, url) in &stale {
                    println!("    {} {}", ep.dimmed(), url.blue());
                }
            }
        }

        // Persist the cursor after every entry point, not once at the end: a run
        // over a whole project is long enough to be interrupted, and a lost
        // cursor would place the next batch on top of the frames already there.
        if !options.dry_run {
            let state = ShelfState::from(&allocator);
            EvmBatMetadata::update_metadata(|m| m.miro.auto.region = Some(state.clone()))
                .change_context(EvmMiroError)?;
        }
    }

    // Wipe the shared screenshot cache once, now that every frame (a whole cluster)
    // has uploaded — each distinct function was rendered once for the entire run.
    if !options.dry_run {
        if let Ok(dir) = BatFolder::Figures.get_path(false) {
            let _ = std::fs::remove_dir_all(&dir);
        }
    }

    Ok(())
}

/// What to deploy.
///
/// Any function can be deployed, not just an entry point: a shared helper needs
/// a frame of its own for anything else to be able to point at it, and it is
/// worth looking at on its own terms too.
///
/// Deploying a whole project at once is deliberately not the default. An audit
/// is read one function at a time, and a project of any size would put thousands
/// of objects on a board that Miro starts to slow down past a thousand — so with
/// nothing named, ask.
fn select_targets(
    metadata: &EvmBatMetadata,
    options: &AutoDeployOptions,
) -> Result<Vec<(String, String, String)>> {
    // A target is `(contract, function, file)`. The file is part of the identity: `lib/`
    // can vendor three copies of `BeaconProxy`, all with the same name.
    let entry_names: HashSet<(String, String)> = metadata
        .entry_points
        .iter()
        .map(|ep| {
            let function = ep
                .name
                .strip_prefix(&format!("{}.", ep.contract_name))
                .unwrap_or(&ep.name)
                .to_string();
            (ep.contract_name.clone(), function)
        })
        .collect();

    // The picker and `--all` list what the project itself defines: `lib/` and
    // constructors are dependency plumbing nobody wants to scroll past. Naming something
    // explicitly with `--entry-point` reaches everything — see `resolve_named_target`.
    let mut entry_points: Vec<(String, String, String)> = Vec::new();
    let mut others: Vec<(String, String, String)> = Vec::new();
    for contract in metadata.contracts.iter().filter(|c| !c.external) {
        for function in &contract.functions {
            let target = (
                contract.name.clone(),
                function.name.clone(),
                contract.file_path.clone(),
            );
            if entry_names.contains(&(contract.name.clone(), function.name.clone())) {
                entry_points.push(target);
            } else if !function.is_constructor {
                others.push(target);
            }
        }
    }
    entry_points.sort();
    entry_points.dedup();
    others.sort();
    others.dedup();

    if let Some(wanted) = &options.entry_point {
        return resolve_named_target(metadata, &entry_names, wanted);
    }

    // Entry points first, since that is where reading usually starts, then
    // everything else. One flat list, because it is fuzzy-searchable: typing
    // `feeOf` reaches a helper as fast as an entry point.
    let deployed: HashSet<String> = metadata
        .miro
        .auto
        .frames
        .iter()
        .map(|frame| frame.entry_point.clone())
        .collect();

    let all: Vec<(String, String, String)> = entry_points
        .iter()
        .cloned()
        .chain(others.iter().cloned())
        .collect();
    if all.is_empty() {
        return Ok(all);
    }

    // Two in-scope contracts can share a name too; only then is the path worth showing.
    let mut title_count: HashMap<String, usize> = HashMap::new();
    for (contract, function, _) in &all {
        *title_count.entry(format!("{contract}.{function}")).or_default() += 1;
    }

    let entry_point_count = entry_points.len();
    let labels: Vec<String> = all
        .iter()
        .enumerate()
        .map(|(index, (contract, function, file))| {
            let title = format!("{contract}.{function}");
            let mut label = if title_count[&title] > 1 {
                format!("{title}  ({file})")
            } else {
                title.clone()
            };
            if index < entry_point_count {
                label = format!("{label}  {}", "[entry point]".blue());
            }
            if deployed.contains(&title) {
                label = format!("{label} {}", "(deployed)".green());
            }
            label
        })
        .collect();

    let selection =
        BatDialoguer::fuzzy_select("Select what to deploy:".to_string(), labels)
            .change_context(EvmMiroError)?;

    Ok(vec![all[selection].clone()])
}

/// Resolve `--entry-point` to exactly one function, or stop and say why.
///
/// Accepts `function`, `Contract.function`, and `path/To.sol:Contract.function`. Named
/// explicitly, anything is reachable: a contract under `lib/`, a constructor, a
/// `fallback`. Following what a constructor does is a legitimate thing to draw, and the
/// person who typed the name has already decided it is worth seeing.
///
/// Several matches are narrowed in the order a reader would expect, and only what the code
/// cannot decide becomes a question:
///
/// 1. the project's own entry points, then its other functions, then `lib/` — so `mint`
///    still means the audited `DebtToken.mint`, not one of OpenZeppelin's;
/// 2. among same-named contracts in different files, the copy the audited code imports,
///    resolved through the import graph and `remappings.txt` exactly as `solc` resolves it;
/// 3. anything still ambiguous — two in-scope contracts with a `poke`, or a library nobody
///    in `src/` imports — stops, listing each candidate in the `path:Contract.function`
///    form that selects it. That decision needs context the code does not carry, which is
///    exactly when the assistant (or the auditor) should make it.
fn resolve_named_target(
    metadata: &EvmBatMetadata,
    entry_names: &HashSet<(String, String)>,
    wanted: &str,
) -> Result<Vec<(String, String, String)>> {
    use crate::batbelt::evm::parser::import_graph::{normalize, reachable_from};

    let (wanted_path, rest) = match wanted.rsplit_once(':') {
        Some((path, rest)) if path.ends_with(".sol") => (Some(normalize(path)), rest),
        _ => (None, wanted),
    };
    let (wanted_contract, wanted_function) = match rest.rsplit_once('.') {
        Some((contract, function)) => (Some(contract), function),
        None => (None, rest),
    };

    // (contract, function, file, external, is entry point)
    let mut matches: Vec<(String, String, String, bool, bool)> = Vec::new();
    for contract in &metadata.contracts {
        // An interface declares, it does not do anything worth drawing.
        if contract.contract_type == EvmContractType::Interface {
            continue;
        }
        if wanted_contract.is_some_and(|name| name != contract.name) {
            continue;
        }
        if let Some(path) = &wanted_path {
            let file = normalize(&contract.file_path);
            if file != *path && !file.ends_with(&format!("/{path}")) {
                continue;
            }
        }
        for function in contract.functions.iter().filter(|f| f.name == wanted_function) {
            let entry = !contract.external
                && entry_names.contains(&(contract.name.clone(), function.name.clone()));
            matches.push((
                contract.name.clone(),
                function.name.clone(),
                contract.file_path.clone(),
                contract.external,
                entry,
            ));
        }
    }
    // Overloads of one function in one contract are one target; the graph picks the overload.
    matches.sort();
    matches.dedup_by(|a, b| a.0 == b.0 && a.1 == b.1 && a.2 == b.2);
    if matches.is_empty() {
        return Ok(Vec::new());
    }

    let tier: Vec<&(String, String, String, bool, bool)> = {
        let entry: Vec<_> = matches.iter().filter(|m| m.4).collect();
        let own: Vec<_> = matches.iter().filter(|m| !m.3).collect();
        if !entry.is_empty() {
            entry
        } else if !own.is_empty() {
            own
        } else {
            matches.iter().collect()
        }
    };
    let pick = |m: &(String, String, String, bool, bool)| vec![(m.0.clone(), m.1.clone(), m.2.clone())];
    if tier.len() == 1 {
        return Ok(pick(tier[0]));
    }

    // Same name, several files: keep the copies the audited code can actually reach.
    let reachable = reachable_from(
        metadata
            .contracts
            .iter()
            .filter(|c| !c.external)
            .map(|c| c.file_path.as_str()),
    );
    let narrowed: Vec<_> = tier
        .iter()
        .filter(|m| reachable.contains(&normalize(&m.2)))
        .copied()
        .collect();
    if narrowed.len() == 1 {
        return Ok(pick(narrowed[0]));
    }

    let listed = if narrowed.is_empty() { &tier } else { &narrowed };
    let candidates = listed
        .iter()
        .map(|m| format!("{}:{}.{}", normalize(&m.2), m.0, m.1))
        .collect::<Vec<_>>();
    let why = if narrowed.is_empty() {
        "nothing in the audited code imports any of them, so the code cannot decide"
    } else {
        "the audited code reaches more than one of them"
    };
    Err(Report::new(EvmMiroError)
        .attach_printable(format!(
            "`{wanted}` matches {} functions — {why}:\n    {}",
            listed.len(),
            candidates.join("\n    ")
        ))
        .attach(crate::Suggestion(format!(
            "pick one and pass it whole, e.g. `bat-cli deploy --entry-point {}`",
            candidates[0]
        ))))
}

/// Reserve (or recover) the board region the automatic frames live in.
async fn resolve_allocator(
    client: &MiroClient,
    metadata: &EvmBatMetadata,
) -> Result<ShelfAllocator> {
    if let Some(state) = &metadata.miro.auto.region {
        return Ok(state.to_allocator());
    }

    println!("Scanning the board once to reserve a region for automatic frames...");
    let frames = client.list_frames().await.change_context(EvmMiroError)?;

    let (origin_x, origin_y) = if frames.is_empty() {
        (0.0, 0.0)
    } else {
        let bottom = frames.iter().map(|f| f.bottom()).fold(f64::MIN, f64::max);
        let left = frames.iter().map(|f| f.left()).fold(f64::MAX, f64::min);
        (left, bottom + REGION_MARGIN)
    };

    println!(
        "  region origin: ({}, {}) — below {} existing frame(s)",
        origin_x.round(),
        origin_y.round(),
        frames.len()
    );
    Ok(ShelfAllocator::new(origin_x, origin_y))
}

async fn deploy_one(
    metadata: &EvmBatMetadata,
    contract_name: &str,
    function_name: &str,
    // The file of the selected contract, which is what tells same-named copies apart.
    root_file: &str,
    options: &AutoDeployOptions,
    client: Option<&MiroClient>,
    allocator: &mut ShelfAllocator,
    // True when the user named this function, false when it is being built only
    // because a card needs somewhere to point.
    is_primary: bool,
    cluster: &ClusterCtx,
) -> Result<()> {
    let title = format!("{contract_name}.{function_name}");
    println!("\n{} {}", "▸".blue(), title.bold());
    // When several contracts share this name, say which copy was picked. The choice is made
    // from the imports and is deterministic, but nobody reading the output should have to
    // go re-derive it from `remappings.txt` to trust the diagram.
    if metadata.contracts.iter().filter(|c| c.name == contract_name).count() > 1 {
        println!("  {} {}", "from".dimmed(), root_file);
    }

    // One frame per function, board-wide. Asked for as a link target, a function
    // already on the board is pointed at rather than drawn again — that is what
    // lets several diagrams share a helper's frame and keeps the fan-in readable.
    // Asked for directly, RECYCLE it: delete the old frame and its items, then
    // redraw — so a redeploy replaces the frame instead of piling up duplicates.
    let (mut nodes, mut edges, unresolved) =
        build_graph(metadata, contract_name, function_name, root_file, options)?;
    if nodes.is_empty() {
        println!("  no function metadata found, skipping");
        return Ok(());
    }

    // Every deploy is fresh, so nothing another deploy left on the board is linked —
    // but a frame THIS run already drew for THIS cluster is a different matter. It is
    // the same rule `ensure_target_frames` reuses by (`cluster_root` matches, id is not
    // the old cluster's), and it is what keeps a helper two branches reach from being
    // drawn twice: the second branch cards it. Cutting to one of these is free — the
    // frame exists — so `best_cut` may target it at any size, which is what you want
    // for a big callee that keeps coming back.
    let deployed_titles: HashSet<String> = if cluster.root.is_empty() {
        HashSet::new()
    } else {
        let meta = EvmBatMetadata::read_metadata().change_context(EvmMiroError)?;
        let in_graph: HashSet<&str> = nodes.iter().map(|node| node.label.as_str()).collect();
        meta.miro
            .auto
            .frames
            .iter()
            .filter(|frame| {
                frame.cluster_root == cluster.root
                    && !cluster.stale_ids.contains(&frame.frame_id)
                    && frame.entry_point != title
                    && in_graph.contains(frame.entry_point.as_str())
            })
            .map(|frame| frame.entry_point.clone())
            .collect()
    };

    // Cross-contract calls this tree reaches through an interface, whose concrete
    // target static analysis cannot pin. By default STOP so the AI (or auditor) can
    // resolve them and the downstream storage writers can be drawn; `--allow-unresolved`
    // draws the partial graph instead.
    if !unresolved.is_empty() && !options.allow_unresolved {
        println!(
            "\n  {} {} interface call(s) in this tree are unresolved — their downstream\n  functions (and any storage changes) are NOT in the graph yet:",
            "⚠".yellow(),
            unresolved.len()
        );
        for u in &unresolved {
            let ty = if u.inferred_type.is_empty() {
                String::new()
            } else {
                format!("  [{}]", u.inferred_type)
            };
            println!(
                "    {}.{}{}  → candidates: {}",
                u.receiver,
                u.method,
                ty,
                if u.candidates.is_empty() {
                    "(none in scope)".to_string()
                } else {
                    u.candidates.join(", ")
                }
            );
            if !u.assigned_in.is_empty() {
                println!("        wired in: {}", u.assigned_in.join(", ").dimmed());
            }
        }
        println!(
            "\n  Resolve each interface to its concrete contract, then deploy again:\n    {}\n  (or pass {} to draw the partial graph as-is.)",
            "bat-cli resolve <INTERFACE> <CONTRACT>".green(),
            "--allow-unresolved".green()
        );
        return Err(Report::new(EvmMiroError).attach_printable(format!(
            "{} unresolved interface call(s) in {}.{} — see the list above",
            unresolved.len(),
            contract_name,
            function_name
        )));
    }
    let depth = nodes.iter().map(|node| node.depth).max().unwrap_or(0);
    println!(
        "  {} screenshots, {} connectors, {} levels deep",
        nodes.len().to_string().green(),
        edges.len().to_string().green(),
        (depth + 1).to_string().green()
    );

    let reuse: HashMap<String, (String, u32, u32)> = HashMap::new();

    render_and_measure(&mut nodes, &title, &reuse)?;

    let layout_nodes: Vec<LayoutNode> = nodes
        .iter()
        .map(|node| LayoutNode {
            id: node.id.clone(),
            width: node.board_width(),
            height: node.board_height(),
        })
        .collect();

    let anchors = compute_anchors(&nodes, &edges);
    let layout_edges: Vec<LayoutEdge> = edges
        .iter()
        .zip(anchors.iter())
        .map(|(edge, anchor)| LayoutEdge {
            from: edge.from.clone(),
            to: edge.to.clone(),
            from_line_fraction: anchor.y_fraction,
        })
        .collect();

    let root_id = nodes[0].id.clone();
    let mut layout = layout_graph(&root_id, &layout_nodes, &layout_edges, LayoutConfig::default());

    // Only cut when the frame is too big to read, and only a cut that measurably
    // shrinks it. Arrows reaching across layers are not by themselves a reason:
    // the layout already reserves a corridor for them, so they cross nothing.
    // What a card buys is space, and it only buys space when the call it
    // replaces was the last reference to a branch.
    // Functions with a frame already on the board: cutting to one is free (no new
    // frame is created), so `best_cut` may target them at any size.
    let framed: HashSet<&str> = deployed_titles.iter().map(|s| s.as_str()).collect();
    // Aim each piece AT a readable size: the budget starts at the target, raised only
    // when the graph is so big that even `MAX_CUTS_PER_FRAME` target-sized cuts wouldn't
    // fit it — then the pieces are bigger and split again by their own deploy.
    let total = screenshot_count(&nodes);
    let mut budget = FRAME_TARGET.max(total.div_ceil(MAX_CUTS_PER_FRAME + 1));
    let mut anchors = anchors;
    // Cut until the frame READS, not a fixed number of times. The cap was a fixed ten
    // passes and a budget that never moved, so a graph whose branches are all smaller
    // than the budget — or all shared — exhausted its passes (or found nothing to cut
    // at all) and shipped whatever was left: `FLAMMSwapLib.execute` landed on the board
    // as 250 screenshots and 641 connectors. The bound is now the node count, which no
    // run can reach: every pass removes at least one screenshot.
    let cut_passes = if options.inline_all { 0 } else { nodes.len() };
    for _ in 0..cut_passes {
        if effective_size(&nodes) <= FRAME_MAX {
            break;
        }
        // Nothing worth cutting AT THIS BUDGET is not the same as nothing worth
        // cutting: aiming at readable pieces first, then smaller ones, beats giving up
        // and drawing a wall. FRAME_MIN is the floor — below it a cut buys a husk frame
        // and costs a card, which is worse than the screenshot it replaced.
        let mut found = None;
        while found.is_none() {
            found = best_cut(&nodes, &edges, &framed, budget);
            if found.is_some() || budget <= FRAME_MIN {
                break;
            }
            budget = (budget * 3 / 4).max(FRAME_MIN);
        }
        let Some((cut_nodes, cut_edges)) = found else {
            println!(
                "  {} {} screenshots and nothing left that can be cut into a readable\n  frame — every branch is either shared or too small to be worth its own",
                "warning:".yellow(),
                screenshot_count(&nodes)
            );
            break;
        };
        println!(
            "  {} {} screenshots is more than reads well; linking a branch out to\n  its own frame instead",
            "note:".yellow(),
            screenshot_count(&nodes)
        );
        nodes = cut_nodes;
        edges = cut_edges;

        anchors = compute_anchors(&nodes, &edges);
        let layout_nodes: Vec<LayoutNode> = nodes
            .iter()
            .map(|node| LayoutNode {
                id: node.id.clone(),
                width: node.board_width(),
                height: node.board_height(),
            })
            .collect();
        let layout_edges: Vec<LayoutEdge> = edges
            .iter()
            .zip(anchors.iter())
            .map(|(edge, anchor)| LayoutEdge {
                from: edge.from.clone(),
                to: edge.to.clone(),
                from_line_fraction: anchor.y_fraction,
            })
            .collect();
        layout = layout_graph(&root_id, &layout_nodes, &layout_edges, LayoutConfig::default());
    }

    // Localize the small helpers that STILL cross after framing. Now that the big
    // shared subtrees are cut out to their own frames, the frame is small, so
    // copying a leaf (sqrt, a getter) next to each far caller is cheap and — crucial
    // — no longer whack-a-mole (the deep floor those copies would re-call is gone).
    // Uses the measured layout (a caller ≥2 columns back = a crossing arrow), copies
    // only SMALL closures, then re-lays-out.
    //
    // That first sentence is a PREMISE, not a description, so it is checked: on a frame
    // framing could not bring under FRAME_MAX, copying helpers adds screenshots to a
    // wall to shorten arrows nobody can follow anyway. Shortening an unreadable diagram
    // is not worth making it bigger, so localization is skipped there.
    if effective_size(&nodes) <= FRAME_MAX {
        // First the crossers too big to copy: they become frames of their own, with a
        // card beside each caller, so the long arrow is gone rather than shortened.
        let cut_crossers = if options.inline_all {
            0
        } else {
            cut_crossing_shared(&mut nodes, &mut edges, &root_id)
        };
        if cut_crossers > 0 {
            println!(
                "  {} {} call(s) flying over a column replaced by a card to the callee's frame",
                "↳".blue(),
                cut_crossers
            );
        }
        let before = screenshot_count(&nodes);
        duplicate_crossing_shared(&mut nodes, &mut edges, &root_id);
        if screenshot_count(&nodes) > before {
            println!(
                "  {} localized {} crossing helper copy(ies)",
                "↳".blue(),
                screenshot_count(&nodes) - before
            );
        }
        anchors = compute_anchors(&nodes, &edges);
        let ln: Vec<LayoutNode> = nodes
            .iter()
            .map(|node| LayoutNode {
                id: node.id.clone(),
                width: node.board_width(),
                height: node.board_height(),
            })
            .collect();
        let le: Vec<LayoutEdge> = edges
            .iter()
            .zip(anchors.iter())
            .map(|(edge, anchor)| LayoutEdge {
                from: edge.from.clone(),
                to: edge.to.clone(),
                from_line_fraction: anchor.y_fraction,
            })
            .collect();
        layout = layout_graph(&root_id, &ln, &le, LayoutConfig::default());
    }
    let by_id: HashMap<&str, &GraphNode> = nodes.iter().map(|n| (n.id.as_str(), n)).collect();

    // Reserve the slot in both modes, so a dry run shows the real sequence of
    // board positions instead of repeating the first one.
    // Every frame is brand new, so it always takes a slot from the allocator — which
    // is what puts a cluster's frames next to each other instead of wherever an
    // earlier deploy happened to leave them.
    let (frame_x, frame_y) = allocator.place(layout.frame_width, layout.frame_height);

    if let Some(preview_path) = &options.preview {
        let path = preview_path.clone();
        render_preview(&nodes, &edges, &anchors, &layout, &path)?;
        println!("  preview written to {}", path.blue());
        // A preview is a LOCAL composition for eyeballing the layout — it never
        // touches the board. (The delete+recreate of a redeploy is slow, so this is
        // the fast way to iterate on the diagram.) Stop here, like a dry run.
        cleanup(&nodes);
        return Ok(());
    }

    if options.dry_run {
        print_dry_run(&nodes, &edges, &anchors, &layout, (frame_x, frame_y));
        cleanup(&nodes);
        return Ok(());
    }

    let client = client.expect("client is present when not in dry-run mode");
    // The frame carries the same answer its nodes do, in its own background: red when
    // something drawn here changes state, amber when something here probably does, and
    // red wins when both are true — a frame that changes state IS one, whatever else it
    // also might do. That is the same precedence a node has, where the amber border is
    // only drawn on a node the red one skipped.
    //
    // A cluster is thirty frames on a board and "where does state change" is asked from
    // that distance, where a node's own border is two pixels. It is the frame's own
    // fill, not a shape laid over it: nothing extra to create, register or clean up.
    let frame_fill = if nodes
        .iter()
        .any(|n| n.writes_storage || !n.write_call_lines.is_empty())
    {
        Some(FRAME_FILL_WRITES)
    } else if nodes.iter().any(|n| !n.external_call_lines.is_empty()) {
        Some(FRAME_FILL_MAY_WRITE)
    } else {
        None
    };
    let frame_id = client
        .create_frame(
            &format!("auto: {title}"),
            frame_x,
            frame_y,
            layout.frame_width,
            layout.frame_height,
            frame_fill,
        )
        .await
        .change_context(EvmMiroError)?;
    println!(
        "  frame {} ({}x{}) at ({}, {})",
        frame_id.green(),
        layout.frame_width.round(),
        layout.frame_height.round(),
        frame_x.round(),
        frame_y.round()
    );

    // Every card needs somewhere to go. One frame per function, board-wide: two
    // cards for the same helper resolve to the same frame, and a helper already
    // deployed is reused rather than drawn again. That is what keeps the fan-in
    // answerable — one frame with several references, not a copy per caller.
    let target_frames = ensure_target_frames(&nodes, options, client, allocator, cluster).await?;

    // Record the frame before filling it, so a run that dies partway through
    // still leaves something that names what is on the board.
    let frame_url = client.frame_url(&frame_id);
    let mut record = AutoDeployedFrame {
        entry_point: title.clone(),
        frame_id: frame_id.clone(),
        frame_url: frame_url.clone(),
        x: frame_x,
        y: frame_y,
        width: layout.frame_width,
        height: layout.frame_height,
        images: Vec::new(),
        image_dims: Vec::new(),
        node_positions: Vec::new(),
        callee_connectors: Vec::new(),
        link_cards: Vec::new(),
        connector_ids: Vec::new(),
        marker_ids: Vec::new(),
        border_ids: Vec::new(),
        // A brand-new frame carries no declaration screenshots: the ones added with
        // `bat-cli screenshot` belong to the frame they were placed on, which this
        // deploy leaves untouched on the board.
        screenshots: Vec::new(),
        // Every frame belongs to the named entry point's cluster, so the next deploy
        // of that entry point can find and report the whole previous cluster.
        cluster_root: if cluster.root.is_empty() { title.clone() } else { cluster.root.clone() },
    };
    save_frame_record(&record)?;

    // Images, already positioned and parented — one call each, no follow-up
    // PATCH. They are independent of each other, so they go up concurrently;
    // the client's semaphore and credit budget are what actually bound the rate.
    let uploads: Vec<_> = nodes
        .iter()
        .filter_map(|node| layout.node(&node.id).map(|placed| (node, placed)))
        .collect();
    let bar = phase_bar("uploading screenshots", uploads.len());
    let mut upload_tasks = tokio::task::JoinSet::new();
    for (node, placed) in uploads {
        let client = client.clone();
        let frame_id = frame_id.clone();
        let node_id = node.id.clone();
        let png_path = node.png_path.clone();
        let label = node.label.clone();
        let kind = node.kind.clone();
        let target_url = match &node.kind {
            NodeKind::Link { target, .. } => target_frames.get(target).cloned().unwrap_or_default(),
            NodeKind::Screenshot => String::new(),
        };
        let reused_image = reuse.get(&node.id).map(|(image_id, _, _)| image_id.clone());
        let (x, y, width, height) = (placed.x, placed.y, placed.width, placed.height);
        let bar = bar.clone();
        upload_tasks.spawn(async move {
            let result = match kind {
                NodeKind::Link { .. } => {
                    client
                        .create_link_card(&frame_id, &label, &target_url, x, y, width, height)
                        .await
                }
                NodeKind::Screenshot => match reused_image {
                    // Refresh: the image is already on the board — just move it.
                    Some(image_id) => client
                        .update_item_position(&image_id, x, y)
                        .await
                        .map(|_| image_id),
                    None => {
                        client
                            .create_image_in_frame(&png_path, &frame_id, &label, x, y, width)
                            .await
                    }
                },
            };
            bar.inc(1);
            result.map(|image_id| (node_id, image_id))
        });
    }

    let mut image_ids: HashMap<String, String> = HashMap::new();
    while let Some(joined) = upload_tasks.join_next().await {
        let (node_id, image_id) = joined
            .into_report()
            .change_context(EvmMiroError)?
            .change_context(EvmMiroError)?;
        image_ids.insert(node_id, image_id);
    }
    bar.finish_and_clear();
    println!("    {} {} screenshots uploaded", "✓".green(), image_ids.len());

    // Storage-write markers: a hollow red rectangle around every node whose function
    // changes state — whether it holds the assignment or only reaches one through what it
    // calls. One marking, not two: the question a reader asks is "does this change state",
    // and a pass-through like `DebtToken.mint` answers yes even though it assigns nothing.
    let drawn_screens = drawn_screen_ids(&nodes);
    let frame_writes: Vec<&GraphNode> = nodes
        .iter()
        .filter(|n| n.writes_storage || surviving_write_calls(n, &drawn_screens).next().is_some())
        .collect();
    let frame_external: Vec<&GraphNode> = nodes
        .iter()
        .filter(|n| !n.external_call_lines.is_empty())
        .collect();
    let borders: Vec<(f64, f64, f64, f64)> = nodes
        .iter()
        .filter(|n| {
            n.writes_storage || surviving_write_calls(n, &drawn_screens).next().is_some()
        })
        .filter_map(|n| layout.node(&n.id).map(|p| (p.x, p.y, p.width, p.height)))
        .collect();
    if !borders.is_empty() {
        let n_borders = borders.len();
        let bar = phase_bar("storage markers", n_borders);
        let mut border_tasks = tokio::task::JoinSet::new();
        for (x, y, width, height) in borders {
            let client = client.clone();
            let frame_id = frame_id.clone();
            let bar = bar.clone();
            border_tasks.spawn(async move {
                let result = client
                    .create_storage_border(&frame_id, x, y, width, height)
                    .await;
                bar.inc(1);
                result
            });
        }
        while let Some(joined) = border_tasks.join_next().await {
            let id = joined
                .into_report()
                .change_context(EvmMiroError)?
                .change_context(EvmMiroError)?;
            record.border_ids.push(id);
        }
        bar.finish_and_clear();
        println!("    {} {} storage markers", "✓".green(), n_borders);
    }

    // External-boundary node borders: a hollow dashed amber rectangle around every
    // node that makes a non-view call to a sourceless external contract but writes
    // NO storage of its own — so it gets no red border, yet a state change probably
    // happens through it. Skipped when the node is already ringed red.
    let ext_borders: Vec<(f64, f64, f64, f64)> = nodes
        .iter()
        .filter(|n| !n.external_call_lines.is_empty() && !n.writes_storage)
        .filter_map(|n| layout.node(&n.id).map(|p| (p.x, p.y, p.width, p.height)))
        .collect();
    if !ext_borders.is_empty() {
        let n_ext_borders = ext_borders.len();
        let bar = phase_bar("external markers", n_ext_borders);
        let mut border_tasks = tokio::task::JoinSet::new();
        for (x, y, width, height) in ext_borders {
            let client = client.clone();
            let frame_id = frame_id.clone();
            let bar = bar.clone();
            border_tasks.spawn(async move {
                let result = client
                    .create_external_border(&frame_id, x, y, width, height)
                    .await;
                bar.inc(1);
                result
            });
        }
        while let Some(joined) = border_tasks.join_next().await {
            let id = joined
                .into_report()
                .change_context(EvmMiroError)?
                .change_context(EvmMiroError)?;
            record.border_ids.push(id);
        }
        bar.finish_and_clear();
        println!("    {} {} external markers", "✓".green(), n_ext_borders);
    }

    // Line highlights: a translucent red band over each exact statement that
    // writes storage, so an auditor sees WHICH state a function mutates (not just
    // that it does). Tracked as border ids so a recycle clears them too.
    let mut highlights: Vec<(f64, f64, f64, f64)> = Vec::new();
    for node in nodes.iter() {
        if node.png_height == 0 {
            continue;
        }
        let surviving: Vec<usize> = surviving_write_calls(node, &drawn_screens)
            .map(|(line, _, _)| *line)
            .collect();
        if node.write_lines.is_empty() && surviving.is_empty() {
            continue;
        }
        let Some(p) = layout.node(&node.id) else {
            continue;
        };
        let geom = silicon::line_geometry(Some(node.font_size));
        let line_h = (p.height * geom.line_height as f64 / node.png_height as f64).max(1.0);
        let mut lines: Vec<usize> = node
            .write_lines
            .iter()
            .map(|(line, _)| *line)
            .chain(surviving.iter().copied())
            .filter(|line| *line >= node.start_line && *line <= node.end_line)
            .collect();
        lines.sort_unstable();
        lines.dedup();
        for line in lines {
            let rendered_index = PATH_HEADER_LINES + (line - node.start_line);
            let y_fraction = geom.line_center_fraction(rendered_index, node.png_height);
            let cy = p.y - p.height / 2.0 + p.height * y_fraction;
            highlights.push((p.x, cy, p.width, line_h));
        }
    }
    if !highlights.is_empty() {
        let n_highlights = highlights.len();
        let bar = phase_bar("storage lines", n_highlights);
        let mut highlight_tasks = tokio::task::JoinSet::new();
        for (x, y, width, height) in highlights {
            let client = client.clone();
            let frame_id = frame_id.clone();
            let bar = bar.clone();
            highlight_tasks.spawn(async move {
                let result = client
                    .create_line_highlight(&frame_id, x, y, width, height)
                    .await;
                bar.inc(1);
                result
            });
        }
        while let Some(joined) = highlight_tasks.join_next().await {
            let id = joined
                .into_report()
                .change_context(EvmMiroError)?
                .change_context(EvmMiroError)?;
            record.border_ids.push(id);
        }
        bar.finish_and_clear();
        println!("    {} {} storage lines", "✓".green(), n_highlights);
    }

    // External-boundary markers: a dashed amber band over each line that calls an
    // external contract with no in-scope source (a non-view method whose storage
    // effect is unknowable). Unverified — visually distinct from the proven-write
    // red. Tracked as border ids so a recycle clears them too.
    let mut ext_bands: Vec<(f64, f64, f64, f64)> = Vec::new();
    for node in nodes.iter() {
        if node.external_call_lines.is_empty() || node.png_height == 0 {
            continue;
        }
        let Some(p) = layout.node(&node.id) else {
            continue;
        };
        let geom = silicon::line_geometry(Some(node.font_size));
        let line_h = (p.height * geom.line_height as f64 / node.png_height as f64).max(1.0);
        for line in &node.external_call_lines {
            if *line < node.start_line || *line > node.end_line {
                continue;
            }
            let rendered_index = PATH_HEADER_LINES + (line - node.start_line);
            let y_fraction = geom.line_center_fraction(rendered_index, node.png_height);
            let cy = p.y - p.height / 2.0 + p.height * y_fraction;
            ext_bands.push((p.x, cy, p.width, line_h));
        }
    }
    if !ext_bands.is_empty() {
        let n_ext = ext_bands.len();
        let bar = phase_bar("external boundaries", n_ext);
        let mut ext_tasks = tokio::task::JoinSet::new();
        for (x, y, width, height) in ext_bands {
            let client = client.clone();
            let frame_id = frame_id.clone();
            let bar = bar.clone();
            ext_tasks.spawn(async move {
                let result = client
                    .create_external_marker(&frame_id, x, y, width, height)
                    .await;
                bar.inc(1);
                result
            });
        }
        while let Some(joined) = ext_tasks.join_next().await {
            let id = joined
                .into_report()
                .change_context(EvmMiroError)?
                .change_context(EvmMiroError)?;
            record.border_ids.push(id);
        }
        bar.finish_and_clear();
        println!("    {} {} external boundaries", "✓".green(), n_ext);
    }

    // Connectors, one per call site. Each starts on an invisible marker sitting
    // on the called token, because Miro clips a connector at the boundary of the
    // item it attaches to: anchoring inside the screenshot itself would push the
    // arrow head out to the screenshot's border.
    let back_edges: HashSet<(String, String)> = layout.back_edges.iter().cloned().collect();

    let _ = anchors;

    // Dependencies that reach the SAME caller line from the SAME side share ONE
    // arrow into that line: they all route into a single edge marker, and one stub
    // carries the arrow in. So a line with two calls (both to the right) gets one
    // arrow at its end, not two overlapping ones.
    struct CalleeLink {
        end_id: String,
        /// The x of this arrow's own vertical lane in the gutter, and the y it has to
        /// reach. Miro routes a connector itself — you give it two endpoints and it
        /// picks the path — so the only way to stop every arrow leaving a caller from
        /// turning on the same x is to stop asking Miro to route at all: the arrow is
        /// drawn as straight segments between markers we place, one lane per arrow.
        lane_x: f64,
        end_y: f64,
        /// The callee's graph node id, so the connectors drawn for it can be
        /// attributed to it for surgical removal.
        node_id: String,
        end_anchor: RelativeAnchor,
        end_point: (f64, f64),
        /// This callee's own colour. A caller line can call several functions
        /// (`_usd(_token(x))`); they share one stub, but each branch keeps the colour
        /// of the function it reaches, so two callees never read as one.
        color: String,
    }
    struct PendingGroup {
        token_x: f64,
        token_y: f64,
        edge_x: f64,
        exit_right: bool,
        style: ConnectorStyle,
        callees: Vec<CalleeLink>,
    }

    // One vertical lane per forward arrow, inside the gutter between the two columns
    // it spans. Lanes are ordered by where the arrow starts and where it ends, which
    // is what keeps two arrows that do not have to cross from crossing: for two
    // arrows going the same way, the one starting lower takes the outer lane, so each
    // one's horizontal leg passes outside the other's vertical leg instead of through
    // it. Arrows that do have to cross (their start and end order disagree) cross
    // once, which is unavoidable with one box per function.
    let lane_of: HashMap<(String, String, usize), f64> = {
        let mut per_layer_right: HashMap<usize, f64> = HashMap::new();
        let mut per_layer_left: HashMap<usize, f64> = HashMap::new();
        for placed in &layout.nodes {
            let right = placed.x + placed.width / 2.0;
            let left = placed.x - placed.width / 2.0;
            per_layer_right
                .entry(placed.layer)
                .and_modify(|value| *value = value.max(right))
                .or_insert(right);
            per_layer_left
                .entry(placed.layer)
                .and_modify(|value| *value = value.min(left))
                .or_insert(left);
        }
        // Group the forward edges by the gutter they cross, carrying (start y, end y).
        let mut per_gap: HashMap<usize, Vec<((String, String, usize), f64, f64)>> = HashMap::new();
        for edge in edges.iter() {
            let (Some(from), Some(to)) = (layout.node(&edge.from), layout.node(&edge.to)) else {
                continue;
            };
            if to.layer <= from.layer {
                continue; // a cycle: drawn dashed, and left to Miro
            }
            let start_y = from.y;
            let end_y = to.y;
            per_gap.entry(from.layer).or_default().push((
                (edge.from.clone(), edge.to.clone(), edge.line_in_slice),
                start_y,
                end_y,
            ));
        }
        let mut lanes = HashMap::new();
        for (layer, mut arrows) in per_gap {
            let right = per_layer_right.get(&layer).copied().unwrap_or(0.0);
            let left = per_layer_left
                .get(&(layer + 1))
                .copied()
                .unwrap_or(right + 550.0);
            // Keep the first turn clear of the screenshot border (and of the red or
            // amber band drawn on it), and give each lane five stroke widths of air —
            // narrowing only when the gutter cannot hold them all.
            let margin = 100.0_f64.min((left - right) / 4.0);
            let usable = (left - right - 2.0 * margin).max(0.0);
            let pitch = if arrows.len() > 1 {
                (usable / (arrows.len() - 1) as f64).min(LANE_PITCH)
            } else {
                0.0
            };
            arrows.sort_by(|a, b| {
                let down = |start: f64, end: f64| end >= start;
                let (a_down, b_down) = (down(a.1, a.2), down(b.1, b.2));
                // Arrows going up take the inner lanes, ordered by where they start;
                // arrows going down take the outer ones, the lowest start furthest out.
                a_down
                    .cmp(&b_down)
                    .then_with(|| {
                        let key = |arrow: &((String, String, usize), f64, f64)| {
                            if a_down { (-arrow.1, -arrow.2) } else { (arrow.1, arrow.2) }
                        };
                        key(a).partial_cmp(&key(b)).unwrap_or(std::cmp::Ordering::Equal)
                    })
            });
            for (index, (key, _, _)) in arrows.into_iter().enumerate() {
                lanes.insert(key, right + margin + index as f64 * pitch);
            }
        }
        lanes
    };

    // Colour the ARROWS, by colouring a conflict graph rather than by ranking boxes.
    //
    // What a colour is for is telling two arrows apart where a reader has to compare
    // them, and that is two places only: arrows running side by side in the same
    // gutter, and arrows leaving the same screenshot. Every rank-based rule collided
    // somewhere else — ranking by depth put the same colour on the two arrows most
    // likely to be side by side, ranking by column position left repeats a palette
    // apart that can still end up in neighbouring lanes. So: build the conflicts, walk
    // the arrows in a fixed order (gutter, then lane), and give each the first colour
    // none of its conflicting neighbours already has. Two arrows that reach the SAME
    // function are not in conflict — sharing their colour is what lets a reader
    // recognise a helper drawn in several places.
    let edge_color: Vec<String> = {
        let lane_index: HashMap<usize, (usize, f64)> = edges
            .iter()
            .enumerate()
            .filter_map(|(index, edge)| {
                let from = layout.node(&edge.from)?;
                let lane = lane_of.get(&(edge.from.clone(), edge.to.clone(), edge.line_in_slice))?;
                Some((index, (from.layer, *lane)))
            })
            .collect();
        // A fixed walk order, so the same graph always comes out the same colours.
        let mut order: Vec<usize> = (0..edges.len()).collect();
        order.sort_by(|a, b| {
            let key = |index: &usize| lane_index.get(index).copied().unwrap_or((usize::MAX, 0.0));
            let (la, xa) = key(a);
            let (lb, xb) = key(b);
            la.cmp(&lb)
                .then(xa.partial_cmp(&xb).unwrap_or(std::cmp::Ordering::Equal))
                .then(a.cmp(b))
        });
        // Neighbours in the gutter: the two lanes on either side are what a reader's
        // eye actually puts next to each other.
        const LANE_NEIGHBOURHOOD: usize = 2;
        let mut per_gap: HashMap<usize, Vec<usize>> = HashMap::new();
        for index in &order {
            if let Some((layer, _)) = lane_index.get(index) {
                per_gap.entry(*layer).or_default().push(*index);
            }
        }
        let mut conflicts: Vec<HashSet<usize>> = vec![HashSet::new(); edges.len()];
        for arrows in per_gap.values() {
            for (position, index) in arrows.iter().enumerate() {
                let lower = position.saturating_sub(LANE_NEIGHBOURHOOD);
                let upper = (position + LANE_NEIGHBOURHOOD + 1).min(arrows.len());
                for other in &arrows[lower..upper] {
                    if other != index && edges[*other].to != edges[*index].to {
                        conflicts[*index].insert(*other);
                        conflicts[*other].insert(*index);
                    }
                }
            }
        }
        // Leaving the same screenshot: those the reader compares directly, at the call
        // lines. And ARRIVING at boxes that sit next to each other in the next column:
        // their last horizontal legs run parallel, a stone's throw apart, which is the
        // same comparison at the other end of the arrow.
        for (index, edge) in edges.iter().enumerate() {
            for (other, sibling) in edges.iter().enumerate() {
                if other != index && sibling.from == edge.from && sibling.to != edge.to {
                    conflicts[index].insert(other);
                }
            }
        }
        let mut column: HashMap<usize, Vec<(f64, String)>> = HashMap::new();
        for placed in &layout.nodes {
            column
                .entry(placed.layer)
                .or_default()
                .push((placed.y, placed.id.clone()));
        }
        let mut neighbour_of: HashMap<&str, HashSet<String>> = HashMap::new();
        for boxes in column.values_mut() {
            boxes.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal));
            for (position, (_, id)) in boxes.iter().enumerate() {
                let lower = position.saturating_sub(1);
                let upper = (position + 2).min(boxes.len());
                neighbour_of.insert(
                    id.as_str(),
                    boxes[lower..upper]
                        .iter()
                        .filter(|(_, other)| other != id)
                        .map(|(_, other)| other.clone())
                        .collect(),
                );
            }
        }
        for (index, edge) in edges.iter().enumerate() {
            let Some(neighbours) = neighbour_of.get(edge.to.as_str()) else {
                continue;
            };
            for (other, sibling) in edges.iter().enumerate() {
                if other != index && neighbours.contains(&sibling.to) {
                    conflicts[index].insert(other);
                    conflicts[other].insert(index);
                }
            }
        }
        let mut palette_of: HashMap<usize, Vec<usize>> = HashMap::new();
        let mut colors: Vec<Option<usize>> = vec![None; edges.len()];
        let mut by_callee: HashMap<&str, usize> = HashMap::new();
        for index in order {
            // The same callee keeps one colour wherever it is reached from.
            if let Some(taken) = by_callee.get(edges[index].to.as_str()) {
                colors[index] = Some(*taken);
                continue;
            }
            let used: HashSet<usize> = conflicts[index]
                .iter()
                .filter_map(|other| colors[*other])
                .collect();
            // Each gutter tries the palette in its own SHUFFLED order. The conflict
            // rule alone always reached for colour 0 first, so every column opened on
            // the same hue and a frame read as one repeated pattern — correct, and
            // monotonous. The shuffle is drawn per run rather than derived from the
            // graph: a deploy draws a fresh cluster anyway, so there is nothing to keep
            // stable between runs, and a diagram that looks different each time is the
            // point of asking for it.
            let gutter = lane_index.get(&index).map(|(layer, _)| *layer).unwrap_or(usize::MAX);
            let palette = palette_of.entry(gutter).or_insert_with(|| {
                let mut order: Vec<usize> = (0..DEPTH_COLORS.len()).collect();
                order.shuffle(&mut rand::thread_rng());
                order
            });
            let choice = palette
                .iter()
                .copied()
                .find(|color| !used.contains(color))
                .unwrap_or(index % DEPTH_COLORS.len());
            colors[index] = Some(choice);
            by_callee.insert(edges[index].to.as_str(), choice);
        }
        colors
            .into_iter()
            .map(|color| DEPTH_COLORS[color.unwrap_or(0)].to_string())
            .collect()
    };
    let callee_color: HashMap<String, String> = edges
        .iter()
        .enumerate()
        .map(|(index, edge)| (edge.to.clone(), edge_color[index].clone()))
        .collect();

    let mut groups: HashMap<(String, usize, bool), PendingGroup> = HashMap::new();
    for edge in edges.iter() {
        let edge_key = (edge.from.clone(), edge.to.clone(), edge.line_in_slice);
        let (Some(_start_id), Some(end_id)) =
            (image_ids.get(&edge.from), image_ids.get(&edge.to))
        else {
            continue;
        };
        let (Some(caller), Some(callee)) =
            (by_id.get(edge.from.as_str()), by_id.get(edge.to.as_str()))
        else {
            continue;
        };
        let Some(caller_placed) = layout.node(&edge.from) else {
            continue;
        };
        let callee_x = layout
            .node(&edge.to)
            .map(|placed| placed.x)
            .unwrap_or(caller_placed.x + 1.0);
        let exit_right = callee_x >= caller_placed.x;

        // Where this dependency meets the callee (its side facing the caller).
        let callee_fraction = silicon::line_geometry(Some(callee.font_size))
            .line_center_fraction(SIGNATURE_LINE_INDEX, callee.png_height);
        let end_point = match layout.node(&edge.to) {
            Some(placed) => (
                if exit_right {
                    placed.x - placed.width / 2.0
                } else {
                    placed.x + placed.width / 2.0
                },
                placed.y - placed.height / 2.0 + placed.height * callee_fraction,
            ),
            None => (0.0, 0.0),
        };
        let link = CalleeLink {
            end_id: end_id.clone(),
            lane_x: lane_of.get(&edge_key).copied().unwrap_or(f64::NAN),
            end_y: end_point.1,
            node_id: edge.to.clone(),
            end_anchor: RelativeAnchor::new(if exit_right { 0.0 } else { 1.0 }, callee_fraction),
            end_point,
            color: callee_color
                .get(&edge.to)
                .cloned()
                .unwrap_or_else(|| DEPTH_COLORS[0].to_string()),
        };

        let dashed = back_edges.contains(&(edge.from.clone(), edge.to.clone()));
        let group = groups
            .entry((edge.from.clone(), edge.line_in_slice, exit_right))
            .or_insert_with(|| {
                // The shared arrow anchor for this caller line + side: the arrow lands
                // at the END of the line for a right entry, or its START for a left
                // one, and enters by a straight horizontal stub from the edge.
                let line_index = edge.line_in_slice.saturating_sub(1) + PATH_HEADER_LINES;
                let line_text = caller
                    .rendered_lines
                    .get(line_index)
                    .cloned()
                    .unwrap_or_default();
                let text_width = |text: &str| {
                    silicon::line_end_x(
                        Some(caller.font_size),
                        true,
                        caller.rendered_lines.len(),
                        caller.line_offset,
                        text,
                    ) as f64
                };
                let y_fraction = silicon::line_geometry(Some(caller.font_size))
                    .line_center_fraction(line_index, caller.png_height);
                let token_frac = if caller.png_width > 0 {
                    let width = caller.png_width as f64;
                    if exit_right {
                        let gap = (text_width("a") - text_width("")) * ANCHOR_GAP_CHARS;
                        ((text_width(&line_text) + gap) / width).min(1.0)
                    } else {
                        (text_width("") / width).max(0.0)
                    }
                } else if exit_right {
                    1.0
                } else {
                    0.0
                };
                let frame_edge = if exit_right {
                    caller_placed.x + caller_placed.width / 2.0
                } else {
                    caller_placed.x - caller_placed.width / 2.0
                };
                let raw_token_x =
                    caller_placed.x - caller_placed.width / 2.0 + caller_placed.width * token_frac;
                // A minimum stub so the arrow head always renders (the widest line
                // ends at the edge, which would make a zero-length stub otherwise).
                let min_stub = 60.0_f64;
                // The convergence point normally sits on the frame edge, giving a
                // clear horizontal stub across most of a (shorter) line. But a
                // FULL-WIDTH line — the signature line carrying modifiers, say —
                // ends flush at the image boundary, so several dependencies fanning
                // into it pile up right at the edge, indistinguishable. Detect that
                // (the line reaches the exit edge) and, only then, push the
                // convergence OUT into the gutter so the fan-out clears the
                // screenshot and a single stub crosses in. Short lines and the
                // whole left side are untouched.
                let edge_gap = 200.0_f64;
                let reaches_edge = exit_right && raw_token_x > frame_edge - min_stub * 2.0;
                let edge_x = if reaches_edge {
                    frame_edge + edge_gap
                } else {
                    frame_edge
                };
                let token_x = if exit_right {
                    raw_token_x.min(edge_x - min_stub)
                } else {
                    raw_token_x.max(edge_x + min_stub)
                };
                PendingGroup {
                    token_x,
                    token_y: caller_placed.y - caller_placed.height / 2.0
                        + caller_placed.height * y_fraction,
                    edge_x,
                    exit_right,
                    style: ConnectorStyle {
                        stroke_color: callee_color
                            .get(&edge.to)
                            .cloned()
                            .unwrap_or_else(|| DEPTH_COLORS[0].to_string()),
                        stroke_width: options.stroke_width.to_string(),
                        dashed: false,
                        caption: None,
                        arrow: ArrowEnd::Start,
                    },
                    callees: Vec::new(),
                }
            });
        group.style.dashed = group.style.dashed || dashed;
        group.callees.push(link);
    }

    let bar = phase_bar("drawing connectors", groups.len());
    let mut connector_tasks = tokio::task::JoinSet::new();
    for (_key, group) in groups {
        let client = client.clone();
        let frame_id = frame_id.clone();
        let bar = bar.clone();
        // Attribute this whole group's connectors + markers to its primary callee,
        // so removing that callee later deletes exactly its arrows.
        let owner = group.callees.first().map(|link| link.node_id.clone());
        connector_tasks.spawn(async move {
            let mut markers = Vec::new();
            let mut connectors = Vec::new();

            // A token marker (arrow head, at the line end/start) and an edge marker
            // (at the caller edge). ONE stub carries the arrow in; every dependency
            // routes into the shared edge marker with no head of its own.
            let token_marker = client
                .create_anchor_marker(&frame_id, group.token_x, group.token_y, ANCHOR_MARKER_SIZE)
                .await?;
            markers.push(token_marker.clone());
            let edge_marker = client
                .create_anchor_marker(&frame_id, group.edge_x, group.token_y, ANCHOR_MARKER_SIZE)
                .await?;
            markers.push(edge_marker.clone());

            let (edge_side, token_side) = if group.exit_right {
                (RelativeAnchor::new(0.0, 0.5), RelativeAnchor::new(1.0, 0.5))
            } else {
                (RelativeAnchor::new(1.0, 0.5), RelativeAnchor::new(0.0, 0.5))
            };
            // The shared stub exists for the arrows Miro still routes. A lane-routed
            // arrow reaches the call line by itself, and drawing the stub as well put
            // a second horizontal on the same y — the little hook the reader sees at
            // the caller's edge is that duplicate, plus the elbow Miro adds to join
            // them.
            let lane_routed = group.exit_right && group.callees.iter().all(|link| link.lane_x.is_finite());
            if !lane_routed {
                let mut stub_style = group.style.clone();
                stub_style.arrow = ArrowEnd::End;
                connectors.push(
                    client
                        .create_connector(&edge_marker, edge_side, &token_marker, token_side, stub_style)
                        .await?,
                );
            }

            for link in &group.callees {
                let mut route_style = group.style.clone();
                route_style.arrow = ArrowEnd::None;
                route_style.stroke_color = link.color.clone();
                // Without a lane (a cycle, drawn dashed, or a gutter too narrow to
                // hold one) fall back to the single Miro-routed connector.
                if !group.exit_right || !link.lane_x.is_finite() {
                    connectors.push(
                        client
                            .create_connector(
                                &link.end_id,
                                link.end_anchor,
                                &edge_marker,
                                facing_anchor((group.edge_x, group.token_y), link.end_point),
                                route_style,
                            )
                            .await?,
                    );
                    continue;
                }
                // Three straight legs, each between two points that share an axis, so
                // there is nothing left for Miro to route: out of the caller at the
                // call line, down (or up) this arrow's own lane, into the callee's
                // signature line.
                let lane_top = client
                    .create_anchor_marker(&frame_id, link.lane_x, group.token_y, ANCHOR_MARKER_SIZE)
                    .await?;
                let lane_end = client
                    .create_anchor_marker(&frame_id, link.lane_x, link.end_y, ANCHOR_MARKER_SIZE)
                    .await?;
                markers.push(lane_top.clone());
                markers.push(lane_end.clone());
                // Straight into the call line itself, carrying this arrow's head: the
                // edge marker is not on the path at all.
                let mut head_style = route_style.clone();
                head_style.arrow = ArrowEnd::End;
                connectors.push(
                    client
                        .create_connector(
                            &lane_top,
                            RelativeAnchor::new(0.0, 0.5),
                            &token_marker,
                            RelativeAnchor::new(1.0, 0.5),
                            head_style,
                        )
                        .await?,
                );
                let (top_side, end_side) = if link.end_y >= group.token_y {
                    (RelativeAnchor::new(0.5, 1.0), RelativeAnchor::new(0.5, 0.0))
                } else {
                    (RelativeAnchor::new(0.5, 0.0), RelativeAnchor::new(0.5, 1.0))
                };
                connectors.push(
                    client
                        .create_connector(&lane_top, top_side, &lane_end, end_side, route_style.clone())
                        .await?,
                );
                connectors.push(
                    client
                        .create_connector(
                            &link.end_id,
                            link.end_anchor,
                            &lane_end,
                            RelativeAnchor::new(1.0, 0.5),
                            route_style,
                        )
                        .await?,
                );
            }

            bar.inc(1);
            Ok::<_, error_stack::Report<crate::batbelt::miro::MiroError>>((owner, markers, connectors))
        });
    }

    let mut connector_ids = Vec::new();
    let mut marker_ids = Vec::new();
    let mut callee_owned: HashMap<String, Vec<String>> = HashMap::new();
    while let Some(joined) = connector_tasks.join_next().await {
        let (owner, markers, connectors) = joined
            .into_report()
            .change_context(EvmMiroError)?
            .change_context(EvmMiroError)?;
        if let Some(owner) = owner {
            let bucket = callee_owned.entry(owner).or_default();
            bucket.extend(markers.iter().cloned());
            bucket.extend(connectors.iter().cloned());
        }
        marker_ids.extend(markers);
        connector_ids.extend(connectors);
    }
    bar.finish_and_clear();
    println!("    {} {} connector(s)", "✓".green(), connector_ids.len());

    // Store each screenshot's measured size so a later --refresh-links can reuse
    // the uploaded image without re-rendering.
    record.image_dims = nodes
        .iter()
        .filter(|node| node.kind == NodeKind::Screenshot && image_ids.contains_key(&node.id))
        .map(|node| (node.id.clone(), node.png_width, node.png_height))
        .collect();
    // Positions and per-callee connector ownership for a surgical --refresh-links.
    record.node_positions = nodes
        .iter()
        .filter_map(|node| layout.node(&node.id).map(|placed| (node.id.clone(), placed.x, placed.y)))
        .collect();
    record.callee_connectors = callee_owned.into_iter().collect();
    // Record link cards by the TARGET they stand for (their own node id is a
    // throwaway `\0link{n}` that changes every deploy), so a later --refresh-links
    // recognises them and never re-creates or deletes them.
    record.link_cards = nodes
        .iter()
        .filter_map(|node| match &node.kind {
            NodeKind::Link { .. } => {
                let target_id = node.label.replacen('.', "::", 1);
                image_ids
                    .get(&node.id)
                    .map(|card_id| (target_id, card_id.clone(), String::new()))
            }
            NodeKind::Screenshot => None,
        })
        .collect();
    record.images = image_ids.into_iter().collect();
    record.connector_ids = connector_ids;
    record.marker_ids = marker_ids;
    save_frame_record(&record)?;

    println!("  {}", frame_url.blue());
    // NB: screenshot files are NOT deleted here — they are shared across every frame
    // in this run (see render_and_measure), so the whole figures folder is wiped once
    // at the end of `run()`.
    Ok(())
}

/// Store what a deployment owns, replacing any earlier record for the same
/// entry point.
pub(crate) fn save_frame_record(record: &AutoDeployedFrame) -> Result<()> {
    let record = record.clone();
    EvmBatMetadata::update_metadata(move |metadata| {
        metadata
            .miro
            .auto
            .frames
            .retain(|frame| frame.entry_point != record.entry_point);
        metadata.miro.auto.frames.push(record.clone());
    })
    .change_context(EvmMiroError)
}

/// Anchors for every edge, in the same order as `edges`.
///
/// Call sites that share a line would otherwise start from the exact same
/// point, so they are fanned out slightly inside the line's height.
fn compute_anchors(nodes: &[GraphNode], edges: &[GraphEdge]) -> Vec<RelativeAnchor> {
    let by_id: HashMap<&str, &GraphNode> = nodes.iter().map(|n| (n.id.as_str(), n)).collect();

    // Keyed by line *and* column: two calls on one line now land on their own
    // tokens, so only genuinely identical positions need fanning out.
    let mut occurrences: HashMap<(&str, usize, usize), usize> = HashMap::new();
    // How many calls share a line, which decides whether an anchor can sit past
    // the end of it or has to sit on its own token.
    let mut per_line: HashMap<(&str, usize), usize> = HashMap::new();
    for edge in edges {
        *occurrences
            .entry((edge.from.as_str(), edge.line_in_slice, edge.column))
            .or_insert(0) += 1;
        *per_line
            .entry((edge.from.as_str(), edge.line_in_slice))
            .or_insert(0) += 1;
    }

    let mut seen: HashMap<(&str, usize, usize), usize> = HashMap::new();
    edges
        .iter()
        .map(|edge| {
            let Some(node) = by_id.get(edge.from.as_str()) else {
                return RelativeAnchor::new(1.0, 0.5);
            };
            let key = (edge.from.as_str(), edge.line_in_slice, edge.column);
            let index = seen.entry(key).or_insert(0);
            let position = *index;
            *index += 1;
            let total = occurrences.get(&key).copied().unwrap_or(1);

            let alone_on_line = per_line
                .get(&(edge.from.as_str(), edge.line_in_slice))
                .copied()
                .unwrap_or(1)
                == 1;
            let mut anchor = caller_anchor(node, edge, alone_on_line);
            if total > 1 && node.png_height > 0 {
                // Spread the siblings across the line's own height, so each
                // connector still visibly belongs to that line.
                let line_height = silicon::line_geometry(Some(node.font_size)).line_height as f64;
                let spread = line_height * 0.6 / node.png_height as f64;
                let offset = (position as f64 - (total as f64 - 1.0) / 2.0) * spread
                    / (total as f64 - 1.0).max(1.0);
                anchor = RelativeAnchor::new(anchor.x_fraction, anchor.y_fraction + offset);
            }
            anchor
        })
        .collect()
}

/// Anchor for the connector's caller end, on the line that makes the call.
///
/// Where on that line depends on whether it is the only call there:
///
/// - Alone, the anchor goes past the end of the line, so the arrow head sits on
///   empty background instead of covering the code it points at.
/// - Sharing the line, it goes on the callee's own token, which the AST gives
///   the column of. `MathLib.wadMul(amount, price(asset))` produces one anchor
///   on `wadMul` and another a few columns later on `price`, with no guessing.
///
/// The end of the line is the nicer place to land, so it is used whenever
/// telling two calls apart does not require otherwise.
fn caller_anchor(node: &GraphNode, edge: &GraphEdge, alone_on_line: bool) -> RelativeAnchor {
    let line_index = edge.line_in_slice - 1 + PATH_HEADER_LINES;
    let geometry = silicon::line_geometry(Some(node.font_size));
    let y_fraction = geometry.line_center_fraction(line_index, node.png_height);

    let line_text = node
        .rendered_lines
        .get(line_index)
        .cloned()
        .unwrap_or_default();

    // Prefer the recorded column; fall back to searching the line, and finally
    // to the end of the line if the token is nowhere to be found.
    let start = if line_text
        .get(edge.column..edge.column + edge.symbol.len())
        .map(|found| found == edge.symbol)
        .unwrap_or(false)
    {
        Some(edge.column)
    } else {
        line_text.find(&edge.symbol)
    };

    let text_width = |text: &str| {
        silicon::line_end_x(
            Some(node.font_size),
            true,
            node.rendered_lines.len(),
            node.line_offset,
            text,
        ) as f64
    };

    let x_fraction = match (start, node.png_width) {
        (_, width) if alone_on_line && width > 0 => {
            // One call on the line: land just past the last character, clear of
            // the code.
            let gap = (text_width("a") - text_width("")) * ANCHOR_GAP_CHARS;
            (text_width(&line_text) + gap) / width as f64
        }
        (Some(column), width) if width > 0 => {
            // Aim at the middle of the token so the head visibly sits on it.
            let before = text_width(&line_text[..column]);
            let through = text_width(&line_text[..column + edge.symbol.len()]);
            (before + through) / 2.0 / width as f64
        }
        (_, width) if width > 0 => {
            silicon::line_end_x(
                Some(node.font_size),
                true,
                node.rendered_lines.len(),
                node.line_offset,
                &line_text,
            ) as f64
                / width as f64
        }
        _ => 1.0,
    };

    RelativeAnchor::new(x_fraction, y_fraction)
}

/// BFS over the call graph, keeping every call site with its line.
/// Walk the call graph from an entry point.
///
/// One screenshot per function, however many places call it. Drawing a copy per
/// call site was tried and is worse: `Vault.depositWithReferral` came to 77
/// screenshots for 27 distinct functions, with `MathLib.mulDiv` — three lines of
/// arithmetic — repeated fourteen times. Two thirds of that diagram carried no
/// information.
/// Is this contract one the auditor said they already know?
///
/// The density of a diagram is not evenly useful. A fixed-point math library called
/// from thirty places is thirty boxes that say the same thing, and the reader knew
/// what `mulDiv` did before they opened the board. Naming it here removes its boxes
/// and its arrows — not the calls to it, which stay visible in the callers' own
/// screenshots, so nothing about the audited code is hidden. Deploy it as an entry
/// point of its own on the day the question is actually about it.
fn ignored_contract(options: &AutoDeployOptions, contract: &ContractMetadata) -> bool {
    options.ignore_contracts.iter().any(|pattern| {
        let pattern = pattern.trim();
        !pattern.is_empty()
            && (contract.name == pattern || contract.file_path.contains(pattern))
    })
}

fn build_graph(
    metadata: &EvmBatMetadata,
    contract_name: &str,
    function_name: &str,
    // The file the root contract lives in, so a name shared by several contracts (three
    // vendored copies of `BeaconProxy`) resolves to the one that was actually selected.
    root_file: &str,
    options: &AutoDeployOptions,
) -> Result<(
    Vec<GraphNode>,
    Vec<GraphEdge>,
    Vec<crate::batbelt::evm::metadata::bat_metadata::UnresolvedCall>,
)> {
    let Some((root_contract, root_function)) =
        find_function(metadata, contract_name, root_file, function_name, None)
    else {
        return Ok((Vec::new(), Vec::new(), Vec::new()));
    };

    // Method name → in-scope, non-stub contracts that directly define it, built
    // ONCE so resolve_call's unique-definer fallback is O(1) per call site instead
    // of scanning every contract each time.
    let mut definer_map: HashMap<String, Vec<String>> = HashMap::new();
    for contract in &metadata.contracts {
        if contract.contract_type == EvmContractType::Interface {
            continue;
        }
        for function in &contract.functions {
            if !function.is_stub {
                definer_map
                    .entry(function.name.clone())
                    .or_default()
                    .push(contract.name.clone());
            }
        }
    }

    // Whether a call changes state is a fact about the code, so the reachability walk
    // always crosses into `lib/` — independently of whether this deploy draws it.
    let write_options = options.clone();
    let mut write_definer_map: HashMap<String, Vec<String>> = HashMap::new();
    for contract in &metadata.contracts {
        if contract.contract_type == EvmContractType::Interface {
            continue;
        }
        for function in &contract.functions {
            if !function.is_stub {
                write_definer_map
                    .entry(function.name.clone())
                    .or_default()
                    .push(contract.name.clone());
            }
        }
    }
    let mut write_memo: HashMap<String, bool> = HashMap::new();

    let mut nodes: Vec<GraphNode> = Vec::new();
    let mut edges: Vec<GraphEdge> = Vec::new();
    // Interface calls in this tree still needing an AI resolution (see `resolve`).
    // Reads through an interface cast with several in-scope implementations, left out of
    // the graph: `(interface, method) → (candidates, call locations)`, printed once each.
    let mut left_out_reads: std::collections::BTreeMap<(String, String), (Vec<String>, Vec<String>)> =
        std::collections::BTreeMap::new();
    let mut unresolved: Vec<crate::batbelt::evm::metadata::bat_metadata::UnresolvedCall> =
        Vec::new();
    // One node per function: a second call to the same function points at the
    // node that already exists.
    let mut drawn: HashMap<String, String> = HashMap::new();

    let root_id = overload_node_key(root_contract, &root_function);
    drawn.insert(root_id.clone(), root_id.clone());
    let mut root_node = make_node(
        root_id.clone(),
        format!("{contract_name}.{function_name}"),
        root_contract,
        &root_function,
        0,
        doc_lines_above(options, &root_contract.file_path, root_function.line),
    );
    root_node.leads_to_write = leads_to_write(
        metadata,
        root_contract,
        &root_function,
        &write_options,
        &write_definer_map,
        &mut write_memo,
        &mut HashSet::new(),
    );
    nodes.push(root_node);

    // Depth-first, so siblings stay in source order and each subtree is built
    // before the next one starts — which is the order the layout wants. `line`
    // pins WHICH overload this node is, so the re-read below lands on the same one.
    struct Pending {
        node_id: String,
        contract: String,
        // The file of that exact contract. A name alone is not an identity once `lib/`
        // vendors several copies of a library.
        file: String,
        function: String,
        line: usize,
        depth: usize,
    }

    let mut stack = vec![Pending {
        node_id: root_id,
        contract: root_contract.name.clone(),
        file: root_contract.file_path.clone(),
        function: function_name.to_string(),
        line: root_function.line,
        depth: 0,
    }];

    while let Some(current) = stack.pop() {
        // The contract that defines the function, which is where its source is.
        // Pin the exact overload by line so a re-read never drifts to a sibling.
        let Some((contract, function)) =
            find_function_at(
                metadata,
                &current.contract,
                &current.file,
                &current.function,
                current.line,
            )
        else {
            continue;
        };
        let slice = read_slice(
            &contract.file_path,
            function.line,
            function_end(&function, contract),
        );
        // `slice` is the body, so every line found in it is relative to the declaration.
        // The screenshot may start higher (the NatSpec), so shift the anchors by exactly
        // the number of documentation lines drawn above this caller.
        let doc_shift = doc_lines_above(options, &contract.file_path, function.line);

        let mut children: Vec<Pending> = Vec::new();
        // Lines in THIS function whose call reaches a storage write, collected while the
        // calls are resolved and written back onto the node once the loop is done.
        let mut caller_write_calls: Vec<(usize, String, String)> = Vec::new();
        // Lines whose call leaves the drawn graph towards `lib/` code that can mutate.
        let mut lib_boundary_lines: Vec<usize> = Vec::new();

        // Modifiers count as dependencies; their call site is the line of the
        // signature where the modifier name appears.
        for modifier_name in &function.modifiers {
            // A base constructor invoked in a constructor's header (`BeaconProxy(beacon,
            // data)`) is parsed as a modifier too. It is not one, so it resolves to nothing
            // here and is drawn below, as the constructor call it really is.
            let Some((owner, definition)) =
                find_modifier(metadata, &current.contract, &current.file, modifier_name)
            else {
                continue;
            };
            let line_in_slice = slice
                .iter()
                .position(|line| line_has_token(line, modifier_name))
                .map(|index| index + 1)
                .unwrap_or(1);
            let target_id = node_key(&owner.name, &definition.name);
            edges.push(GraphEdge {
                from: current.node_id.clone(),
                to: target_id.clone(),
                line_in_slice: line_in_slice + doc_shift,
                column: slice
                    .get(line_in_slice - 1)
                    .and_then(|line| line.find(modifier_name.as_str()))
                    .unwrap_or(0),
                symbol: modifier_name.clone(),
            });
            if drawn.insert(target_id.clone(), target_id.clone()).is_none() {
                nodes.push(make_modifier_node(
                    target_id,
                    owner,
                    &definition,
                    current.depth + 1,
                    doc_lines_above(options, &owner.file_path, definition.line),
                ));
            }
        }

        for call in extract_call_sites_from_source(&body_only(&slice).join("\n")) {
            let arity = (call.arg_count != usize::MAX).then_some(call.arg_count);

            // Mark the calling line whenever the call reaches a write, BEFORE deciding
            // whether the callee is drawn. A target in `lib/` is dropped from the graph
            // without `--include-external`, but the state change it causes is still real,
            // and this line is the last place in the frame that can show it.
            if let Some((reached_contract, reached_function)) = resolve_call(
                metadata,
                contract,
                &call.name,
                arity,
                &write_options,
                &write_definer_map,
            ) {
                if leads_to_write(
                    metadata,
                    reached_contract,
                    &reached_function,
                    &write_options,
                    &write_definer_map,
                    &mut write_memo,
                    &mut HashSet::new(),
                ) {
                    // Empty when the callee is dropped from the graph (a `lib/` target
                    // without `--include-external`): nothing downstream can carry the
                    // mark, so this line keeps it.
                    let callee_id = resolve_call(
                        metadata,
                        contract,
                        &call.name,
                        arity,
                        options,
                        &definer_map,
                    )
                    .map(|(c, f)| overload_node_key(c, &f))
                    .unwrap_or_default();
                    caller_write_calls.push((
                        function.line + call.line - 1,
                        call.symbol.clone(),
                        callee_id,
                    ));
                }
            }

            let Some((target_contract, target_function)) =
                resolve_call(metadata, contract, &call.name, arity, options, &definer_map)
            else {
                // An interface cast with several implementations and no recorded
                // resolution. Guessing would draw code that may never run here, so:
                // - if any candidate can change state, it goes on the list the deploy
                //   stops on, the same list `bat-cli resolve` works through;
                // - if none can, it is a read — stopping a deploy for every
                //   `IERC20(token).balanceOf` is the noise the scan already prunes — so
                //   say it was left out and how to bring it in, and carry on.
                // A call that resolves only because `lib/` was allowed in: the target is
                // dependency code this frame does not draw. A non-view one can change state
                // (`SafeERC20.safeTransferFrom` moves tokens), and it is invisible otherwise
                // — the write happens in a contract that is not even in the repository.
                if let Some((lib_contract, lib_function)) = resolve_call(
                    metadata,
                    contract,
                    &call.name,
                    arity,
                    &write_options,
                    &write_definer_map,
                ) {
                    let read_only = matches!(
                        lib_function.mutability,
                        crate::batbelt::evm::types::EvmMutability::View
                            | crate::batbelt::evm::types::EvmMutability::Pure
                    );
                    if lib_contract.external && !read_only {
                        lib_boundary_lines.push(function.line + call.line - 1);
                    }
                }

                if let Some((receiver, method)) = call.name.split_once('.') {
                    if let Some(type_name) = receiver.strip_suffix("()") {
                        let candidates = cast_implementations(
                            metadata,
                            contract,
                            type_name,
                            method,
                            arity,
                        );
                        if candidates.len() > 1 && !metadata.resolutions.contains_key(type_name) {
                            let names: Vec<String> =
                                candidates.iter().map(|(c, _)| c.name.clone()).collect();
                            let writes = candidates.iter().any(|(c, f)| {
                                leads_to_write(
                                    metadata,
                                    c,
                                    f,
                                    &write_options,
                                    &write_definer_map,
                                    &mut write_memo,
                                    &mut HashSet::new(),
                                )
                            });
                            if writes {
                                unresolved.push(
                                    crate::batbelt::evm::metadata::bat_metadata::UnresolvedCall {
                                        receiver: receiver.to_string(),
                                        method: method.to_string(),
                                        inferred_type: type_name.to_string(),
                                        candidates: names,
                                        assigned_in: Vec::new(),
                                    },
                                );
                            } else {
                                let entry = left_out_reads
                                    .entry((type_name.to_string(), method.to_string()))
                                    .or_insert_with(|| (names.clone(), Vec::new()));
                                entry
                                    .1
                                    .push(format!("{}:{}", contract.name, function.line + call.line - 1));
                            }
                        }
                    }
                }
                continue;
            };
            if ignored_contract(options, target_contract) {
                continue;
            }
            let target_id = overload_node_key(target_contract, &target_function);
            if target_id == current.node_id {
                continue; // a function calling itself needs no arrow
            }

            edges.push(GraphEdge {
                from: current.node_id.clone(),
                to: target_id.clone(),
                line_in_slice: call.line + doc_shift,
                column: call.column,
                symbol: call.symbol.clone(),
            });


            // Seen before: the arrow points at the node already drawn, and there
            // is nothing left to expand.
            if drawn.insert(target_id.clone(), target_id.clone()).is_some() {
                continue;
            }
            let mut child = make_node(
                target_id.clone(),
                format!("{}.{}", target_contract.name, target_function.name),
                target_contract,
                &target_function,
                current.depth + 1,
                doc_lines_above(options, &target_contract.file_path, target_function.line),
            );
            child.leads_to_write = leads_to_write(
                metadata,
                target_contract,
                &target_function,
                &write_options,
                &write_definer_map,
                &mut write_memo,
                &mut HashSet::new(),
            );
            nodes.push(child);
            children.push(Pending {
                node_id: target_id,
                contract: target_contract.name.clone(),
                file: target_contract.file_path.clone(),
                function: target_function.name.clone(),
                line: target_function.line,
                depth: current.depth + 1,
            });
        }

        // A constructor runs its base contracts' constructors before its own body, whether
        // the header invokes them (`BeaconProxy(beacon, data)`) or not. Without this a
        // constructor like `FLAMMProxy`'s — empty, everything it does lives in the base —
        // drew as one lonely screenshot with nothing below it.
        if function.is_constructor {
            let header_end = slice
                .iter()
                .position(|line| line.contains('{'))
                .unwrap_or(0);
            for (base, constructor) in base_constructors(metadata, contract) {
                if ignored_contract(options, base) {
                    continue;
                }
                // Anchor on the header token naming the base when it is invoked there;
                // an implicit base constructor has no call site, so the signature.
                let line_in_slice = slice
                    .iter()
                    .take(header_end + 1)
                    .position(|line| line_has_token(line, &base.name))
                    .map(|index| index + 1)
                    .unwrap_or(1);
                let target_id = overload_node_key(base, &constructor);
                if target_id == current.node_id {
                    continue;
                }
                edges.push(GraphEdge {
                    from: current.node_id.clone(),
                    to: target_id.clone(),
                    line_in_slice: line_in_slice + doc_shift,
                    column: slice
                        .get(line_in_slice - 1)
                        .and_then(|line| line.find(base.name.as_str()))
                        .unwrap_or(0),
                    symbol: base.name.clone(),
                });
                if drawn.insert(target_id.clone(), target_id.clone()).is_some() {
                    continue;
                }
                let mut child = make_node(
                    target_id.clone(),
                    format!("{}.{}", base.name, constructor.name),
                    base,
                    &constructor,
                    current.depth + 1,
                    doc_lines_above(options, &base.file_path, constructor.line),
                );
                child.leads_to_write = leads_to_write(
                    metadata,
                    base,
                    &constructor,
                    &write_options,
                    &write_definer_map,
                    &mut write_memo,
                    &mut HashSet::new(),
                );
                nodes.push(child);
                children.push(Pending {
                    node_id: target_id,
                    contract: base.name.clone(),
                    file: base.file_path.clone(),
                    function: constructor.name.clone(),
                    line: constructor.line,
                    depth: current.depth + 1,
                });
            }
        }

        // Cross-contract interface calls: follow the ones the AI has resolved (so the
        // concrete downstream function — and its storage writes — appear and recurse),
        // and collect the rest as needing a resolution.
        //
        // Two sources feed the same drawing: interface calls the AI resolved with
        // `bat-cli resolve`, and calls the scan already pinned by type (`resolved_calls`),
        // such as `$.priceFeed.pegOk` — a storage-struct field the deploy cannot type
        // itself. The third element is the originating unresolved call, if any.
        let mut followed: Vec<(String, String, Option<&crate::batbelt::evm::metadata::bat_metadata::UnresolvedCall>)> =
            Vec::new();
        for u in &function.unresolved_calls {
            let concrete = if u.inferred_type.is_empty() {
                None
            } else {
                metadata.resolutions.get(&u.inferred_type)
            };
            match concrete {
                Some(concrete) => followed.push((u.method.clone(), concrete.clone(), Some(u))),
                None => unresolved.push(u.clone()),
            }
        }
        for typed in &function.resolved_calls {
            followed.push((typed.method.clone(), typed.contract.clone(), None));
        }
        for (method, concrete, origin) in &followed {
            let Some((tc, tf)) =
                find_function(metadata, concrete, &contract.file_path, method, None)
            else {
                // A resolution is set but its method isn't there — still unresolved.
                if let Some(u) = origin {
                    unresolved.push((*u).clone());
                }
                continue;
            };
            // A resolution that lands on a virtual/interface stub is redirected to
            // its concrete override; a pure declaration with none is dropped.
            let Some((tc, tf)) = destub(metadata, (tc, tf), options) else {
                continue;
            };
            if ignored_contract(options, tc) {
                continue;
            }
            let target_id = overload_node_key(tc, &tf);
            if target_id == current.node_id {
                continue;
            }
            // A plain state-variable receiver (`debtToken.mint`) is typed by the deploy too,
            // and already has its arrow from the call-site pass; don't draw it twice.
            if origin.is_none()
                && edges
                    .iter()
                    .any(|edge| edge.from == current.node_id && edge.to == target_id)
            {
                continue;
            }
            let line_in_slice = slice
                .iter()
                .position(|l| line_has_call(l, method))
                .map(|i| i + 1)
                .unwrap_or(1);
            edges.push(GraphEdge {
                from: current.node_id.clone(),
                to: target_id.clone(),
                line_in_slice: line_in_slice + doc_shift,
                column: slice
                    .get(line_in_slice - 1)
                    .and_then(|l| l.find(method.as_str()))
                    .unwrap_or(0),
                symbol: method.clone(),
            });
            if leads_to_write(
                metadata,
                tc,
                &tf,
                &write_options,
                &write_definer_map,
                &mut write_memo,
                &mut HashSet::new(),
            ) {
                caller_write_calls.push((
                    function.line + line_in_slice - 1,
                    method.clone(),
                    target_id.clone(),
                ));
            }
            if drawn.insert(target_id.clone(), target_id.clone()).is_some() {
                continue;
            }
            let mut child = make_node(
                target_id.clone(),
                format!("{}.{}", tc.name, tf.name),
                tc,
                &tf,
                current.depth + 1,
                doc_lines_above(options, &tc.file_path, tf.line),
            );
            child.leads_to_write = leads_to_write(
                metadata,
                tc,
                &tf,
                &write_options,
                &write_definer_map,
                &mut write_memo,
                &mut HashSet::new(),
            );
            nodes.push(child);
            children.push(Pending {
                node_id: target_id,
                contract: tc.name.clone(),
                file: tc.file_path.clone(),
                function: tf.name.clone(),
                line: tf.line,
                depth: current.depth + 1,
            });
        }

        // Calls to external contracts with no in-scope source: flag the lines that
        // reach a non-view method (a `view`/`pure` one is compiler-guaranteed not to
        // mutate, so it is never a state-change risk). Located on the caller's node.
        let mut external_lines: Vec<usize> = std::mem::take(&mut lib_boundary_lines);
        for uec in &function.unknown_external_calls {
            let read_only = find_function(
                metadata,
                &uec.inferred_type,
                &contract.file_path,
                &uec.method,
                None,
            )
                .map(|(_, f)| {
                    matches!(
                        f.mutability,
                        crate::batbelt::evm::types::EvmMutability::View
                            | crate::batbelt::evm::types::EvmMutability::Pure
                    )
                })
                .unwrap_or(false);
            if read_only {
                continue;
            }
            if let Some(pos) = slice.iter().position(|l| line_has_call(l, &uec.method)) {
                // The scan finds implementers by inheritance only, so a contract that
                // matches the interface without declaring `is <interface>` leaves the call
                // listed here even though the call-site pass above drew its arrow into
                // in-scope code. That call doesn't leave the audited code: no amber.
                let drawn_in_scope = edges.iter().any(|e| {
                    e.from == current.node_id
                        && e.symbol == uec.method
                        && e.line_in_slice == pos + 1 + doc_shift
                });
                if drawn_in_scope {
                    continue;
                }
                external_lines.push(function.line + pos);
            }
        }
        if !caller_write_calls.is_empty() {
            caller_write_calls.sort_unstable();
            caller_write_calls.dedup();
            if let Some(node) = nodes.iter_mut().find(|n| n.id == current.node_id) {
                node.write_call_lines = caller_write_calls;
            }
        }

        if !external_lines.is_empty() {
            external_lines.sort_unstable();
            external_lines.dedup();
            if let Some(node) = nodes.iter_mut().find(|n| n.id == current.node_id) {
                node.external_call_lines = external_lines;
            }
        }

        // Reversed, because popping a stack undoes the order.
        for child in children.into_iter().rev() {
            stack.push(child);
        }
    }

    // Surface the WHOLE tree's unresolved calls at once (not just the drawn frontier):
    // follow each unambiguous hop — a resolved interface, or a lone candidate — into
    // its function and collect ITS unresolved too, so the AI can resolve in one pass.
    let unresolved = expand_unresolved(metadata, unresolved);

    // De-sharing (duplicating a shared function per caller) is decided AFTER render,
    // in `deploy_one`, where a preliminary layout tells which shared nodes actually
    // sit far from a caller and would cross — see `duplicate_crossing_shared`. A
    // blanket duplication here would repeat functions whose callers are adjacent
    // (no crossing) for nothing.
    for ((type_name, method), (candidates, locations)) in &left_out_reads {
        println!(
            "  {} {}.{}() is a read with {} implementations ({}), left out at {} — {} draws it",
            "note:".yellow(),
            type_name,
            method,
            candidates.len(),
            candidates.join(", "),
            locations.join(", "),
            format!("bat-cli resolve {type_name} <CONTRACT>").green()
        );
    }

    Ok((nodes, edges, unresolved))
}

/// Transitively collect every unresolved interface call reachable from `seed`,
/// descending through the unambiguous hops (a resolution, or a single candidate).
fn expand_unresolved(
    metadata: &EvmBatMetadata,
    seed: Vec<crate::batbelt::evm::metadata::bat_metadata::UnresolvedCall>,
) -> Vec<crate::batbelt::evm::metadata::bat_metadata::UnresolvedCall> {
    let mut out = Vec::new();
    let mut seen_calls: HashSet<(String, String)> = HashSet::new();
    let mut visited_fns: HashSet<(String, String)> = HashSet::new();
    let mut frontier = seed;
    while let Some(u) = frontier.pop() {
        if !seen_calls.insert((u.receiver.clone(), u.method.clone())) {
            continue;
        }
        // Pick a single target to descend into: a recorded resolution, else a lone
        // candidate. Ambiguous (multi-candidate) calls are listed, not descended.
        let target = if !u.inferred_type.is_empty() {
            metadata.resolutions.get(&u.inferred_type).cloned()
        } else {
            None
        }
        .or_else(|| {
            if u.candidates.len() == 1 {
                Some(u.candidates[0].clone())
            } else {
                None
            }
        });
        if let Some(contract) = target {
            if visited_fns.insert((contract.clone(), u.method.clone())) {
                // No caller file survives into this frontier, so an ambiguous name keeps
                // the old first-match behaviour here.
                if let Some((_, f)) = find_function(metadata, &contract, "", &u.method, None) {
                    for du in &f.unresolved_calls {
                        frontier.push(du.clone());
                    }
                }
            }
        }
        out.push(u);
    }
    out.sort_by(|a, b| (&a.receiver, &a.method).cmp(&(&b.receiver, &b.method)));
    out
}

/// Identity of a function, used to detect recursion along a path.
fn node_key(contract: &str, function: &str) -> String {
    format!("{contract}::{function}")
}


fn node_id(contract: &str, function: &str) -> String {
    format!("{contract}::{function}")
}

fn make_node(
    id: String,
    label: String,
    contract: &ContractMetadata,
    function: &FunctionMetadata,
    depth: usize,
    doc_lines: usize,
) -> GraphNode {
    GraphNode {
        kind: NodeKind::Screenshot,
        id,
        label,
        file_path: contract.file_path.clone(),
        // The screenshot starts at the NatSpec when `--with-documentation` asked for it,
        // so the render key, the line gutter and every absolute-line lookup all agree on
        // where the image begins.
        start_line: function.line - doc_lines,
        end_line: function_end(function, contract),
        depth,
        // Rendered at the reference font (so one render serves every depth); the
        // depth's smaller look comes from `scale`, not a separate render.
        font_size: REFERENCE_FONT,
        scale: scale_for_depth(depth),
        png_path: String::new(),
        png_width: 0,
        png_height: 0,
        rendered_lines: Vec::new(),
        line_offset: 0,
        writes_storage: !function.storage_writes.is_empty(),
        write_lines: function
            .storage_write_sites
            .iter()
            .map(|s| (s.line, s.name.clone()))
            .collect(),
        external_call_lines: Vec::new(),
        leads_to_write: false,
        write_call_lines: Vec::new(),
    }
}

fn is_ident_byte(byte: u8) -> bool {
    byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'$'
}

/// True when `token` appears in `line` as a WHOLE identifier, so `mint` does not
/// match inside `mintedAlmShares`.
fn line_has_token(line: &str, token: &str) -> bool {
    let bytes = line.as_bytes();
    let mut from = 0;
    while let Some(rel) = line[from..].find(token) {
        let start = from + rel;
        let end = start + token.len();
        let before_ok = start == 0 || !is_ident_byte(bytes[start - 1]);
        let after_ok = end >= bytes.len() || !is_ident_byte(bytes[end]);
        if before_ok && after_ok {
            return true;
        }
        from = start + 1;
    }
    false
}

/// Like [`line_has_token`] but the identifier must be a CALL — followed (after
/// optional spaces) by `(`. So `mint` matches `collVault.mint(…)` on line 362 but
/// not the `mintedAlmShares` declaration on line 351.
fn line_has_call(line: &str, method: &str) -> bool {
    let bytes = line.as_bytes();
    let mut from = 0;
    while let Some(rel) = line[from..].find(method) {
        let start = from + rel;
        let end = start + method.len();
        let before_ok = start == 0 || !is_ident_byte(bytes[start - 1]);
        let after_ident_ok = end >= bytes.len() || !is_ident_byte(bytes[end]);
        let mut cursor = end;
        while cursor < bytes.len() && (bytes[cursor] == b' ' || bytes[cursor] == b'\t') {
            cursor += 1;
        }
        let is_call = cursor < bytes.len() && bytes[cursor] == b'(';
        if before_ok && after_ident_ok && is_call {
            return true;
        }
        from = start + 1;
    }
    false
}

fn make_modifier_node(
    id: String,
    contract: &ContractMetadata,
    definition: &crate::batbelt::evm::types::EvmModifierDef,
    depth: usize,
    doc_lines: usize,
) -> GraphNode {
    let end_line = if definition.end_line > 0 {
        definition.end_line
    } else {
        definition.line + 6
    };
    GraphNode {
        kind: NodeKind::Screenshot,
        id,
        label: format!("{}.{} (modifier)", contract.name, definition.name),
        file_path: contract.file_path.clone(),
        start_line: definition.line - doc_lines,
        end_line,
        depth,
        font_size: REFERENCE_FONT,
        scale: scale_for_depth(depth),
        png_path: String::new(),
        png_width: 0,
        png_height: 0,
        rendered_lines: Vec::new(),
        line_offset: 0,
        // A modifier that writes storage (e.g. `initializer`) is marked like any
        // state-mutating node.
        writes_storage: !definition.storage_writes.is_empty(),
        write_lines: definition
            .storage_write_sites
            .iter()
            .map(|(name, line)| (*line, name.clone()))
            .collect(),
        external_call_lines: Vec::new(),
        leads_to_write: false,
        write_call_lines: Vec::new(),
    }
}

fn function_end(function: &FunctionMetadata, contract: &ContractMetadata) -> usize {
    if function.end_line > 0 {
        return function.end_line;
    }
    // Fall back to a brace scan when sonar did not record the end line.
    let content = std::fs::read_to_string(&contract.file_path).unwrap_or_default();
    let lines: Vec<&str> = content.lines().collect();
    let mut depth = 0i32;
    let mut started = false;
    for (index, line) in lines.iter().enumerate().skip(function.line.saturating_sub(1)) {
        for character in line.chars() {
            match character {
                '{' => {
                    depth += 1;
                    started = true;
                }
                '}' => depth -= 1,
                _ => {}
            }
        }
        if started && depth <= 0 {
            return index + 1;
        }
    }
    function.line
}

/// Find a function, and the contract that actually **defines** it.
///
/// Returning the contract it was reached through instead is wrong for anything
/// inherited: `Settlement.settle` is defined in `Pipeline`, so reading its source
/// out of `Settlement.sol` lands on unrelated lines, and the screenshot comes out
/// empty. That silently truncated every diagram at the first inherited call.
///
/// `from_file` is the file doing the naming: a contract name is resolved through ITS
/// imports (see `EvmBatMetadata::contract_in_scope`), and each base contract through the
/// imports of the contract that inherits it. Pass `""` when there is no such file.
fn find_function<'a>(
    metadata: &'a EvmBatMetadata,
    contract_name: &str,
    from_file: &str,
    function_name: &str,
    arg_count: Option<usize>,
) -> Option<(&'a ContractMetadata, FunctionMetadata)> {
    let contract = metadata.contract_in_scope(contract_name, from_file)?;
    let overloads: Vec<&FunctionMetadata> =
        contract.functions.iter().filter(|f| f.name == function_name).collect();
    if !overloads.is_empty() {
        // With several same-named overloads, pick the one whose parameter count
        // matches the call site; otherwise (or when the arity is unknown) keep the
        // first, which preserves the old single-definition behaviour exactly.
        let chosen = match arg_count {
            Some(n) if overloads.len() > 1 => overloads
                .iter()
                .find(|f| f.params.len() == n)
                .copied()
                .unwrap_or(overloads[0]),
            _ => overloads[0],
        };
        return Some((contract, chosen.clone()));
    }
    for base in &contract.base_contracts {
        if let Some(found) =
            find_function(metadata, base, &contract.file_path, function_name, arg_count)
        {
            return Some(found);
        }
    }
    None
}

/// Resolve to the SPECIFIC overload defined at `line` (walking base contracts),
/// so the DFS re-reads the same overload an edge was built for — not just the
/// first one sharing the name.
fn find_function_at<'a>(
    metadata: &'a EvmBatMetadata,
    contract_name: &str,
    from_file: &str,
    function_name: &str,
    line: usize,
) -> Option<(&'a ContractMetadata, FunctionMetadata)> {
    let contract = metadata.contract_in_scope(contract_name, from_file)?;
    if let Some(function) = contract
        .functions
        .iter()
        .find(|f| f.name == function_name && f.line == line)
    {
        return Some((contract, function.clone()));
    }
    for base in &contract.base_contracts {
        if let Some(found) =
            find_function_at(metadata, base, &contract.file_path, function_name, line)
        {
            return Some(found);
        }
    }
    None
}

/// Node id for a function, distinguishing overloads: when a contract defines the
/// same name several times, the id carries the definition line so each overload is
/// its own node (otherwise both collapse and a wrapper→overload call looks like a
/// self-call and is pruned). A single-definition function keeps the plain id, so
/// non-overloaded graphs are byte-identical to before.
fn overload_node_key(contract: &ContractMetadata, function: &FunctionMetadata) -> String {
    let overloaded = contract.functions.iter().filter(|f| f.name == function.name).count() > 1;
    if overloaded {
        format!("{}@{}", node_key(&contract.name, &function.name), function.line)
    } else {
        node_key(&contract.name, &function.name)
    }
}

/// The constructors that run before `contract`'s own, nearest first along each base.
///
/// A base without a constructor of its own still runs ITS bases' constructors, so the walk
/// descends through it. Each base name is resolved through the imports of the contract that
/// inherits it, so a vendored copy of the library that nobody imports is never picked.
fn base_constructors<'a>(
    metadata: &'a EvmBatMetadata,
    contract: &ContractMetadata,
) -> Vec<(&'a ContractMetadata, FunctionMetadata)> {
    let mut found: Vec<(&'a ContractMetadata, FunctionMetadata)> = Vec::new();
    let mut seen: HashSet<(String, String)> = HashSet::new();
    let mut pending: Vec<(String, String)> = contract
        .base_contracts
        .iter()
        .rev()
        .map(|base| (base.clone(), contract.file_path.clone()))
        .collect();
    while let Some((name, from_file)) = pending.pop() {
        let Some(base) = metadata.contract_in_scope(&name, &from_file) else {
            continue;
        };
        if !seen.insert((base.name.clone(), base.file_path.clone())) {
            continue;
        }
        if let Some(constructor) = base.functions.iter().find(|f| f.is_constructor) {
            found.push((base, constructor.clone()));
        } else {
            for grand in base.base_contracts.iter().rev() {
                pending.push((grand.clone(), base.file_path.clone()));
            }
        }
    }
    found
}

fn find_modifier<'a>(
    metadata: &'a EvmBatMetadata,
    contract_name: &str,
    from_file: &str,
    modifier_name: &str,
) -> Option<(&'a ContractMetadata, crate::batbelt::evm::types::EvmModifierDef)> {
    let contract = metadata.contract_in_scope(contract_name, from_file)?;
    if let Some(definition) = contract.modifiers.iter().find(|m| m.name == modifier_name) {
        return Some((contract, definition.clone()));
    }
    for base in &contract.base_contracts {
        if let Some(found) = find_modifier(metadata, base, &contract.file_path, modifier_name) {
            return Some(found);
        }
    }
    None
}

/// Map a call site name to the contract and function it refers to.
///
/// Handles `helper(...)` (same contract or inherited), `Lib.fn(...)`,
/// `super.fn(...)` and `stateVar.fn(...)` where the variable's declared type is
/// an interface with a known implementation.
/// The call lines that actually get a mark on this frame.
///
/// One state change must produce ONE mark. A chain like
/// `_increaseDebt → DebtToken.mint → ERC20._mint → ERC20._update` would otherwise paint
/// every hop for the single write in `_update`, and counting the red marks on a frame
/// would tell the reader nothing.
///
/// So a call line keeps its mark only when the callee is NOT a screenshot on this frame:
/// then this line is the deepest the frame gets to the write, and the last place able to
/// show it. When the callee IS drawn, it carries the mark instead — its own assignment, or
/// its own outgoing call — which is nearer to where the change really happens. A callee
/// cut out to another frame (a link card) counts as absent, since the mark belongs to the
/// frame that draws it.
fn surviving_write_calls<'a>(
    node: &'a GraphNode,
    drawn_screens: &HashSet<&str>,
) -> impl Iterator<Item = &'a (usize, String, String)> {
    let drawn: HashSet<String> = drawn_screens.iter().map(|id| id.to_string()).collect();
    node.write_call_lines
        .iter()
        .filter(move |(_, _, callee)| !drawn.contains(callee))
}

/// Node ids drawn as source on this frame, which is what decides who owns a mark.
fn drawn_screen_ids(nodes: &[GraphNode]) -> HashSet<&str> {
    nodes
        .iter()
        .filter(|node| node.kind == NodeKind::Screenshot)
        .map(|node| node.id.as_str())
        .collect()
}

/// Does this function reach a storage write, directly or through anything it calls?
///
/// A node is drawn red only when it holds the assignment itself, and that hides real state
/// changes: `PositionManager._increaseDebt` calls `debtToken.mint`, which calls
/// `ERC20._mint`, which in OpenZeppelin v5 only validates and delegates to `_update` —
/// the single function in the chain that assigns anything. Every hop in between looked
/// inert on the board.
///
/// The walk is over the METADATA call graph, not the drawn one, and it crosses into
/// `lib/` deliberately: whether a call changes state is a fact about the code, not about
/// how much of it this deploy chose to draw. That is what keeps the mark visible when the
/// chain is cut short by framing, `--max-depth`, or leaving `--include-external` off.
///
/// `function_dependencies.callees` holds the same call strings `resolve_call` consumes
/// (`_increaseDebt`, `debtToken.mint`, `PropMath._computeNominalCR`), so resolution here
/// is exactly the resolution used to draw the graph.
fn leads_to_write(
    metadata: &EvmBatMetadata,
    contract: &ContractMetadata,
    function: &FunctionMetadata,
    options: &AutoDeployOptions,
    definer_map: &HashMap<String, Vec<String>>,
    memo: &mut HashMap<String, bool>,
    stack: &mut HashSet<String>,
) -> bool {
    if !function.storage_writes.is_empty() {
        return true;
    }
    let id = function.metadata_id.clone();
    if let Some(&cached) = memo.get(&id) {
        return cached;
    }
    // Recursion is normal in a call graph; a cycle contributes nothing on its own.
    if !stack.insert(id.clone()) {
        return false;
    }

    let callees = metadata
        .function_dependencies
        .iter()
        .find(|dependency| dependency.function_metadata_id == id)
        .map(|dependency| dependency.callees.clone())
        .unwrap_or_default();

    let mut reaches = false;
    for callee in callees {
        if let Some((target_contract, target_function)) =
            resolve_call(metadata, contract, &callee, None, options, definer_map)
        {
            if leads_to_write(
                metadata,
                target_contract,
                &target_function,
                options,
                definer_map,
                memo,
                stack,
            ) {
                reaches = true;
                break;
            }
        }
    }

    // Calls the call-string resolver cannot reach: those pinned by type in the scan
    // (`$.priceFeed.pegOk`) and interface calls the AI resolved.
    if !reaches {
        let followed = function
            .resolved_calls
            .iter()
            .map(|typed| (typed.contract.clone(), typed.method.clone()))
            .chain(function.unresolved_calls.iter().filter_map(|u| {
                metadata
                    .resolutions
                    .get(&u.inferred_type)
                    .map(|concrete| (concrete.clone(), u.method.clone()))
            }))
            .collect::<Vec<_>>();
        for (concrete, method) in followed {
            if let Some((target_contract, target_function)) =
                find_function(metadata, &concrete, &contract.file_path, &method, None)
            {
                if leads_to_write(
                    metadata,
                    target_contract,
                    &target_function,
                    options,
                    definer_map,
                    memo,
                    stack,
                ) {
                    reaches = true;
                    break;
                }
            }
        }
    }

    stack.remove(&id);
    memo.insert(id, reaches);
    reaches
}

fn resolve_call<'a>(
    metadata: &'a EvmBatMetadata,
    caller_contract: &ContractMetadata,
    call_name: &str,
    arg_count: Option<usize>,
    options: &AutoDeployOptions,
    definer_map: &HashMap<String, Vec<String>>,
) -> Option<(&'a ContractMetadata, FunctionMetadata)> {
    let keep = |_contract: &ContractMetadata| true;

    let (target_name, method) = match call_name.split_once('.') {
        Some((target, method)) => (Some(target), method),
        None => (None, call_name),
    };

    let candidates: Vec<String> = match target_name {
        None => {
            let mut chain = vec![caller_contract.name.clone()];
            chain.extend(caller_contract.base_contracts.iter().cloned());
            chain
        }
        Some("super") | Some("this") => {
            let mut chain = caller_contract.base_contracts.clone();
            chain.push(caller_contract.name.clone());
            chain
        }
        // `IFace(addr).method()`, rendered `IFace()`: a cast of a runtime address.
        Some(target) if target.ends_with("()") => {
            return resolve_cast(
                metadata,
                caller_contract,
                target.trim_end_matches("()"),
                method,
                arg_count,
                options,
            );
        }
        Some(target) => {
            if metadata.contract_in_scope(target, &caller_contract.file_path).is_some() {
                // Library or contract called by name.
                vec![target.to_string()]
            } else if let Some(variable) = caller_contract
                .state_variables
                .iter()
                .find(|v| v.name == target)
            {
                // `oracle.quote(...)` — resolve the variable's interface type to
                // whatever contract implements it.
                implementations_of(metadata, &variable.type_name)
            } else {
                Vec::new()
            }
        }
    };

    for candidate in candidates {
        let Some(contract) = metadata.contract_in_scope(&candidate, &caller_contract.file_path)
        else {
            continue;
        };
        if contract.contract_type == EvmContractType::Interface {
            // An interface has no body worth screenshotting; jump to the impl.
            for implementation in implementations_of(metadata, &contract.name) {
                if let Some(target) =
                    metadata.contract_in_scope(&implementation, &caller_contract.file_path)
                {
                    if !keep(target) {
                        continue;
                    }
                    if let Some(found) =
                        find_function(metadata, &target.name, &target.file_path, method, arg_count)
                    {
                        // Only accept a concrete result; a bodyless stub with no
                        // override falls through to the unique-definer fallback.
                        if let Some(resolved) = destub(metadata, found, options) {
                            return Some(resolved);
                        }
                    }
                }
            }
            continue;
        }
        if !keep(contract) {
            continue;
        }
        if let Some(found) =
            find_function(metadata, &contract.name, &contract.file_path, method, arg_count)
        {
            if let Some(resolved) = destub(metadata, found, options) {
                return Some(resolved);
            }
        }
    }

    // Fallback for an interface-typed receiver we could not pin through
    // inheritance (nothing declares `is IFace`): if exactly ONE in-scope contract
    // directly defines this method with a real body, that is the unambiguous
    // target — draw it. This catches a view read like `alm.getReservesAtSqrtPrice`
    // whose unresolved entry the storage-write prune would otherwise drop. Gated
    // on a `receiver.method` call AND on uniqueness, so a common name (`transfer`,
    // defined by many) never auto-binds to the wrong contract.
    if matches!(target_name, Some(t) if t != "super" && t != "this") {
        if let Some(definers) = definer_map.get(method) {
            if definers.len() == 1 {
                return find_function(
                    metadata,
                    &definers[0],
                    &caller_contract.file_path,
                    method,
                    arg_count,
                );
            }
        }
    }
    None
}

/// Resolve `Type(addr).method()`.
///
/// Casting to a concrete contract names the code outright. Casting to an interface does
/// not: which implementation sits behind the address is decided when the system is
/// deployed, which no reading of the source can reveal. So an interface cast is followed
/// only when that question has an answer — a recorded `bat-cli resolve`, or a single
/// implementation defining the method. Several candidates return `None`; the graph
/// builder then asks (see `cast_implementations`) instead of drawing a guess.
fn resolve_cast<'a>(
    metadata: &'a EvmBatMetadata,
    caller_contract: &ContractMetadata,
    type_name: &str,
    method: &str,
    arg_count: Option<usize>,
    options: &AutoDeployOptions,
) -> Option<(&'a ContractMetadata, FunctionMetadata)> {
    let keep = |_contract: &ContractMetadata| true;
    let typed = metadata.contract_in_scope(type_name, &caller_contract.file_path)?;

    if typed.contract_type != EvmContractType::Interface {
        if !keep(typed) {
            return None;
        }
        let found = find_function(metadata, &typed.name, &typed.file_path, method, arg_count)?;
        return destub(metadata, found, options);
    }

    if let Some(concrete) = metadata.resolutions.get(type_name) {
        let target = metadata.contract_in_scope(concrete, &caller_contract.file_path)?;
        if !keep(target) {
            return None;
        }
        let found = find_function(metadata, &target.name, &target.file_path, method, arg_count)?;
        return destub(metadata, found, options);
    }

    let mut implementations = cast_implementations(metadata, caller_contract, type_name, method, arg_count);
    implementations.retain(|(contract, _)| keep(contract));
    if implementations.len() == 1 {
        return implementations.pop();
    }
    None
}

/// Every concrete IN-SCOPE contract that implements interface `type_name` and defines
/// `method` with a body, one per name. None means the target is an external contract.
///
/// Same-named copies collapse to the one reachable from the caller's imports, so three
/// vendored `UpgradeableBeacon`s count as one candidate, not three.
fn cast_implementations<'a>(
    metadata: &'a EvmBatMetadata,
    caller_contract: &ContractMetadata,
    type_name: &str,
    method: &str,
    arg_count: Option<usize>,
) -> Vec<(&'a ContractMetadata, FunctionMetadata)> {
    let mut names: Vec<String> = implementations_of(metadata, type_name);
    names.sort();
    names.dedup();
    let mut found = Vec::new();
    for name in names {
        if name == type_name {
            continue;
        }
        let Some(contract) = metadata.contract_in_scope(&name, &caller_contract.file_path) else {
            continue;
        };
        if contract.contract_type == EvmContractType::Interface {
            continue;
        }
        // The same rule the scan applies (`compute_unresolved_calls`): a generic library
        // implementation is not what a runtime address points at. `IERC20(token)` is some
        // deployed token, never OpenZeppelin's `ERC20` template, and offering the template
        // as a candidate invites a global `bat-cli resolve IERC20 ERC20` that would bind
        // every IERC20 cast in the project to the wrong code.
        if contract.external {
            continue;
        }
        if let Some((defining, function)) =
            find_function(metadata, &contract.name, &contract.file_path, method, arg_count)
        {
            if !function.is_stub {
                found.push((defining, function));
            }
        }
    }
    found
}

/// Redirect a resolved call that landed on a stub (a bodyless interface/abstract
/// declaration or an empty `virtual {}`) to its concrete implementation: the one
/// non-stub override among the contracts deriving from / implementing the stub's
/// contract. Returns the override when exactly one exists; the stub itself when
/// none does (it is the only thing there is to show); `None` when several
/// overrides make the runtime target ambiguous.
fn destub<'a>(
    metadata: &'a EvmBatMetadata,
    found: (&'a ContractMetadata, FunctionMetadata),
    options: &AutoDeployOptions,
) -> Option<(&'a ContractMetadata, FunctionMetadata)> {
    let (contract, function) = found;
    if !function.is_stub {
        return Some((contract, function));
    }
    let keep = |_c: &ContractMetadata| true;
    let mut overrides: Vec<(&'a ContractMetadata, FunctionMetadata)> = Vec::new();
    for impl_name in implementations_of(metadata, &contract.name) {
        if impl_name == contract.name {
            continue;
        }
        if let Some((tc, tf)) = find_function(
            metadata,
            &impl_name,
            &contract.file_path,
            &function.name,
            Some(function.params.len()),
        )
        {
            if !tf.is_stub && keep(tc) {
                overrides.push((tc, tf));
            }
        }
    }
    // Exactly one override → draw it. None (a pure interface/abstract declaration
    // or an empty virtual with no override) or several (ambiguous runtime target)
    // → nothing meaningful to screenshot.
    if overrides.len() == 1 {
        return overrides.pop();
    }
    None
}

/// Contracts implementing `type_name`, which may be an interface name or a
/// concrete contract name.
fn implementations_of(metadata: &EvmBatMetadata, type_name: &str) -> Vec<String> {
    let clean = type_name.trim();
    if let Some(interface) = metadata.interfaces.iter().find(|i| i.name == clean) {
        if !interface.implemented_by.is_empty() {
            return interface.implemented_by.clone();
        }
    }
    // Fall back to any contract declaring it as a base.
    let derived: Vec<String> = metadata
        .contracts
        .iter()
        .filter(|c| c.base_contracts.iter().any(|b| b == clean))
        .map(|c| c.name.clone())
        .collect();
    if !derived.is_empty() {
        return derived;
    }
    vec![clean.to_string()]
}

/// First line of the NatSpec block written directly above `decl_line`, or `decl_line`
/// itself when there is none.
///
/// "Directly above" is deliberate: a comment separated from the declaration by a blank
/// line belongs to whatever came before it as often as not, and pulling it in would put
/// another function's documentation on this one's screenshot. Both NatSpec forms count —
/// a run of `///` lines, or one `/** … */` block — and nothing else does, so an ordinary
/// `//` note is left out.
pub(crate) fn natspec_start(file_path: &str, decl_line: usize) -> usize {
    let content = std::fs::read_to_string(file_path).unwrap_or_default();
    let lines: Vec<&str> = content.lines().collect();
    // `decl_line` is 1-based, so the line above it is at index `decl_line - 2`.
    if decl_line < 2 || decl_line > lines.len() {
        return decl_line;
    }
    let mut index = decl_line - 2;
    let above = lines[index].trim();

    if above.ends_with("*/") {
        // Walk up to the line that opens the block. A one-line `/** … */` opens and
        // closes on the same line, which this handles too.
        loop {
            let line = lines[index].trim();
            if line.starts_with("/**") || line.starts_with("/*") {
                return index + 1;
            }
            if index == 0 {
                return decl_line; // unterminated — take nothing rather than guess
            }
            index -= 1;
        }
    }

    if !above.starts_with("///") {
        return decl_line;
    }
    // Consume the whole run of `///` lines.
    while index > 0 && lines[index - 1].trim().starts_with("///") {
        index -= 1;
    }
    index + 1
}

/// How many lines `--with-documentation` prepends to this declaration's screenshot.
///
/// Every rendered line above the declaration shifts the anchors computed from the body,
/// so this same number is added to each edge's `line_in_slice`.
fn doc_lines_above(options: &AutoDeployOptions, file_path: &str, decl_line: usize) -> usize {
    if !options.with_documentation {
        return 0;
    }
    decl_line.saturating_sub(natspec_start(file_path, decl_line))
}

pub(crate) fn read_slice(file_path: &str, start_line: usize, end_line: usize) -> Vec<String> {
    let content = std::fs::read_to_string(file_path).unwrap_or_default();
    let lines: Vec<&str> = content.lines().collect();
    let start = start_line.saturating_sub(1);
    let end = end_line.min(lines.len());
    if start >= end {
        return Vec::new();
    }
    lines[start..end].iter().map(|l| l.to_string()).collect()
}

/// Render every node and read back its pixel size, without uploading anything.
///
/// `reuse` maps a node id to its already-uploaded image and measured size: those
/// nodes are NOT re-rendered (their size is taken as given), which is what makes
/// `--refresh-links` cheap. An empty map is a normal full render.
fn render_and_measure(
    nodes: &mut [GraphNode],
    owner: &str,
    reuse: &HashMap<String, (String, u32, u32)>,
) -> Result<()> {
    // Screenshots are scratch: they are deleted once uploaded, so the directory
    // is often not there. Create it rather than treating its absence as an
    // error the user has to fix.
    BatFolder::Figures
        .create_folder()
        .change_context(EvmMiroError)?;
    let destination = BatFolder::Figures
        .get_path(true)
        .change_context(EvmMiroError)?;

    // Render DEDUP: every node now renders at the reference font, so two nodes with
    // the same (file, line range) produce a byte-identical image — a function used
    // (or duplicated) N times used to render N identical PNGs, the dominant cost on
    // a big diagram. Render each DISTINCT (file, start, end) once and share it; the
    // per-depth smaller look is applied later via `scale`, not another render.
    type RenderKey = (String, usize, usize);
    let key_of = |node: &GraphNode| -> Option<RenderKey> {
        (!node.file_path.is_empty() && !reuse.contains_key(&node.id))
            .then(|| (node.file_path.clone(), node.start_line, node.end_line))
    };
    let mut distinct: Vec<RenderKey> = Vec::new();
    let mut seen: HashSet<RenderKey> = HashSet::new();
    for node in nodes.iter() {
        if let Some(key) = key_of(node) {
            if seen.insert(key.clone()) {
                distinct.push(key);
            }
        }
    }

    struct Rendered {
        png_path: String,
        width: u32,
        height: u32,
        line_offset: usize,
        lines: Vec<String>,
    }

    let bar = phase_bar("rendering screenshots", distinct.len());
    // CPU-bound and independent per DISTINCT function — fans out across cores.
    let results: std::result::Result<Vec<(RenderKey, Rendered)>, String> = distinct
        .par_iter()
        .map(|key| {
            let (file_path, start, end) = key;
            let code = read_slice(file_path, *start, *end);
            let pretty_path = crate::batbelt::path::prettify_source_code_path(file_path)
                .unwrap_or_else(|_| file_path.clone());
            let mut lines = vec![format!("// {pretty_path}"), String::new()];
            lines.extend(code.iter().cloned());
            let line_offset = start.saturating_sub(PATH_HEADER_LINES);
            // One file per DISTINCT function, named ONLY by (file, lines) — no
            // deployment prefix — so every frame in the same run (a whole --redeploy
            // cluster) SHARES it: a function that appears in several frames is rendered
            // once for the entire run, not once per frame. Cleanup is deferred to the
            // end of the run so the shared files survive between frames.
            let file_name = format!(
                "fn_{}_{}_{}.js",
                file_path.replace([':', '.', '/'], "_"),
                start,
                end
            );
            let png_path = format!("{destination}/{file_name}.png");
            // Cache hit: an earlier frame this run already rendered this function.
            if !std::path::Path::new(&png_path).exists() {
                silicon::create_figure(
                    &lines.join("\n"),
                    &destination,
                    &file_name,
                    line_offset,
                    Some(REFERENCE_FONT),
                    true,
                );
            }
            let (width, height) = image::image_dimensions(&png_path)
                .map_err(|e| format!("cannot measure {png_path}: {e}"))?;
            if width > 8192 || height > 8192 {
                log::warn!("{png_path} renders to {width}x{height}, above Miro's 8192 px limit");
            }
            bar.inc(1);
            Ok((
                key.clone(),
                Rendered { png_path, width, height, line_offset, lines },
            ))
        })
        .collect();
    let rendered: HashMap<RenderKey, Rendered> = results
        .map_err(|message| Report::new(EvmMiroError).attach_printable(message))?
        .into_iter()
        .collect();
    bar.finish_and_clear();

    // Fan the shared renders (and reused sizes) back onto every node.
    for node in nodes.iter_mut() {
        if let Some((_, width, height)) = reuse.get(&node.id) {
            node.png_width = *width;
            node.png_height = *height;
            continue;
        }
        let Some(key) = key_of(node) else { continue };
        if let Some(r) = rendered.get(&key) {
            node.png_path = r.png_path.clone();
            node.png_width = r.width;
            node.png_height = r.height;
            node.line_offset = r.line_offset;
            node.rendered_lines = r.lines.clone();
        }
    }
    println!(
        "    {} {} screenshots ({} distinct rendered)",
        "✓".green(),
        nodes.len(),
        distinct.len()
    );
    Ok(())
}

/// Compose the frame locally: the real screenshots at their real positions,
/// plus a marker on every connector anchor.
///
/// Miro exposes no way to download a rendered board — export jobs are
/// Enterprise-only and `board.picture` is just a generic icon — so this is how
/// the layout gets reviewed without a human taking a screenshot. It shows
/// sizing, spacing and exactly which line each anchor lands on. What it cannot
/// show is Miro's own elbow routing, which the board decides.
fn render_preview(
    nodes: &[GraphNode],
    edges: &[GraphEdge],
    anchors: &[RelativeAnchor],
    layout: &GraphLayout,
    path: &str,
) -> Result<()> {
    use image::{Rgba, RgbaImage};

    // Keep the canvas manageable for very wide frames.
    let scale = (2600.0 / layout.frame_width).min(1.0);
    let width = (layout.frame_width * scale).round().max(1.0) as u32;
    let height = (layout.frame_height * scale).round().max(1.0) as u32;
    let mut canvas = RgbaImage::from_pixel(width, height, Rgba([24, 25, 33, 255]));

    for node in nodes {
        let Some(placed) = layout.node(&node.id) else {
            continue;
        };
        if node.png_path.is_empty() {
            continue;
        }
        let Ok(screenshot) = image::open(&node.png_path) else {
            continue;
        };
        let target_width = (placed.width * scale).round().max(1.0) as u32;
        let target_height = (placed.height * scale).round().max(1.0) as u32;
        let resized = screenshot.resize_exact(
            target_width,
            target_height,
            image::imageops::FilterType::Triangle,
        );
        let left = ((placed.x - placed.width / 2.0) * scale).round() as i64;
        let top = ((placed.y - placed.height / 2.0) * scale).round() as i64;
        image::imageops::overlay(&mut canvas, &resized, left, top);
    }

    // Anchor points and the straight line between them. The real connector is
    // routed by Miro, so treat this as "where it starts and ends", not "how it
    // gets there".
    let by_id: HashMap<&str, &GraphNode> = nodes.iter().map(|n| (n.id.as_str(), n)).collect();
    for (index, (edge, anchor)) in edges.iter().zip(anchors.iter()).enumerate() {
        let (Some(from), Some(to)) = (layout.node(&edge.from), layout.node(&edge.to)) else {
            continue;
        };
        let start = (
            ((from.x - from.width / 2.0 + from.width * anchor.x_fraction) * scale) as i64,
            ((from.y - from.height / 2.0 + from.height * anchor.y_fraction) * scale) as i64,
        );
        let callee_fraction = by_id
            .get(edge.to.as_str())
            .map(|node| {
                silicon::line_geometry(Some(node.font_size))
                    .line_center_fraction(SIGNATURE_LINE_INDEX, node.png_height)
            })
            .unwrap_or(0.5);
        let end = (
            ((to.x - to.width / 2.0) * scale) as i64,
            ((to.y - to.height / 2.0 + to.height * callee_fraction) * scale) as i64,
        );

        let hex = DEPTH_COLORS[from.layer % DEPTH_COLORS.len()];
        let color = parse_hex(hex);
        draw_line(&mut canvas, start, end, color);
        // The arrow head sits on the caller, so mark that end fatter.
        draw_disc(&mut canvas, start, 5, color);
        draw_disc(&mut canvas, end, 2, color);
        let _ = index;
    }

    if let Some(parent) = std::path::Path::new(path).parent() {
        if !parent.as_os_str().is_empty() {
            let _ = std::fs::create_dir_all(parent);
        }
    }
    canvas
        .save(path)
        .into_report()
        .change_context(EvmMiroError)
        .attach_printable_lazy(|| format!("cannot write the preview to {path}"))?;
    Ok(())
}

fn parse_hex(hex: &str) -> image::Rgba<u8> {
    let clean = hex.trim_start_matches('#');
    let value = u32::from_str_radix(clean, 16).unwrap_or(0xffffff);
    image::Rgba([
        ((value >> 16) & 0xff) as u8,
        ((value >> 8) & 0xff) as u8,
        (value & 0xff) as u8,
        255,
    ])
}

fn draw_line(
    canvas: &mut image::RgbaImage,
    from: (i64, i64),
    to: (i64, i64),
    color: image::Rgba<u8>,
) {
    // Bresenham, thick enough to stay visible once the canvas is scaled down.
    let (mut x, mut y) = from;
    let dx = (to.0 - x).abs();
    let dy = -(to.1 - y).abs();
    let step_x = if x < to.0 { 1 } else { -1 };
    let step_y = if y < to.1 { 1 } else { -1 };
    let mut error = dx + dy;
    loop {
        draw_disc(canvas, (x, y), 1, color);
        if x == to.0 && y == to.1 {
            break;
        }
        let double = 2 * error;
        if double >= dy {
            error += dy;
            x += step_x;
        }
        if double <= dx {
            error += dx;
            y += step_y;
        }
    }
}

fn draw_disc(canvas: &mut image::RgbaImage, center: (i64, i64), radius: i64, color: image::Rgba<u8>) {
    for offset_y in -radius..=radius {
        for offset_x in -radius..=radius {
            if offset_x * offset_x + offset_y * offset_y > radius * radius {
                continue;
            }
            let x = center.0 + offset_x;
            let y = center.1 + offset_y;
            if x >= 0 && y >= 0 && (x as u32) < canvas.width() && (y as u32) < canvas.height() {
                canvas.put_pixel(x as u32, y as u32, color);
            }
        }
    }
}

fn cleanup(nodes: &[GraphNode]) {
    for node in nodes {
        if !node.png_path.is_empty() {
            let _ = std::fs::remove_file(&node.png_path);
        }
    }
}

fn print_dry_run(
    nodes: &[GraphNode],
    edges: &[GraphEdge],
    anchors: &[RelativeAnchor],
    layout: &GraphLayout,
    (frame_x, frame_y): (f64, f64),
) {
    println!(
        "  frame {}x{} at ({}, {})",
        layout.frame_width.round(),
        layout.frame_height.round(),
        frame_x.round(),
        frame_y.round()
    );
    println!(
        "  {:<38} {:>5} {:>9} {:>9} {:>7} {:>7}  {:<11}  {}",
        "node", "layer", "x", "y", "w", "h", "png", "state"
    );
    let drawn_screens = drawn_screen_ids(nodes);
    let mut placed: Vec<_> = layout.nodes.iter().collect();
    placed.sort_by_key(|node| (node.layer, node.y as i64));
    for node in placed {
        let source = nodes.iter().find(|n| n.id == node.id);
        println!(
            "  {:<38} {:>5} {:>9.0} {:>9.0} {:>7.0} {:>7.0}  {:<11}  {}",
            truncate(&source.map(|n| n.label.clone()).unwrap_or_default(), 38),
            node.layer,
            node.x,
            node.y,
            node.width,
            node.height,
            source
                .map(|n| format!("{}x{}", n.png_width, n.png_height))
                .unwrap_or_default(),
            // What this node actually gets drawn with: `write` holds the assignment,
            // `→write` carries the mark for a change that happens past the frame's edge.
            // A node that only passes the call along shows nothing — the callee owns it.
            source
                .map(|n| {
                    if n.writes_storage {
                        "write".to_string()
                    } else if surviving_write_calls(n, &drawn_screens).next().is_some() {
                        "→write".to_string()
                    } else {
                        String::new()
                    }
                })
                .unwrap_or_default()
        );
    }

    let marked_lines: Vec<String> = nodes
        .iter()
        .flat_map(|node| {
            surviving_write_calls(node, &drawn_screens)
                .map(move |(line, symbol, _)| format!("{} L{line} → {symbol}()", node.label))
        })
        .collect();
    if !marked_lines.is_empty() {
        println!("  {} call line(s) reaching a state change:", marked_lines.len());
        for line in marked_lines {
            println!("    {line}");
        }
    }
    let external_lines: Vec<String> = nodes
        .iter()
        .flat_map(|node| node.external_call_lines.iter().map(move |line| format!("{} L{line}", node.label)))
        .collect();
    if !external_lines.is_empty() {
        println!("  {} external boundary line(s) (amber):", external_lines.len());
        for line in external_lines {
            println!("    {line}");
        }
    }

    // The span is how many columns the arrow flies over, computed from the placed
    // NODES rather than their labels: a copied helper shares its label with every
    // other copy, so counting by name reports the shortest arrow that could have been
    // drawn instead of the one that will be.
    let mut spans: Vec<usize> = Vec::new();
    println!("  {} connector(s):", edges.len());
    for (edge, anchor) in edges.iter().zip(anchors.iter()) {
        let Some(caller) = nodes.iter().find(|n| n.id == edge.from) else {
            continue;
        };
        let callee_label = nodes
            .iter()
            .find(|n| n.id == edge.to)
            .map(|n| n.label.clone())
            .unwrap_or_default();
        let span = match (layout.node(&edge.from), layout.node(&edge.to)) {
            (Some(from), Some(to)) => to.layer.saturating_sub(from.layer),
            _ => 0,
        };
        spans.push(span);
        println!(
            "    {:<34} L{:<5} → {:<34} start ({:.2}%, {:.2}%){}",
            truncate(&caller.label, 34),
            caller.start_line + edge.line_in_slice - 1,
            truncate(&callee_label, 34),
            anchor.x_fraction * 100.0,
            anchor.y_fraction * 100.0,
            if span > 1 { format!("  spans {span} columns") } else { String::new() }
        );
    }
    let crossing = spans.iter().filter(|span| **span > 1).count();
    println!(
        "  {} of {} connector(s) fly over a column (worst {})",
        crossing,
        spans.len(),
        spans.iter().max().copied().unwrap_or(0)
    );
    if !layout.back_edges.is_empty() {
        println!(
            "  {} cycle(s) will be drawn dashed: {:?}",
            layout.back_edges.len(),
            layout.back_edges
        );
    }
}

fn truncate(text: &str, width: usize) -> String {
    if text.len() <= width {
        return text.to_string();
    }
    format!("{}…", &text[..width.saturating_sub(1)])
}

/// Which side of an item a connector should leave through to reach `toward`.
///
/// Anchoring at the centre lets Miro choose, and it chooses the same side every
/// time — so every arrow approached its token from above regardless of where
/// the line actually came from. Picking the side that faces the other end makes
/// a line coming from below arrive from below, and one coming from the right
/// arrive horizontally, which is the variation that makes a dense diagram
/// readable.
fn facing_anchor(from: (f64, f64), toward: (f64, f64)) -> RelativeAnchor {
    let dx = toward.0 - from.0;
    let dy = toward.1 - from.1;

    if dx > 0.0 {
        // Forward edge (callee is to the right, the layout's flow). Leave
        // HORIZONTALLY so the connector starts at its own call-line height and
        // Miro turns it in the gutter — instead of leaving top/bottom and hugging
        // the source's edge, which bundles many calls into one overlapping trunk.
        // Only a near-vertical edge (callee almost directly above/below) leaves
        // top/bottom.
        if dy.abs() > dx.abs() * 3.0 {
            if dy > 0.0 {
                RelativeAnchor::new(0.5, 1.0)
            } else {
                RelativeAnchor::new(0.5, 0.0)
            }
        } else {
            RelativeAnchor::new(1.0, 0.5)
        }
    } else {
        // Back / same-column edge: the dominant axis decides; horizontal ties go
        // left (away from the flow).
        if dy.abs() > dx.abs() {
            if dy > 0.0 {
                RelativeAnchor::new(0.5, 1.0)
            } else {
                RelativeAnchor::new(0.5, 0.0)
            }
        } else {
            RelativeAnchor::new(0.0, 0.5)
        }
    }
}

#[cfg(test)]
mod facing_anchor_test {
    use super::*;

    #[test]
    fn test_the_side_faces_the_other_end() {
        let origin = (100.0, 100.0);

        // Straight to the right, and far enough right that x dominates.
        let right = facing_anchor(origin, (500.0, 120.0));
        assert_eq!((right.x_fraction, right.y_fraction), (1.0, 0.5));

        // Mostly downwards.
        let below = facing_anchor(origin, (120.0, 900.0));
        assert_eq!((below.x_fraction, below.y_fraction), (0.5, 1.0));

        // Mostly upwards.
        let above = facing_anchor(origin, (120.0, -400.0));
        assert_eq!((above.x_fraction, above.y_fraction), (0.5, 0.0));

        // Back to the left, which happens on a cycle.
        let left = facing_anchor(origin, (-300.0, 110.0));
        assert_eq!((left.x_fraction, left.y_fraction), (0.0, 0.5));
    }

    /// The two ends of one hop must face each other, not the same way.
    #[test]
    fn test_both_ends_of_a_hop_face_each_other() {
        let a = (0.0, 0.0);
        let b = (0.0, 500.0);
        let from_a = facing_anchor(a, b);
        let from_b = facing_anchor(b, a);
        assert_eq!((from_a.x_fraction, from_a.y_fraction), (0.5, 1.0));
        assert_eq!((from_b.x_fraction, from_b.y_fraction), (0.5, 0.0));
    }
}

/// Give every caller of a shared leaf its own copy of it.
///
/// Sharing a node keeps the diagram small, but a node shared by callers sitting
/// on different layers is what produces the long edges: layering puts it after
/// its deepest caller, so the arrows from the shallower ones have to cross every
/// column in between. In `Vault.depositWithReferral`, `MathLib.mulDiv` alone
/// accounts for three of the five such edges.
///
/// A leaf is the one case where splitting is nearly free: it carries no subtree,
/// so a copy costs exactly one screenshot, and the copy lands on the layer right
/// after its caller, which turns a layer-spanning edge into an adjacent one by
/// construction.
///
/// Both conditions are counted off the edge list — out-degree zero, in-degree
/// above one — with no notion of what the function does. "Leaf" here means leaf
/// *as drawn*: a node can have no outgoing edges because it genuinely calls
/// nothing, because a call could not be resolved, or because its callee lives in
/// `lib/` and was excluded. For laying out the picture those are the same thing,
/// since what matters is that the node has nothing hanging off it.
/// The node plus its transitively PRIVATE (non-shared) descendants — the copy
/// unit. Descent stops at any shared descendant, so a copy unit is always a
/// disjoint private subtree cut at shared/anchor nodes; that is what makes the
/// duplication non-cascading.
fn private_closure(
    root: &str,
    out: &HashMap<String, Vec<String>>,
    shared: &HashSet<String>,
) -> HashSet<String> {
    let mut result = HashSet::new();
    result.insert(root.to_string());
    let mut stack = vec![root.to_string()];
    while let Some(current) = stack.pop() {
        if let Some(children) = out.get(&current) {
            for child in children {
                if shared.contains(child) {
                    continue; // cut at shared descendants — decided on their own
                }
                if result.insert(child.clone()) {
                    stack.push(child.clone());
                }
            }
        }
    }
    result
}

/// De-share ONLY the functions whose reuse tangles the diagram. A shared node
/// sitting several columns back from a caller draws a long arrow that crosses the
/// screenshots between them (Miro routes connectors itself, so the layout can't
/// bend around them); that far caller gets a local copy of the node's private
/// closure instead — a repeated screenshot, which the auditor prefers to a
/// crossing. A caller in the adjacent column keeps sharing the one node, so nothing
/// is repeated for free. Runs after render, so copies inherit the image.
///
/// Each round lays the graph out, finds the shared node with the farthest-back
/// caller, and copies its closure for every caller ≥ `CROSS_LAYERS` columns back —
/// keeping the NEAREST caller on the original so it is never orphaned (with one
/// caller left, layering places the node adjacent, so it no longer crosses).
/// Re-lays-out each round because a copy changes the columns; bounded by closure
/// size and a box budget.
/// Replace the CROSSING CALL — not the callee — with a card, when the callee is too
/// big to copy next to its far caller.
///
/// Framing cuts for SPACE: a branch leaves the frame when the frame is too big to
/// read. That left a whole class of mess untouched — a helper called from columns 1
/// and 3 is pinned to the far right by the longest-path layering, so its arrow from
/// column 1 flies over everything in between, and no amount of space made that
/// arrow shorter. The only two ways to shorten it are a copy next to each caller or
/// a card next to each caller, and a card is what a callee too big to copy gets.
///
/// It cuts the offending EDGE, not the node: the caller sitting next to the callee
/// keeps reading it as a screenshot, and only the caller that was flying an arrow
/// over two columns gets a card instead. Replacing the node would take the drawing
/// away from the near caller too, to fix a problem that caller never had.
///
/// Returns how many calls were cut, so the caller can say so.
fn cut_crossing_shared(nodes: &mut Vec<GraphNode>, edges: &mut Vec<GraphEdge>, root_id: &str) -> usize {
    const CROSS_LAYERS: usize = 2;
    let mut done = 0usize;
    loop {
        let layout_nodes: Vec<LayoutNode> = nodes
            .iter()
            .map(|node| LayoutNode {
                id: node.id.clone(),
                width: node.board_width(),
                height: node.board_height(),
            })
            .collect();
        let anchors = compute_anchors(nodes, edges);
        let layout_edges: Vec<LayoutEdge> = edges
            .iter()
            .zip(anchors.iter())
            .map(|(edge, anchor)| LayoutEdge {
                from: edge.from.clone(),
                to: edge.to.clone(),
                from_line_fraction: anchor.y_fraction,
            })
            .collect();
        let layout = layout_graph(root_id, &layout_nodes, &layout_edges, LayoutConfig::default());
        let layer_of: HashMap<&str, usize> =
            layout.nodes.iter().map(|p| (p.id.as_str(), p.layer)).collect();

        let mut callers: HashMap<String, Vec<String>> = HashMap::new();
        let mut out: HashMap<String, Vec<String>> = HashMap::new();
        for edge in edges.iter() {
            callers.entry(edge.to.clone()).or_default().push(edge.from.clone());
            out.entry(edge.from.clone()).or_default().push(edge.to.clone());
        }
        let shared: HashSet<String> = callers
            .iter()
            .filter(|(_, cs)| cs.len() >= 2)
            .map(|(id, _)| id.clone())
            .collect();

        // The biggest crosser first: it is the one whose frame is most worth having,
        // and cutting it often takes several other crossers with it.
        let mut victim: Option<(usize, String)> = None;
        for id in &shared {
            let is_screenshot = nodes
                .iter()
                .any(|node| node.id == *id && matches!(node.kind, NodeKind::Screenshot));
            if !is_screenshot || id == root_id {
                continue;
            }
            let worst = callers
                .get(id)
                .map(|cs| {
                    cs.iter()
                        .map(|c| match (layer_of.get(id.as_str()), layer_of.get(c.as_str())) {
                            (Some(&vl), Some(&cl)) => vl.saturating_sub(cl),
                            _ => 0,
                        })
                        .max()
                        .unwrap_or(0)
                })
                .unwrap_or(0);
            if worst < CROSS_LAYERS {
                continue;
            }
            // Two different costs, so two different thresholds. Copying a callee costs
            // its closure ONCE PER far caller, so a helper the size of a getter is still
            // expensive when nine callers need their own copy — that is how one contract
            // put 203 boxes on a board for 30 functions. Either cost alone is enough to
            // prefer a frame: one drawing, a card beside each caller.
            let clen = private_closure(id, &out, &shared).len();
            let far = callers
                .get(id)
                .map(|cs| {
                    let mut distinct: Vec<&String> = cs.iter().collect();
                    distinct.sort();
                    distinct.dedup();
                    distinct
                        .iter()
                        .filter(|c| match (layer_of.get(id.as_str()), layer_of.get(c.as_str())) {
                            (Some(&vl), Some(&cl)) => vl.saturating_sub(cl) >= CROSS_LAYERS,
                            _ => false,
                        })
                        .count()
                })
                .unwrap_or(0);
            if clen < FRAME_MIN && far <= MAX_COPIES_OF_ONE_CALLEE {
                continue; // cheap enough to copy; localization handles it
            }
            if victim.as_ref().map_or(true, |(best, _)| clen > *best) {
                victim = Some((clen, id.clone()));
            }
        }
        let Some((_, id)) = victim else {
            break;
        };
        // The far calls only. `cut_edge` prunes and renumbers, so one per pass and
        // re-measure: the copy it removes can change every other node's column.
        let Some(index) = edges.iter().position(|edge| {
            edge.to == id
                && match (layer_of.get(id.as_str()), layer_of.get(edge.from.as_str())) {
                    (Some(&vl), Some(&cl)) => vl.saturating_sub(cl) >= CROSS_LAYERS,
                    _ => false,
                }
        }) else {
            break;
        };
        cut_edge(nodes, edges, index);
        done += 1;
    }
    done
}

fn duplicate_crossing_shared(
    nodes: &mut Vec<GraphNode>,
    edges: &mut Vec<GraphEdge>,
    root_id: &str,
) {
    const CROSS_LAYERS: usize = 2; // a caller this many columns back skips a column
    // Copy helpers small enough that a frame of their own would be a husk. The two
    // bands MEET at FRAME_MIN, which is the whole point: under it a crossing callee
    // is copied next to each far caller, at or over it `cut_crossing_shared` has
    // already given it a frame and a card per caller. Nothing falls between them and
    // keeps crossing, which is what the old cap of 3 left behind — a helper with four
    // callees of its own was too big to copy and never big enough to be cut.
    const MAX_CLOSURE: usize = FRAME_MIN - 1;
    // Effectively uncapped copies: a leaf used 56× needs 56 local copies, or it
    // still draws long crossing arrows. Small copies, so the box budget (below)
    // is the real bound.
    const MAX_COPIES: usize = 4096;
    let budget = nodes.len() * 4;
    let mut added = 0usize;

    loop {
        if added >= budget {
            break;
        }
        // Preliminary layout to read each node's column (layer).
        let layout_nodes: Vec<LayoutNode> = nodes
            .iter()
            .map(|node| LayoutNode {
                id: node.id.clone(),
                width: node.board_width(),
                height: node.board_height(),
            })
            .collect();
        let anchors = compute_anchors(nodes, edges);
        let layout_edges: Vec<LayoutEdge> = edges
            .iter()
            .zip(anchors.iter())
            .map(|(edge, anchor)| LayoutEdge {
                from: edge.from.clone(),
                to: edge.to.clone(),
                from_line_fraction: anchor.y_fraction,
            })
            .collect();
        let layout = layout_graph(root_id, &layout_nodes, &layout_edges, LayoutConfig::default());
        let layer_of: HashMap<&str, usize> =
            layout.nodes.iter().map(|p| (p.id.as_str(), p.layer)).collect();

        // Callers + out-adjacency + shared set (recomputed; copies change them).
        let mut callers: HashMap<String, Vec<String>> = HashMap::new();
        let mut out: HashMap<String, Vec<String>> = HashMap::new();
        for edge in edges.iter() {
            callers.entry(edge.to.clone()).or_default().push(edge.from.clone());
            out.entry(edge.from.clone()).or_default().push(edge.to.clone());
        }
        let shared: HashSet<String> = callers
            .iter()
            .filter(|(_, cs)| cs.len() >= 2)
            .map(|(id, _)| id.clone())
            .collect();

        // How far back a caller sits from a node, in columns.
        let skip = |v: &str, c: &str| -> usize {
            match (layer_of.get(v), layer_of.get(c)) {
                (Some(&vl), Some(&cl)) => vl.saturating_sub(cl),
                _ => 0,
            }
        };

        // Copy the SMALLEST crossing helper first (the cheap mesh floor — leaves
        // like sqrt/mul512), then bigger ones; ties broken by the farthest-back
        // caller. Copying the floor first dissolves the mesh from the bottom, which
        // is what a top-down pass could never reach before the budget ran out.
        let mut best: Option<(usize, usize, String)> = None; // (closure_len, -worst, id)
        for v in &shared {
            let worst = callers
                .get(v)
                .map(|cs| cs.iter().map(|c| skip(v, c)).max().unwrap_or(0))
                .unwrap_or(0);
            if worst < CROSS_LAYERS {
                continue;
            }
            let clen = private_closure(v, &out, &shared).len();
            if clen > MAX_CLOSURE {
                continue;
            }
            // Repeating one callee past this is `cut_crossing_shared`'s business: it
            // gave the callee a frame, and copying it here as well would put the
            // drawing back beside every caller and undo that.
            let far = callers
                .get(v)
                .map(|cs| {
                    let mut distinct: Vec<&String> = cs.iter().collect();
                    distinct.sort();
                    distinct.dedup();
                    distinct.iter().filter(|c| skip(v, c) >= CROSS_LAYERS).count()
                })
                .unwrap_or(0);
            if far > MAX_COPIES_OF_ONE_CALLEE {
                continue;
            }
            // Prefer smaller closure, then larger skip.
            let key = (clen, usize::MAX - worst);
            if best.as_ref().map_or(true, |(cl, w, _)| key < (*cl, *w)) {
                best = Some((key.0, key.1, v.clone()));
            }
        }
        let Some((_, _, victim)) = best else {
            break;
        };
        let closure = private_closure(&victim, &out, &shared);

        // Copy for callers ≥ CROSS_LAYERS back, but never for the NEAREST one — it
        // stays on the original so the victim keeps a caller (and, alone, no longer
        // crosses).
        let mut distinct_callers: Vec<String> = callers.get(&victim).cloned().unwrap_or_default();
        distinct_callers.sort();
        distinct_callers.dedup();
        distinct_callers.sort_by_key(|c| skip(&victim, c)); // nearest first
        let distant: Vec<String> = distinct_callers
            .iter()
            .skip(1)
            .filter(|c| skip(&victim, c) >= CROSS_LAYERS)
            .cloned()
            .collect();
        if distant.is_empty() {
            break;
        }

        let templates: HashMap<String, GraphNode> = nodes
            .iter()
            .filter(|node| closure.contains(&node.id))
            .map(|node| (node.id.clone(), node.clone()))
            .collect();
        let internal: Vec<GraphEdge> = edges
            .iter()
            .filter(|edge| closure.contains(&edge.from) && closure.contains(&edge.to))
            .cloned()
            .collect();
        // Keep calls to shared children OUTSIDE the closure, or the copy dead-ends.
        let external: Vec<GraphEdge> = edges
            .iter()
            .filter(|edge| closure.contains(&edge.from) && !closure.contains(&edge.to))
            .cloned()
            .collect();

        let mut made = 0usize;
        for caller in distant.iter() {
            if made >= MAX_COPIES || added + closure.len() > budget {
                break;
            }
            let suffix = format!("dup{added}_{made}");
            let id_map: HashMap<String, String> = closure
                .iter()
                .map(|id| (id.clone(), format!("{id}#{suffix}")))
                .collect();
            for id in &closure {
                if let Some(template) = templates.get(id) {
                    let mut copy = template.clone();
                    copy.id = id_map[id].clone();
                    nodes.push(copy);
                }
            }
            for edge in &internal {
                let mut copy = edge.clone();
                copy.from = id_map[&edge.from].clone();
                copy.to = id_map[&edge.to].clone();
                edges.push(copy);
            }
            // Copy each external call from the copied closure onto the SAME shared
            // target, so the duplicate keeps calling out (no dead-ends).
            for edge in &external {
                let mut copy = edge.clone();
                copy.from = id_map[&edge.from].clone();
                edges.push(copy);
            }
            // Repoint every call from THIS caller to the victim onto its own copy.
            for edge in edges.iter_mut() {
                if edge.from == *caller && edge.to == victim {
                    edge.to = id_map[&victim].clone();
                }
            }
            added += closure.len();
            made += 1;
        }
        if made == 0 {
            break; // budget exhausted for even the smallest closure
        }
    }
}

fn split_shared_leaves(nodes: &mut Vec<GraphNode>, edges: &mut [GraphEdge]) {
    let mut outgoing: HashMap<&str, usize> = HashMap::new();
    let mut incoming: HashMap<&str, usize> = HashMap::new();
    for edge in edges.iter() {
        *outgoing.entry(edge.from.as_str()).or_insert(0) += 1;
        *incoming.entry(edge.to.as_str()).or_insert(0) += 1;
    }

    let shared_leaves: HashSet<String> = nodes
        .iter()
        .filter(|node| {
            outgoing.get(node.id.as_str()).copied().unwrap_or(0) == 0
                && incoming.get(node.id.as_str()).copied().unwrap_or(0) > 1
        })
        .map(|node| node.id.clone())
        .collect();
    if shared_leaves.is_empty() {
        return;
    }

    let template: HashMap<String, GraphNode> = nodes
        .iter()
        .filter(|node| shared_leaves.contains(&node.id))
        .map(|node| (node.id.clone(), node.clone()))
        .collect();

    // One instance of the leaf PER DISTINCT CALLER, not per call. A leaf called
    // several times from the SAME caller stays one node — the arrows converge from
    // that caller's own (adjacent) lines, a small local fan, and N identical boxes
    // would be pure noise. Different callers still each get their own copy: that is
    // what keeps a widely-shared leaf from becoming one node every layer has to
    // reach across. The first caller keeps the original node.
    let mut instance: HashMap<(String, String), String> = HashMap::new();
    let mut keeper: HashMap<String, String> = HashMap::new();
    let mut copies: Vec<GraphNode> = Vec::new();
    for edge in edges.iter_mut() {
        if !shared_leaves.contains(&edge.to) {
            continue;
        }
        // The first caller seen for this leaf keeps the original node.
        let first = keeper
            .entry(edge.to.clone())
            .or_insert_with(|| edge.from.clone());
        if *first == edge.from {
            continue;
        }
        let Some(original) = template.get(&edge.to) else {
            continue;
        };
        // Reuse this caller's single copy across its repeated calls.
        let copy_id = instance
            .entry((edge.to.clone(), edge.from.clone()))
            .or_insert_with(|| {
                let copy_id = format!("{}#{}", edge.to, copies.len());
                let mut copy = original.clone();
                copy.id = copy_id.clone();
                copies.push(copy);
                copy_id
            })
            .clone();
        edge.to = copy_id;
    }

    nodes.extend(copies);
}

#[cfg(test)]
mod split_shared_leaves_test {
    use super::*;

    fn node(id: &str) -> GraphNode {
        GraphNode {
            kind: NodeKind::Screenshot,
            id: id.to_string(),
            label: id.to_string(),
            file_path: String::new(),
            start_line: 1,
            end_line: 2,
            depth: 0,
            font_size: 22,
            scale: 1.0,
            png_path: String::new(),
            png_width: 0,
            png_height: 0,
            rendered_lines: Vec::new(),
            line_offset: 0,
            writes_storage: false,
        write_lines: Vec::new(),
        external_call_lines: Vec::new(),
        leads_to_write: false,
        write_call_lines: Vec::new(),
        }
    }

    fn edge(from: &str, to: &str) -> GraphEdge {
        GraphEdge {
            from: from.to_string(),
            to: to.to_string(),
            line_in_slice: 1,
            column: 0,
            symbol: to.to_string(),
        }
    }

    /// The rule is arithmetic on the edge list: out-degree zero, in-degree above
    /// one. Nothing about it knows what a function does.
    #[test]
    fn test_a_leaf_with_several_callers_is_split() {
        let mut nodes = vec![node("a"), node("b"), node("leaf")];
        let mut edges = vec![edge("a", "leaf"), edge("b", "leaf")];

        split_shared_leaves(&mut nodes, &mut edges);

        assert_eq!(nodes.len(), 4, "the leaf should have gained a copy");
        assert_ne!(edges[0].to, edges[1].to, "each caller gets its own");
        assert_eq!(edges[0].to, "leaf", "the first caller keeps the original");
    }

    /// A node with children carries a subtree, so a copy is not cheap and the
    /// rule leaves it alone.
    #[test]
    fn test_a_shared_node_with_children_is_left_shared() {
        let mut nodes = vec![node("a"), node("b"), node("mid"), node("deep")];
        let mut edges = vec![edge("a", "mid"), edge("b", "mid"), edge("mid", "deep")];

        split_shared_leaves(&mut nodes, &mut edges);

        assert_eq!(nodes.len(), 4, "nothing should have been copied");
        assert_eq!(edges[0].to, "mid");
        assert_eq!(edges[1].to, "mid");
    }

    /// One caller means nothing to gain: a copy would be the same picture.
    #[test]
    fn test_a_leaf_with_one_caller_is_untouched() {
        let mut nodes = vec![node("a"), node("leaf")];
        let mut edges = vec![edge("a", "leaf")];

        split_shared_leaves(&mut nodes, &mut edges);

        assert_eq!(nodes.len(), 2);
        assert_eq!(edges[0].to, "leaf");
    }
}

/// Balanced partitioning, not "cut until under a cap". A frame is aimed AT a
/// readable size, and a graph too big for one frame is split into several pieces
/// each near that size — never one giant frame, never a scatter of husks.
///
/// - `FRAME_TARGET` — the size (in screenshots) a frame is aimed at. ~1500–2600px
///   screenshots across ≤5 layers land around 10–12k px wide: readable at a normal
///   zoom, ~30 connectors. (Auditors rejected 24–33-shot frames as unreadable.)
/// - `FRAME_MAX` — above this (measured as EFFECTIVE size, depth included) a frame
///   is split; a graph at or under it ships whole (one 20-shot frame beats a
///   14 + 6 split with a link card to chase).
/// - `FRAME_MIN` — a cut branch, and the residual left behind, must each keep at
///   least this many of their own screenshots; below it the piece is a husk.
/// - `MAX_CUTS_PER_FRAME` — at most this many branches leave one frame, so a frame
///   never becomes a scavenger hunt of link cards. A cut branch bigger than
///   `FRAME_MAX` becomes its own frame and is split again by the same policy.
const FRAME_TARGET: usize = 15;
const FRAME_MAX: usize = 20;
const FRAME_MIN: usize = 6;
const MAX_CUTS_PER_FRAME: usize = 10;

/// Depth costs horizontal px (the scarce resource): past this many layers a frame
/// runs off-screen even at a modest screenshot count. Effective size scales up
/// `DEPTH_PENALTY` per layer beyond the free budget, so a deep-and-narrow frame is
/// cut sooner than a shallow-and-wide one of the same raw count.
const DEPTH_FREE_LAYERS: usize = 5;
const DEPTH_PENALTY: f64 = 0.15;

/// Replace one call with a card linking to the callee's own frame.
///
/// The decision is per **edge**, not per function. `FeeLib.feeOf` is called from
/// layer 1 and from layer 2 and lays out on layer 3: the arrow from layer 2 is
/// fine, the one from layer 1 reaches further. Moving the whole function out
/// would take away the arrow that was already fine, so only the far call is
/// replaced — the near caller keeps the screenshot.
/// Swaps each callee that already has its own frame for a link card, except when that would
/// leave this frame under `FRAME_MIN` screenshots: a frame that is one screenshot and a couple
/// of link cards shows nothing (the same husk floor as the automatic cut), so such a callee
/// is drawn inline instead. Returns the calls linked and the callees kept inline.
fn link_deployed_frames(
    nodes: &mut Vec<GraphNode>,
    edges: &mut Vec<GraphEdge>,
    deployed_titles: &HashSet<String>,
) -> (usize, Vec<String>) {
    let Some(root_id) = nodes.first().map(|n| n.id.clone()) else {
        return (0, Vec::new());
    };
    let targets: Vec<String> = {
        let mut seen = HashSet::new();
        edges
            .iter()
            .filter(|edge| edge.to != root_id)
            .filter(|edge| {
                nodes.iter().any(|node| {
                    node.id == edge.to
                        && node.kind == NodeKind::Screenshot
                        && deployed_titles.contains(&node.label)
                })
            })
            .filter_map(|edge| seen.insert(edge.to.clone()).then(|| edge.to.clone()))
            .collect()
    };
    let (mut linked, mut kept) = (0usize, Vec::new());
    for target in targets {
        // Already pruned by an earlier link (it was inside that subtree).
        let Some(label) = nodes.iter().find(|n| n.id == target).map(|n| n.label.clone()) else {
            continue;
        };
        let (mut trial_nodes, mut trial_edges) = (nodes.clone(), edges.clone());
        let calls = trial_edges.iter().filter(|e| e.to == target).count();
        cut_node(&mut trial_nodes, &mut trial_edges, &target);
        if screenshot_count(&trial_nodes) < FRAME_MIN {
            kept.push(label);
            continue;
        }
        *nodes = trial_nodes;
        *edges = trial_edges;
        linked += calls;
    }
    (linked, kept)
}

fn cut_edge(nodes: &mut Vec<GraphNode>, edges: &mut Vec<GraphEdge>, index: usize) {
    let Some((label, file)) = nodes
        .iter()
        .find(|node| node.id == edges[index].to)
        .map(|node| (node.label.clone(), node.file_path.clone()))
    else {
        return;
    };

    let card_id = format!("\u{0}link{index}");
    nodes.push(GraphNode {
        id: card_id.clone(),
        label: label.clone(),
        kind: NodeKind::Link { target: label, file },
        file_path: String::new(),
        start_line: 0,
        end_line: 0,
        depth: 0,
        font_size: 22,
        scale: 1.0,
        png_path: String::new(),
        png_width: LINK_CARD_WIDTH as u32,
        png_height: LINK_CARD_HEIGHT as u32,
        rendered_lines: Vec::new(),
        line_offset: 0,
        writes_storage: false,
        write_lines: Vec::new(),
        external_call_lines: Vec::new(),
        leads_to_write: false,
        write_call_lines: Vec::new(),
    });
    edges[index].to = card_id;
    prune_unreachable(nodes, edges);
}

/// Link out a whole (possibly shared) node: repoint EVERY call into `target_id`
/// onto its own link card, so each caller keeps a nearby card pointing at the
/// node's frame, and the node's now-unreachable subtree is pruned. Unlike
/// [`cut_edge`], which severs a single last-reference call, this removes a node
/// reached from several callers — the only way to carve a balanced piece out of a
/// densely-shared graph, where cutting one edge frees nothing.
fn cut_node(nodes: &mut Vec<GraphNode>, edges: &mut Vec<GraphEdge>, target_id: &str) {
    let Some((label, file)) = nodes
        .iter()
        .find(|node| node.id == target_id)
        .map(|node| (node.label.clone(), node.file_path.clone()))
    else {
        return;
    };
    let in_edges: Vec<usize> = edges
        .iter()
        .enumerate()
        .filter(|(_, e)| e.to == target_id)
        .map(|(i, _)| i)
        .collect();
    for (n, idx) in in_edges.into_iter().enumerate() {
        let card_id = format!("\u{0}linknode_{target_id}_{n}");
        nodes.push(GraphNode {
            id: card_id.clone(),
            label: label.clone(),
            kind: NodeKind::Link { target: label.clone(), file: file.clone() },
            file_path: String::new(),
            start_line: 0,
            end_line: 0,
            depth: 0,
            font_size: 22,
            scale: 1.0,
            png_path: String::new(),
            png_width: LINK_CARD_WIDTH as u32,
            png_height: LINK_CARD_HEIGHT as u32,
            rendered_lines: Vec::new(),
            line_offset: 0,
            writes_storage: false,
        write_lines: Vec::new(),
        external_call_lines: Vec::new(),
        leads_to_write: false,
        write_call_lines: Vec::new(),
        });
        edges[idx].to = card_id;
    }
    prune_unreachable(nodes, edges);
}

/// Screenshots only: a card is a reference, not something to read.
fn screenshot_count(nodes: &[GraphNode]) -> usize {
    nodes
        .iter()
        .filter(|node| node.kind == NodeKind::Screenshot)
        .count()
}

/// Screenshot count adjusted for depth: past `DEPTH_FREE_LAYERS` layers a frame
/// runs off-screen horizontally, so each extra layer inflates the effective size.
/// A shallow-wide frame reads far better than a deep-narrow one of the same count,
/// and this is what makes the cut policy split the latter sooner.
fn effective_size(nodes: &[GraphNode]) -> usize {
    let count = screenshot_count(nodes);
    let max_layer = nodes
        .iter()
        .filter(|n| n.kind == NodeKind::Screenshot)
        .map(|n| n.depth)
        .max()
        .unwrap_or(0);
    let over = max_layer.saturating_sub(DEPTH_FREE_LAYERS);
    (count as f64 * (1.0 + DEPTH_PENALTY * over as f64)).round() as usize
}

/// The cut that removes the most screenshots, if any removes one at all.
///
/// A cut has to earn its place. Replacing a call to a shared function takes
/// nothing off the frame, because the other caller still needs the function and
/// everything under it: the card is added and no screenshot leaves. It only pays
/// when the call was the last reference, so the subtree becomes unreachable and
/// goes with it.
///
/// Any call is a candidate, not only the ones reaching across layers. A call
/// spanning layers can never strand anything — the longer path that put its
/// target down there arrives through a nearer caller, which keeps holding it up.
/// The calls that free space are the ordinary ones: the single call into a deep
/// branch, whose removal takes the branch with it.
///
/// Leaves are never candidates: a copy costs one small screenshot and
/// [`split_shared_leaves`] has already made those, so a card would be a click in
/// exchange for nothing.
/// Screenshot ids reachable from `root` (root included if it is a screenshot),
/// following edges. A visited set makes cycles/shared subtrees count once.
fn reachable_screens(root: &str, adjacency: &HashMap<&str, Vec<&str>>, screens: &HashSet<&str>) -> HashSet<String> {
    let mut seen: HashSet<String> = HashSet::new();
    let mut out: HashSet<String> = HashSet::new();
    let mut stack = vec![root.to_string()];
    while let Some(id) = stack.pop() {
        if !seen.insert(id.clone()) {
            continue;
        }
        if screens.contains(id.as_str()) {
            out.insert(id.clone());
        }
        for next in adjacency.get(id.as_str()).cloned().unwrap_or_default() {
            stack.push(next.to_string());
        }
    }
    out
}

/// All node ids reachable from `root` (root included), following edges. Used to
/// measure a branch's whole subtree and its edge boundary.
fn reachable_nodes(root: &str, adjacency: &HashMap<&str, Vec<&str>>) -> HashSet<String> {
    let mut seen: HashSet<String> = HashSet::new();
    let mut stack = vec![root.to_string()];
    while let Some(id) = stack.pop() {
        if !seen.insert(id.clone()) {
            continue;
        }
        for next in adjacency.get(id.as_str()).cloned().unwrap_or_default() {
            stack.push(next.to_string());
        }
    }
    seen
}

/// Choose the single best branch to link out to its own frame — or `None` when no
/// cut yields a readable, non-husk piece. Rather than lopping off the LARGEST
/// subtree (which leaves two lopsided halves), we score each candidate on how close
/// its size lands to `budget` (the per-piece target), minus the cross-frame edges
/// the cut severs (each becomes a link card, not a drawn arrow), plus small bonuses
/// for a subtree that is widely reused or already has a frame. A branch smaller than
/// `FRAME_MIN`, or one whose removal would leave the frame itself below `FRAME_MIN`,
/// is rejected — that is the husk guard, in both directions.
fn best_cut(
    nodes: &[GraphNode],
    edges: &[GraphEdge],
    framed: &HashSet<&str>,
    budget: usize,
) -> Option<(Vec<GraphNode>, Vec<GraphEdge>)> {
    let has_children: HashSet<&str> = edges.iter().map(|edge| edge.from.as_str()).collect();
    let screens: HashSet<&str> = nodes
        .iter()
        .filter(|n| n.kind == NodeKind::Screenshot)
        .map(|n| n.id.as_str())
        .collect();
    let mut adjacency: HashMap<&str, Vec<&str>> = HashMap::new();
    for edge in edges.iter() {
        adjacency.entry(edge.from.as_str()).or_default().push(edge.to.as_str());
    }
    let root = nodes.first().map(|n| n.id.as_str()).unwrap_or("");

    let before = screenshot_count(nodes);
    let budget_f = budget.max(1) as f64;
    let mut best: Option<(f64, Vec<GraphNode>, Vec<GraphEdge>)> = None;

    // Candidates are NODES with a subtree (not the root, not a leaf, not a link
    // card). Cutting a node lifts out its whole subtree — as one frame — no matter
    // how many callers reach it, which is what lets a densely-shared graph be
    // partitioned at all.
    for node in nodes.iter() {
        if node.kind != NodeKind::Screenshot
            || node.id == root
            || !has_children.contains(node.id.as_str())
        {
            continue;
        }
        let has_frame = framed.contains(node.label.as_str());
        let sub = reachable_screens(&node.id, &adjacency, &screens).len();

        let mut candidate_nodes = nodes.to_vec();
        let mut candidate_edges = edges.to_vec();
        cut_node(&mut candidate_nodes, &mut candidate_edges, &node.id);
        let saved = before.saturating_sub(screenshot_count(&candidate_nodes));
        if saved == 0 {
            continue;
        }
        let residual = before.saturating_sub(saved);

        // Husk guard, both directions: neither the new piece nor the leftover frame
        // may fall below the readable minimum. An existing frame is exempt on the
        // piece side (no new frame is created — the cut only replaces arrows).
        if (!has_frame && sub < FRAME_MIN) || residual < FRAME_MIN {
            continue;
        }

        // Cross-frame edges this cut severs (the subtree's boundary) — each becomes
        // a link card rather than a drawn arrow — and how many callers reach it.
        let subtree = reachable_nodes(&node.id, &adjacency);
        let severed = edges
            .iter()
            .filter(|e| subtree.contains(&e.from) != subtree.contains(&e.to))
            .count()
            .max(1);
        let reuse = edges.iter().filter(|e| e.to == node.id).count();

        // Nearness to the target dominates; severed edges tiebreak; reuse and an
        // existing frame nudge. (Weights: size distance ~3.3/shot, edge ~12.)
        let score = -(50.0 / budget_f) * (sub as f64 - budget_f).abs()
            - 12.0 * (severed as f64 - 1.0)
            + 10.0 * (reuse.min(3) as f64)
            + if has_frame { 8.0 } else { 0.0 };
        if best.as_ref().map(|(most, _, _)| score > *most).unwrap_or(true) {
            best = Some((score, candidate_nodes, candidate_edges));
        }
    }

    best.map(|(_, nodes, edges)| (nodes, edges))
}

/// Drop nodes no longer reachable from the root, and the edges into them.
fn prune_unreachable(nodes: &mut Vec<GraphNode>, edges: &mut Vec<GraphEdge>) {
    let Some(root) = nodes.first().map(|node| node.id.clone()) else {
        return;
    };
    let mut adjacency: HashMap<&str, Vec<&str>> = HashMap::new();
    for edge in edges.iter() {
        adjacency
            .entry(edge.from.as_str())
            .or_default()
            .push(edge.to.as_str());
    }

    let mut reachable: HashSet<String> = HashSet::new();
    let mut stack = vec![root];
    while let Some(id) = stack.pop() {
        if !reachable.insert(id.clone()) {
            continue;
        }
        for next in adjacency.get(id.as_str()).cloned().unwrap_or_default() {
            stack.push(next.to_string());
        }
    }
    nodes.retain(|node| reachable.contains(&node.id));
    edges.retain(|edge| reachable.contains(&edge.from) && reachable.contains(&edge.to));
}

#[cfg(test)]
mod cut_test {
    use super::*;
    use crate::batbelt::miro::layout::{layout_graph, LayoutConfig, LayoutEdge, LayoutNode};

    fn node(id: &str) -> GraphNode {
        GraphNode {
            id: id.to_string(),
            label: id.to_string(),
            kind: NodeKind::Screenshot,
            file_path: String::new(),
            start_line: 1,
            end_line: 2,
            depth: 0,
            font_size: 22,
            scale: 1.0,
            png_path: String::new(),
            png_width: 1000,
            png_height: 300,
            rendered_lines: Vec::new(),
            line_offset: 0,
            writes_storage: false,
        write_lines: Vec::new(),
        external_call_lines: Vec::new(),
        leads_to_write: false,
        write_call_lines: Vec::new(),
        }
    }

    fn edge(from: &str, to: &str) -> GraphEdge {
        GraphEdge {
            from: from.to_string(),
            to: to.to_string(),
            line_in_slice: 1,
            column: 0,
            symbol: to.to_string(),
        }
    }

    /// A callee with its own frame becomes a link card only while the frame keeps
    /// `FRAME_MIN` screenshots: `priced` → `book` + `priceIn`, both framed, used to end
    /// up as one screenshot and two cards.
    #[test]
    fn linking_to_deployed_frames_never_leaves_a_husk() {
        // priced → book → b1..b5 ; priced → priceIn → p1..p8
        let mut nodes = vec![node("priced"), node("book"), node("priceIn")];
        let mut edges = vec![edge("priced", "book"), edge("priced", "priceIn")];
        for i in 1..=5 {
            nodes.push(node(&format!("b{i}")));
            edges.push(edge("book", &format!("b{i}")));
        }
        for i in 1..=8 {
            nodes.push(node(&format!("p{i}")));
            edges.push(edge("priceIn", &format!("p{i}")));
        }
        let framed: HashSet<String> = ["book", "priceIn"].iter().map(|s| s.to_string()).collect();
        let (linked, kept) = link_deployed_frames(&mut nodes, &mut edges, &framed);
        // book goes out (10 screenshots stay), priceIn would leave 1: drawn inline.
        assert_eq!(linked, 1);
        assert_eq!(kept, vec!["priceIn".to_string()]);
        assert_eq!(screenshot_count(&nodes), 10);
        assert!(!nodes.iter().any(|n| n.id == "b1"));
        assert!(nodes.iter().any(|n| n.id == "p1"));
    }

    fn lay(nodes: &[GraphNode], edges: &[GraphEdge]) -> GraphLayout {
        let layout_nodes: Vec<LayoutNode> = nodes
            .iter()
            .map(|n| LayoutNode {
                id: n.id.clone(),
                width: n.board_width(),
                height: n.board_height(),
            })
            .collect();
        let layout_edges: Vec<LayoutEdge> = edges
            .iter()
            .map(|e| LayoutEdge {
                from: e.from.clone(),
                to: e.to.clone(),
                from_line_fraction: 0.5,
            })
            .collect();
        layout_graph(
            &nodes[0].id,
            &layout_nodes,
            &layout_edges,
            LayoutConfig::default(),
        )
    }

    /// The case that made the rule necessary. `shared` is reached from far away
    /// *and* from next door, so cutting the far call leaves it drawn for the
    /// near one and takes nothing off the frame. A card would be added for
    /// nothing.
    #[test]
    fn test_a_cut_that_saves_nothing_is_refused() {
        let nodes = vec![
            node("root"),
            node("far"),
            node("near"),
            node("shared"),
            node("child"),
        ];
        let edges = vec![
            edge("root", "far"),
            edge("far", "near"),
            edge("near", "shared"),
            edge("far", "shared"),
            edge("shared", "child"),
        ];

        if let Some((cut_nodes, _)) = best_cut(&nodes, &edges, &HashSet::new(), FRAME_TARGET) {
            assert!(
                screenshot_count(&cut_nodes) < screenshot_count(&nodes),
                "a cut that is taken has to free something"
            );
        }
    }

    /// Cutting one long call can never take a screenshot off the frame, and the
    /// layering is why.
    ///
    /// A call spans layers only because a longer path reaches the same function,
    /// and that path arrives through a different caller one layer above it. Cut
    /// the long call and the function still hangs off that other caller, with
    /// everything under it. There is no graph where this comes out otherwise, so
    /// there is no graph where a single cut pays for itself in space.
    #[test]
    fn test_a_long_call_always_has_a_nearer_caller() {
        for extra in 0..4 {
            let mut nodes = vec![node("root"), node("mid"), node("target"), node("child")];
            let mut edges = vec![
                edge("root", "mid"),
                edge("root", "target"),
                edge("mid", "target"),
                edge("target", "child"),
            ];
            // Lengthen the path a few different ways; the property holds anyway.
            for step in 0..extra {
                let id = format!("step{step}");
                nodes.push(node(&id));
                edges.push(edge("mid", &id));
                edges.push(edge(&id, "target"));
            }

            // Cut the long call specifically, rather than whichever cut is
            // best overall, since the claim is about that one.
            let long = edges
                .iter()
                .position(|e| e.from == "root" && e.to == "target")
                .expect("the long call");
            let mut cut_nodes = nodes.clone();
            let mut cut_edges = edges.clone();
            cut_edge(&mut cut_nodes, &mut cut_edges, long);

            assert_eq!(
                screenshot_count(&cut_nodes),
                screenshot_count(&nodes),
                "with {extra} extra hops, cutting the long call freed a screenshot"
            );
        }
    }

    /// A graph too small to split is left alone: the husk guard wins over the cut.
    ///
    /// Cutting root→a would strand `b` with it, which frees two screenshots — but both
    /// the piece (2) and the residual (1) land under `FRAME_MIN`, and a frame holding one
    /// screenshot that points at a frame holding two is a scavenger hunt, not a diagram.
    /// So there is no candidate at all.
    #[test]
    fn test_a_graph_below_the_husk_floor_is_not_cut() {
        let nodes = vec![node("root"), node("a"), node("b")];
        let edges = vec![edge("root", "a"), edge("a", "b")];

        assert!(nodes.len() < FRAME_MIN);
        assert!(best_cut(&nodes, &edges, &HashSet::new(), FRAME_TARGET).is_none());
    }
}

/// Frame URL for every function a card in this graph points at.
///
/// A function that already has a frame is reused; one that does not is deployed
/// first, so the card has somewhere to go. Distinct cards for the same function
/// collapse to one lookup, which is what makes several diagrams share a helper's
/// frame instead of each building its own.
async fn ensure_target_frames(
    nodes: &[GraphNode],
    options: &AutoDeployOptions,
    client: &MiroClient,
    allocator: &mut ShelfAllocator,
    cluster: &ClusterCtx,
) -> Result<HashMap<String, String>> {
    let wanted: Vec<(String, String)> = {
        let mut seen = HashSet::new();
        nodes
            .iter()
            .filter_map(|node| match &node.kind {
                NodeKind::Link { target, file } => Some((target.clone(), file.clone())),
                NodeKind::Screenshot => None,
            })
            .filter(|(target, _)| seen.insert(target.clone()))
            .collect()
    };
    if wanted.is_empty() {
        return Ok(HashMap::new());
    }

    let mut resolved = HashMap::new();
    for (target, target_file) in wanted {
        // Reuse ONLY a frame created earlier in THIS run for THIS cluster
        // (cluster_root == root AND a fresh, non-stale id). Anything else — the old
        // cluster, or a frame from another entry point's deploy — is drawn fresh, so
        // the cluster is fully self-contained in its clean zone and a helper shared
        // inside it is still drawn once.
        let reusable = {
            let created_here = EvmBatMetadata::read_metadata().ok().is_some_and(|m| {
                m.miro.auto.frames.iter().any(|f| {
                    f.entry_point == target
                        && f.cluster_root == cluster.root
                        && !cluster.stale_ids.contains(&f.frame_id)
                })
            });
            if created_here {
                live_frame_url(&target, Some(client)).await?
            } else {
                None
            }
        };
        if let Some(url) = reusable {
            println!("  {} reuses its frame", target.blue());
            resolved.insert(target, url);
            continue;
        }
        let metadata = EvmBatMetadata::read_metadata().change_context(EvmMiroError)?;

        let Some((contract, function)) = target.split_once('.') else {
            continue;
        };
        println!("  {} needs a frame of its own, deploying it first", target.blue());
        // Boxed because this is the recursive step: the frame being built for a
        // helper can itself need cards, and those need frames.
        Box::pin(deploy_one(
            &metadata,
            contract,
            function,
            &target_file,
            options,
            Some(client),
            allocator,
            false,
            cluster,
        ))
        .await?;

        let metadata = EvmBatMetadata::read_metadata().change_context(EvmMiroError)?;
        if let Some(created) = metadata
            .miro
            .auto
            .frames
            .iter()
            .find(|frame| frame.entry_point == target)
        {
            resolved.insert(target, created.frame_url.clone());
        }
    }
    Ok(resolved)
}

/// The frame URL for a function, if it is registered **and** still on the board.
///
/// A registry entry outlives the frame it names: boards are edited by hand, and
/// deleting a frame in Miro leaves the entry behind. Checking the board costs
/// one read and turns "you already deployed this" into something true, rather
/// than a refusal to redeploy what is no longer there. A stale entry is dropped
/// on the way past, so the question is only asked once.
/// `bat-cli relink`: point a record at the frame it belongs to, or report the drift.
///
/// Arranging a board is part of reading it, and cutting a frame and pasting it elsewhere gives
/// every widget a new id — so the registry ends up describing frames that no longer exist,
/// while the frames themselves are right there under the same titles. Deploying again would
/// fix the record and lose the arrangement, which is the wrong trade.
pub async fn run_relink(
    entry_point: Option<String>,
    frame_url: Option<String>,
    check: bool,
) -> Result<()> {
    let client = MiroClient::new_refreshed()
        .await
        .change_context(EvmMiroError)?;
    let metadata = EvmBatMetadata::read_metadata().change_context(EvmMiroError)?;

    if check || entry_point.is_none() {
        let frames = client.list_frames().await.change_context(EvmMiroError)?;
        let mut alive = 0usize;
        let mut fixable: Vec<(String, usize)> = Vec::new();
        let mut gone: Vec<String> = Vec::new();
        for record in &metadata.miro.auto.frames {
            if frames.iter().any(|frame| frame.id == record.frame_id) {
                alive += 1;
                continue;
            }
            let wanted = format!("auto: {}", record.entry_point);
            let matches = frames.iter().filter(|frame| frame.title == wanted).count();
            if matches == 0 {
                gone.push(record.entry_point.clone());
            } else {
                fixable.push((record.entry_point.clone(), matches));
            }
        }
        println!("{} frame(s) recorded, {alive} still where the registry says", metadata.miro.auto.frames.len());
        for (entry_point, matches) in &fixable {
            if *matches == 1 {
                println!(
                    "  {} {} moved — {} re-anchors it",
                    "↻".yellow(),
                    entry_point,
                    format!("bat-cli relink {entry_point}").green()
                );
            } else {
                println!(
                    "  {} {} has {matches} frames with its title — {} picks one",
                    "?".yellow(),
                    entry_point,
                    format!("bat-cli relink {entry_point} --frame-url <url>").green()
                );
            }
        }
        for entry_point in &gone {
            println!("  {} {} is not on the board at all", "✗".red(), entry_point);
        }
        if fixable.is_empty() && gone.is_empty() {
            println!("  {} nothing to relink", "✓".green());
        }
        return Ok(());
    }

    let entry_point = entry_point.expect("checked above");
    let Some(record) = metadata
        .miro
        .auto
        .frames
        .iter()
        .find(|frame| frame.entry_point == entry_point)
        .cloned()
    else {
        return Err(Report::new(EvmMiroError)
            .attach_printable(format!("no frame recorded for `{entry_point}`"))
            .attach(crate::Suggestion(
                "run `bat-cli relink --check` to see what is recorded".to_string(),
            )));
    };

    // Named frame: take the widget id straight out of the URL the board hands out.
    if let Some(url) = frame_url {
        let Some(id) = url
            .split("moveToWidget=")
            .nth(1)
            .map(|rest| rest.split(['&', '#']).next().unwrap_or(rest).to_string())
        else {
            return Err(Report::new(EvmMiroError)
                .attach_printable(format!("no `moveToWidget=` id in `{url}`"))
                .attach(crate::Suggestion(
                    "copy the frame's link from Miro (right-click → Copy link)".to_string(),
                )));
        };
        let frames = client.list_frames().await.change_context(EvmMiroError)?;
        let Some(frame) = frames.iter().find(|frame| frame.id == id) else {
            return Err(Report::new(EvmMiroError)
                .attach_printable(format!("no frame with id {id} on this board")));
        };
        let record = rebuild_record(record, frame, &client).await?;
        println!(
            "{} {} → {}",
            "✓".green(),
            entry_point.bold(),
            record.frame_url.blue()
        );
        return Ok(());
    }

    match reanchor_frame(&entry_point, &client).await? {
        Some(record) => {
            println!(
                "{} {} → {}",
                "✓".green(),
                entry_point.bold(),
                record.frame_url.blue()
            );
            Ok(())
        }
        None => Err(Report::new(EvmMiroError)
            .attach_printable(format!(
                "no frame titled `auto: {entry_point}` on the board"
            ))
            .attach(crate::Suggestion(
                "pass --frame-url <url> if it was renamed, or deploy it again".to_string(),
            ))),
    }
}

/// The label a node's screenshot was uploaded with, which is what survives on the board.
///
/// Node ids are `Contract::function` (plus `@line` when the name is overloaded); the image's
/// title is the dotted `Contract.function`. A link card has neither — it is a shape, and the
/// board keeps no title for it, so it cannot be recognised after a paste.
fn label_for_node(node_id: &str) -> Option<String> {
    if node_id.starts_with('\u{0}') {
        return None;
    }
    let base = node_id.split('@').next().unwrap_or(node_id);
    Some(base.replace("::", "."))
}

/// Re-point a frame's record at the copy that is actually on the board.
///
/// Cutting and pasting a frame in Miro gives it and every child a NEW id, which orphans the
/// registry — and dragging does not, so the difference is invisible to whoever is arranging
/// the board. The paste keeps the titles, though: the frame is still `auto: <entry point>`
/// and each screenshot still carries its function's label, so the record can be rebuilt from
/// what is there.
///
/// Shapes cannot: link cards, connector markers and borders carry no title. Their recorded
/// ids are dropped, which is safe because `undeploy` deletes the frame's live children rather
/// than the ids it once wrote down.
async fn reanchor_frame(
    title: &str,
    client: &MiroClient,
) -> Result<Option<AutoDeployedFrame>> {
    let record = {
        let metadata = EvmBatMetadata::read_metadata().change_context(EvmMiroError)?;
        metadata
            .miro
            .auto
            .frames
            .iter()
            .find(|frame| frame.entry_point == title)
            .cloned()
    };
    let Some(record) = record else {
        return Ok(None);
    };

    let wanted = format!("auto: {title}");
    let frames = client.list_frames().await.change_context(EvmMiroError)?;
    let candidates: Vec<_> = frames.iter().filter(|frame| frame.title == wanted).collect();

    match candidates.len() {
        0 => Ok(None),
        // A duplicated frame (or a paste whose original is still there) makes this a
        // question about which one the auditor means, and that is theirs to answer.
        _ if candidates.len() > 1 => Err(Report::new(EvmMiroError)
            .attach_printable(format!(
                "{} frames on the board are titled `{wanted}`:\n    {}",
                candidates.len(),
                candidates
                    .iter()
                    .map(|frame| client.frame_url(&frame.id))
                    .collect::<Vec<_>>()
                    .join("\n    ")
            ))
            .attach(crate::Suggestion(format!(
                "pick one: `bat-cli relink {title} --frame-url <url>`"
            )))),
        _ => {
            let frame = candidates[0];
            let record = rebuild_record(record, frame, client).await?;
            println!(
                "  {} re-anchored {} to the frame now on the board (its id changed, so it was cut and pasted)",
                "↻".yellow(),
                title.bold()
            );
            Ok(Some(record))
        }
    }
}

/// Rewrite a record against a frame that is really on the board, matching every screenshot by
/// the title it carries.
async fn rebuild_record(
    mut record: AutoDeployedFrame,
    frame: &crate::batbelt::miro::client::BoardFrame,
    client: &MiroClient,
) -> Result<AutoDeployedFrame> {
    let children = client
        .frame_children(&frame.id, (frame.x, frame.y, frame.width, frame.height))
        .await
        .unwrap_or_default();
    let by_title: HashMap<&str, &crate::batbelt::miro::client::FrameChild> = children
        .iter()
        .filter(|child| !child.title.is_empty())
        .map(|child| (child.title.as_str(), child))
        .collect();

    let mut images = Vec::new();
    let mut image_dims = Vec::new();
    let mut node_positions = Vec::new();
    for (node_id, _) in &record.images {
        let Some(label) = label_for_node(node_id) else {
            continue;
        };
        let Some(child) = by_title.get(label.as_str()) else {
            continue;
        };
        images.push((node_id.clone(), child.id.clone()));
        image_dims.push((node_id.clone(), child.width as u32, child.height as u32));
        node_positions.push((node_id.clone(), child.x, child.y));
    }
    let screenshots = record
        .screenshots
        .iter()
        .filter_map(|shot| {
            by_title.get(shot.label.as_str()).map(|child| {
                crate::batbelt::evm::metadata::bat_metadata::ExtraScreenshot {
                    label: shot.label.clone(),
                    item_id: child.id.clone(),
                    x: child.x,
                    y: child.y,
                    width: child.width,
                    height: child.height,
                }
            })
        })
        .collect();

    record.frame_id = frame.id.clone();
    record.frame_url = client.frame_url(&frame.id);
    record.x = frame.x;
    record.y = frame.y;
    record.width = frame.width;
    record.height = frame.height;
    record.images = images;
    record.image_dims = image_dims;
    record.node_positions = node_positions;
    record.screenshots = screenshots;
    // Untitled items (link cards, markers, borders) and the connectors between them cannot be
    // recognised on the pasted copy. Their old ids point at nothing, so drop them rather than
    // keep a list that would delete items on somebody else's frame.
    record.link_cards.clear();
    record.callee_connectors.clear();
    record.connector_ids.clear();
    record.marker_ids.clear();
    record.border_ids.clear();
    save_frame_record(&record)?;
    Ok(record)
}

/// The record for `title`, re-anchored if the board moved underneath it, or `None` when the
/// frame really is gone (in which case the record is forgotten, as before).
pub(crate) async fn ensure_frame_record(
    title: &str,
    client: &MiroClient,
) -> Result<Option<AutoDeployedFrame>> {
    let record = {
        let metadata = EvmBatMetadata::read_metadata().change_context(EvmMiroError)?;
        metadata
            .miro
            .auto
            .frames
            .iter()
            .find(|frame| frame.entry_point == title)
            .cloned()
    };
    let Some(record) = record else {
        return Ok(None);
    };
    if client.item_exists(&record.frame_id).await {
        return Ok(Some(record));
    }
    if let Some(reanchored) = reanchor_frame(title, client).await? {
        return Ok(Some(reanchored));
    }

    println!(
        "  {} the frame recorded for {} is gone from the board; forgetting it",
        "note:".yellow(),
        title
    );
    let owner = title.to_string();
    EvmBatMetadata::update_metadata(move |metadata| {
        metadata
            .miro
            .auto
            .frames
            .retain(|frame| frame.entry_point != owner);
    })
    .change_context(EvmMiroError)?;
    Ok(None)
}

async fn live_frame_url(title: &str, client: Option<&MiroClient>) -> Result<Option<String>> {
    let Some(client) = client else {
        let metadata = EvmBatMetadata::read_metadata().change_context(EvmMiroError)?;
        return Ok(metadata
            .miro
            .auto
            .frames
            .iter()
            .find(|frame| frame.entry_point == title)
            .map(|frame| frame.frame_url.clone()));
    };
    Ok(ensure_frame_record(title, client)
        .await?
        .map(|record| record.frame_url))
}

#[cfg(test)]
mod natspec_test {
    use super::*;

    /// Writes `body` to a scratch .sol file and returns its path.
    fn sol_fixture(name: &str, body: &str) -> String {
        let dir = std::env::temp_dir().join(format!("bat-cli-natspec-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join(format!("{name}.sol"));
        std::fs::write(&path, body).unwrap();
        path.to_string_lossy().to_string()
    }

    #[test]
    fn takes_a_run_of_slash_slash_slash_lines() {
        //                   1                2                3               4
        let path = sol_fixture("triple", "contract C {\n    /// @notice a\n    /// @dev b\n    function f() {}\n}\n");
        assert_eq!(natspec_start(&path, 4), 2); // the whole run, not just the last line
    }

    #[test]
    fn takes_a_block_comment_whole() {
        let path = sol_fixture(
            "block",
            "contract C {\n    /**\n     * @notice a\n     */\n    function f() {}\n}\n",
        );
        assert_eq!(natspec_start(&path, 5), 2); // opens at `/**`, four lines up
    }

    #[test]
    fn takes_a_one_line_block() {
        let path = sol_fixture("oneline", "contract C {\n    /** @notice a */\n    function f() {}\n}\n");
        assert_eq!(natspec_start(&path, 3), 2);
    }

    #[test]
    fn leaves_an_ordinary_comment_out() {
        // `//` is a note to the reader, not documentation of the function.
        let path = sol_fixture("plain", "contract C {\n    // just a note\n    function f() {}\n}\n");
        assert_eq!(natspec_start(&path, 3), 3);
    }

    #[test]
    fn a_blank_line_detaches_the_comment() {
        // A comment separated by a blank line belongs to whatever came before it as
        // often as not; pulling it in would put another function's docs on this one.
        let path = sol_fixture("detached", "contract C {\n    /// @notice a\n\n    function f() {}\n}\n");
        assert_eq!(natspec_start(&path, 4), 4);
    }

    #[test]
    fn takes_nothing_when_there_is_nothing() {
        let path = sol_fixture("bare", "contract C {\n    function f() {}\n}\n");
        assert_eq!(natspec_start(&path, 2), 2);
        // Out of range and line 1 are handled without panicking.
        assert_eq!(natspec_start(&path, 1), 1);
        assert_eq!(natspec_start(&path, 999), 999);
        assert_eq!(natspec_start("/no/such/file.sol", 7), 7);
    }

    #[test]
    fn doc_lines_above_is_zero_unless_asked_for() {
        let path = sol_fixture("gated", "contract C {\n    /// @notice a\n    function f() {}\n}\n");
        let mut options = AutoDeployOptions::default();
        assert_eq!(doc_lines_above(&options, &path, 3), 0);
        options.with_documentation = true;
        assert_eq!(doc_lines_above(&options, &path, 3), 1);
    }
}