tilezz 0.1.4

Utilities to work with perfect-precision polygonal tiles built on top of cyclotomic integer rings.
Documentation
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
//! Neighborhood types: catalog of local *interfaces* between a tile
//! and any legal context patch that could meet it along one
//! contiguous edge run, plus the post-absorption "surrounded tile"
//! states that arise once the central tile's edges are all
//! consumed.
//!
//! # Two phases
//!
//! The catalog has two kinds of entries (unified as [`NtEntry`]):
//!
//! - **Phase 1 — [`NeighborhoodType`]**: the central tile is still
//!   on the patch boundary along a matched segment, with CW/CCW
//!   frontier vertices where context tiles can still be added.
//!   This is the original "open NT" model.
//!
//! - **Phase 2 — [`SurroundedTile`]**: a phase-1 step absorbed the
//!   last central edge, so the central is now interior; only its
//!   vertices may remain incident with the boundary (= an "open
//!   vertex" where the angle gap hasn't closed). The full
//!   `GrowingPatch` boundary state is stored, in normalized form;
//!   see [`SurroundedTile::to_patch`] for reconstruction.
//!
//! Phase-2 entries either:
//!   - **closed** (no open vertex remaining; central fully
//!     surrounded — terminal Blessed state), or
//!   - **open** (one open vertex remains; phase-2 BFS attempts to
//!     close it by gluing further petals).
//!
//! # Why grow incrementally
//!
//! A naive "enumerate all length-≤k boundary strings" approach has
//! to separately filter realizable from junk strings — a costly
//! secondary step. Growing the patch one tile at a time via BFS
//! gives realizability for free: every entry is built from a
//! known-realizable predecessor, so no candidate has to be checked
//! against geometric legality post-hoc.
//!
//! The trade-off: the BFS catalog is **finer** than the interface
//! equivalence quotient. The same configuration can be reached by
//! multiple distinct growth histories, and each history becomes its
//! own catalog entry. The true interface quotient is a coarser,
//! derived view; the canonicalisation pass that runs after each
//! glue (via [`GrowingPatch::normalize`]) deduplicates aggressively
//! but not exhaustively.
//!
//! # Classification → forbidden patterns
//!
//! Every entry gets a `Dead`/`Undead`/`Blessed`/`Free` reachability
//! kind via [`NeighborhoodIndex::classify_all`]. The Dead and
//! Undead interfaces are the actionable output: they are the local
//! patterns a tiling can never recover from. Downstream consumers
//! treat them as **forbidden patterns** that must not appear in any
//! extending glue. Together with the dead/undead VTs (a finer
//! per-vertex constraint, see `vertextypes.rs`), these constraints
//! prune the tile-growth search.
//!
//! See [`NeighborhoodType`] / [`SurroundedTile`] for entry layout
//! and [`NeighborhoodIndex::new`] for the BFS algorithm.
//!
//! # ⚠ KNOWN GAP — incomplete segment enumeration
//!
//! **The BFS as it stands does NOT enumerate every boundary segment
//! that can appear on a legal patch.** A *segment* (in the sense of
//! [`crate::geom::segtypes`]) is a maximal run of edges from one
//! tile, bounded by two open-vertex junctions on the boundary. The
//! catalog only sees segments that appear inside some BFS state's
//! **extended-match window** (= matched interval + one ctx segment of
//! pad on each side); segments that never sit inside such a window
//! are missed.
//!
//! ## Concrete example
//!
//! In a hexagonal closed corona (= 7-hex flower, [`SurroundedTile`]
//! `is_closed=true`), the outer boundary has 6 junctions, each between
//! two adjacent outer hexes, spaced 3 hex edges apart. The segment
//! between two consecutive corona junctions is **3 edges of one outer
//! hex**. Locally this is "two hexes meeting at a junction with no
//! inner edge" — geometrically the same junction structure as a plain
//! 2-hex glue. But a 2-hex glue's segment spans **5 edges** of one
//! hex, not 3. No phase-1 state's extended-match window produces the
//! 3-edge-per-tile spacing, so its segment type is invisible to the
//! BFS catalog. Empirically: of 216 distinct phase-2-closed seg pairs
//! on hex, **0** match any phase-1 LHS segment pair. (Spectre shows
//! the same asymmetry on a larger universe.)
//!
//! ## Why this matters
//!
//! Downstream uses that treat the seg catalog as exhaustive (e.g.,
//! propagating per-seg classifications, rewriting-system analyses)
//! will mis-classify the missed segs. A correct seg enumeration would
//! need a different algorithm — one that doesn't tie segments to a
//! match-anchor neighborhood. This is an open design problem;
//! [`crate::geom::segtypes`] currently builds against the
//! incomplete view and is limited accordingly.

use std::collections::VecDeque;
use std::sync::Arc;

use rustc_hash::FxHashMap;

use crate::analysis::matchtypes::MatchTypeIndex;
use crate::cyclotomic::IsRing;
use crate::geom::matches::{EdgeRange, Segment};
use crate::geom::patch::{GrowingPatch, PatchMatch, PatchSeed};
use crate::geom::tileset::TileSet;
use crate::geom::vertices::{EdgeInfo, OpenVertexType, TransitionSide};

/// One catalog entry of a local **interface** between a tile and any
/// legal context patch sharing one contiguous matched edge run with
/// it. The geometrically-significant content is the central + the
/// shape of the matched segment; everything else about the context
/// (its outer perimeter, internal tile arrangement, total tile
/// count) is incidental to the interface but is retained here to
/// support the BFS that generates the catalog.
///
/// # Interface vs BFS entry
///
/// **A `NeighborhoodType` is a BFS state, not an interface class.**
/// The catalog can contain multiple BFS entries that describe the
/// same interface, reached via different growth histories. The
/// interface-equivalence quotient (= same `central_tile_id`, same
/// `cw_anchor_on_central`, same canonical matched-segment boundary)
/// is a coarser view, computable from this catalog but not
/// represented as a separate type. Downstream consumers exporting
/// forbidden-pattern sets work at the interface level; the BFS works
/// at the entry level for combinatorial cleanliness (every step
/// adds exactly one tile, no canonicalization-collapse cases to
/// reason about).
///
/// # Field semantics
///
/// The matched segment is the CCW range `[cw_anchor_on_central,
/// ccw_anchor_on_central)` on the central tile (mod `central_n`); its
/// length is `(ccw_anchor_on_central - cw_anchor_on_central) mod
/// central_n`. The corresponding covered segment on the context boundary
/// is described by `vt_seq`: the sequence of context-context junctions
/// incident with the match, in CCW order from `vt_seq[0]` (the CCW-most
/// junction reachable CW from the CW frontier) to `vt_seq.last()` (the
/// CW-most junction reachable CCW from the CCW frontier).
///
/// Frontier positions on context are parameterized by short distances
/// from `vt_seq`'s endpoints:
/// * `cw_anchor_on_context` = CW distance from `vt_seq[0]`'s junction to
///   the CW frontier vertex on context.
/// * `ccw_anchor_on_context` = CCW distance from `vt_seq.last()`'s
///   junction to the CCW frontier vertex on context.
///
/// `num_ctx_tiles` records the number of context tiles in the matched
/// patch; it grows by exactly 1 per BFS step regardless of direction, so
/// it gives the natural DAG layering for both CCW and CW transitions.
///
/// # Derived (redundant) fields
///
/// The CCW-side anchors are cached derivations of the CW-side anchors
/// plus the geometry; they are stored to avoid recomputation per
/// BFS step but are not independent state:
///
/// * `ccw_anchor_on_central = (cw_anchor_on_central - match_len) mod
///   central_n`, where
///   `match_len = (cw_anchor_on_central - ccw_anchor_on_central) mod
///   central_n` (the same equation in the other direction).
/// * `ccw_anchor_on_context` is determined by walking the
///   reconstructed context to find the CCW-most junction within the
///   covered segment - see [`try_construct_nt_from_cw`] for the
///   canonical re-derivation.
///
/// Constructing a `NeighborhoodType` directly (as the parser and
/// `seed_phase` do) can produce inconsistent CCW fields. The
/// invariant - "stored CCW fields equal what the geometry implies" -
/// is checked by [`nt_is_valid`] and is part of `validate`'s
/// contract.
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct NeighborhoodType {
    pub central_tile_id: usize,
    pub cw_anchor_on_central: usize,
    pub ccw_anchor_on_central: usize,
    pub cw_anchor_on_context: usize,
    pub ccw_anchor_on_context: usize,
    pub num_ctx_tiles: usize,
    pub vt_seq: Vec<OpenVertexType>,
}

/// Phase-2 entry: the central tile has had all of its edges absorbed
/// by surrounding tiles ("surrounded"). Stores the full `GrowingPatch`
/// boundary state, in **normalized** form (= rotated to lex-min
/// boundary angles, `patch_tile_ids` densified to `0..k` by
/// CCW-first-occurrence). Two SurroundedTiles describing geometrically
/// equivalent patches compare equal via derived `Eq`/`Hash`.
///
/// `is_closed = true` when the corona fully encloses the central
/// (no boundary vertex incident with central). The entry is a
/// terminal Blessed state — it has no outgoing transitions, and
/// [`NeighborhoodIndex::classify_all`] recognises it as an
/// escape destination for the entries that transition into it.
///
/// `is_closed = false` when an open vertex remains on the boundary.
/// `open_vertex_pos` is the boundary position of that open vertex
/// in the normalized boundary (= where phase-2 BFS attaches petals).
///
/// To reconstruct as a `GrowingPatch`, use [`SurroundedTile::to_patch`].
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct SurroundedTile {
    pub central_tile_id: usize,
    pub is_closed: bool,
    /// Open vertex's boundary position in the normalized boundary
    /// (only meaningful when `!is_closed`; set to 0 by convention
    /// for closed entries).
    pub open_vertex_pos: usize,
    /// Number of distinct boundary tile instances (= `next_tile_id`
    /// after [`GrowingPatch::normalize`]). Fully-interior tiles are
    /// not counted here — see normalize's note.
    pub num_tile_instances: usize,
    pub angles: Vec<i8>,
    pub edges: Vec<EdgeInfo>,
    pub inner_chains: Vec<Vec<EdgeInfo>>,
    pub patch_tile_ids: Vec<usize>,
}

impl SurroundedTile {
    /// Reconstruct the surrounded-tile patch as a `GrowingPatch`. Returns
    /// `None` only on `from_parts` invariant violations (= shouldn't
    /// happen for SurroundedTiles produced by the BFS).
    ///
    /// In debug builds, asserts the internal-consistency invariants
    /// callers must uphold:
    /// - Per-position arrays (`angles`, `edges`, `inner_chains`,
    ///   `patch_tile_ids`) are the same length.
    /// - `num_tile_instances` equals `max(patch_tile_ids) + 1` (= the
    ///   dense-renumbering output of [`GrowingPatch::normalize`]).
    /// - `open_vertex_pos < angles.len()` when `!is_closed`.
    pub fn to_patch<T: IsRing>(
        &self,
        match_index: Arc<MatchTypeIndex<T>>,
    ) -> Option<GrowingPatch<T>> {
        let n = self.angles.len();
        debug_assert_eq!(self.edges.len(), n, "edges length mismatch");
        debug_assert_eq!(self.inner_chains.len(), n, "inner_chains length mismatch");
        debug_assert_eq!(
            self.patch_tile_ids.len(),
            n,
            "patch_tile_ids length mismatch"
        );
        debug_assert_eq!(
            self.num_tile_instances,
            self.patch_tile_ids.iter().max().map_or(0, |m| m + 1),
            "num_tile_instances doesn't match patch_tile_ids"
        );
        debug_assert!(
            self.is_closed || self.open_vertex_pos < n,
            "open_vertex_pos {} out of range for boundary len {}",
            self.open_vertex_pos,
            n
        );
        GrowingPatch::from_parts(
            match_index,
            self.angles.clone(),
            self.edges.clone(),
            self.inner_chains.clone(),
            self.patch_tile_ids.clone(),
            self.num_tile_instances,
        )
    }
}

/// A catalog entry: either a phase-1 NT (central still on the
/// patch boundary along a matched segment) or a phase-2 SurroundedTile
/// (central fully edge-absorbed, possibly with an open vertex).
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum NtEntry {
    Phase1(NeighborhoodType),
    Phase2(SurroundedTile),
}

impl NtEntry {
    pub fn central_tile_id(&self) -> usize {
        match self {
            NtEntry::Phase1(nt) => nt.central_tile_id,
            NtEntry::Phase2(st) => st.central_tile_id,
        }
    }

    /// For phase-1 entries: the matched-segment `vt_seq`. For phase-2
    /// entries: an empty slice (the surrounded-tile representation is
    /// now boundary state, not a junction sequence; query
    /// [`SurroundedTile::to_patch`] and `junction_vertex_type_at` for
    /// per-junction info).
    pub fn vt_seq(&self) -> &[OpenVertexType] {
        match self {
            NtEntry::Phase1(nt) => &nt.vt_seq,
            NtEntry::Phase2(_) => &[],
        }
    }

    pub fn as_phase1(&self) -> Option<&NeighborhoodType> {
        match self {
            NtEntry::Phase1(nt) => Some(nt),
            _ => None,
        }
    }

    pub fn as_phase2(&self) -> Option<&SurroundedTile> {
        match self {
            NtEntry::Phase2(st) => Some(st),
            _ => None,
        }
    }
}

#[derive(
    Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, serde::Serialize, serde::Deserialize,
)]
pub enum NtKind {
    Dead,
    Undead,
    Blessed,
    Free,
}

#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct NtTransition {
    pub src_id: usize,
    pub dst_id: usize,
    pub side: TransitionSide,
    pub tile_id: usize,
    pub tile_offset: usize,
}

pub struct NeighborhoodIndex<T: IsRing> {
    tileset: Arc<TileSet<T>>,
    entries: Vec<NtEntry>,
    transitions: Vec<NtTransition>,
}

impl<T: IsRing> NeighborhoodIndex<T> {
    /// Build the full open-NT catalog for `tileset` by BFS over the
    /// neighborhood-transition graph.
    ///
    /// # Catalog vs interface quotient
    ///
    /// The catalog is **finer than the interface-equivalence
    /// quotient**: the same interface (= same central +
    /// same canonical matched-segment boundary) can be reached by
    /// multiple growth histories, and the BFS records each as a
    /// distinct entry. The interface quotient is therefore a derived
    /// view, not directly stored. This is intentional - the BFS gets
    /// "every step adds exactly one tile" as a clean invariant in
    /// exchange for that over-counting. Consumers wanting the
    /// quotient compute it post-hoc by grouping entries by their
    /// canonical interface fingerprint.
    ///
    /// # Algorithm
    ///
    /// 1. **Seed generation.** For every match-type `(tile_a,
    ///    start_a, tile_b, start_b, len)` in [`MatchTypeIndex`]:
    ///    build a two-tile patch by gluing `tile_b` to `tile_a` and
    ///    normalize. For every additional candidate from
    ///    [`GrowingPatch::get_all_matches`], try gluing a third
    ///    ("central") tile to a clone (non-convex tiles can collide;
    ///    skip on failure). Filter the patch's junctions to those
    ///    incident with the match (CCW distance from the match
    ///    anchor is at most the match length) - that's `vt_seq`.
    ///    Validate via [`nt_is_valid`] and dedup against the BFS's
    ///    `PartialEq` dedup key (which is the full
    ///    `NeighborhoodType`, not the interface).
    /// 2. **BFS growth.** Dequeue each entry id and dispatch:
    ///    - [`NtEntry::Phase1`]: enumerate one-petal CCW successors
    ///      via [`explore_phase1`]. Each successor is either another
    ///      phase-1 NT (central edges still remain) or a phase-2
    ///      [`SurroundedTile`] (central edges all absorbed).
    ///    - [`NtEntry::Phase2`] (open only): explore one petal at
    ///      the open vertex via [`explore_phase2`]; closed phase-2
    ///      entries are terminal Blessed states with no outgoing
    ///      transitions ([`Self::classify_all`] recognises them
    ///      directly as escape destinations).
    ///
    ///    New entries are enqueued; transitions are recorded.
    ///    Every step adds exactly one tile to the underlying patch,
    ///    so the transition graph is a DAG.
    ///
    /// # CCW-only exploration
    ///
    /// Phase-1 BFS only explores in the CCW direction; the
    /// `spectre_ccw_only_is_complete` regression test confirms this
    /// is complete (= every brute-force petal candidate at the CCW
    /// frontier either closes the central or produces an NT already
    /// in the catalog). Phase-2 BFS likewise only attaches at the
    /// open vertex's CCW edge.
    pub fn new(tileset: Arc<TileSet<T>>) -> Self {
        let match_index = Arc::new(MatchTypeIndex::new(Arc::clone(&tileset)));
        // IDs are 1-based: entries[i] has id i + 1. `seen` and
        // transitions store ids, not indices.
        let mut state = BfsState::default();
        seed_phase(&mut state, &match_index);
        bfs_phase(&mut state, &match_index);

        let BfsState {
            entries,
            transitions,
            ..
        } = state;

        NeighborhoodIndex {
            tileset,
            entries,
            transitions,
        }
    }

    /// All catalog entries in BFS-discovery order.
    /// `entries()[id - 1]` is the entry for 1-based id `id`.
    pub fn entries(&self) -> &[NtEntry] {
        &self.entries
    }

    /// Number of catalog entries (phase 1 + phase 2). Ids run
    /// `1..=num_types()`.
    pub fn num_types(&self) -> usize {
        self.entries.len()
    }

    /// Number of phase-1 (open-NT) entries.
    pub fn num_phase1(&self) -> usize {
        self.entries
            .iter()
            .filter(|e| matches!(e, NtEntry::Phase1(_)))
            .count()
    }

    /// Number of phase-2 (SurroundedTile) entries.
    pub fn num_phase2(&self) -> usize {
        self.entries
            .iter()
            .filter(|e| matches!(e, NtEntry::Phase2(_)))
            .count()
    }

    /// All recorded BFS transitions, in BFS-emission order. Both
    /// `src_id` and `dst_id` are 1-based entry ids.
    pub fn transitions(&self) -> &[NtTransition] {
        &self.transitions
    }

    /// The tileset this catalog was built from.
    pub fn tileset(&self) -> &Arc<TileSet<T>> {
        &self.tileset
    }

    /// Classify every entry as Dead / Undead / Blessed / Free by
    /// walking the transition graph.
    ///
    /// * `Dead` — no outgoing transitions, not a closed phase-2 terminal.
    /// * `Undead` — has outgoing transitions, every reachable path
    ///   eventually traps at a Dead/Undead entry (never reaches a
    ///   closed phase-2 terminal).
    /// * `Blessed` — every outgoing transition reaches a closed
    ///   phase-2 terminal or another Blessed entry. Closed phase-2
    ///   terminals are themselves Blessed.
    /// * `Free` — has at least one path that reaches a closed
    ///   terminal AND at least one that traps at Dead/Undead.
    ///
    /// # Downstream use: forbidden patterns
    ///
    /// The Dead and Undead kinds are the actionable output of the
    /// classification. Their match-side boundary strings are
    /// **forbidden local boundary patterns** for the tileset: any
    /// tile growth that would create one of these interfaces is
    /// guaranteed to never complete to a full corona, so consumers
    /// growing tilings prune candidate glues against this set. The
    /// vertex-level analog lives in `vertextypes.rs` (Dead/Undead
    /// VTs are even smaller local forbidden patterns; every
    /// Dead/Undead NT contains at least one Dead/Undead VT, so the
    /// VT antichain is the minimal-pattern compression of the
    /// constraint set).
    ///
    /// # Algorithm
    ///
    /// O(n + m) via worklist propagation on the reverse adjacency.
    pub fn classify_all(&self) -> Vec<NtKind> {
        // Transition ids are 1-based; convert with `- 1` when indexing into
        // these per-entry vectors.
        //
        // Closed phase-2 SurroundedTile entries are "terminal-good" —
        // they have no outgoing transitions but represent a valid
        // closure (= central fully surrounded). They are the *only*
        // Blessed seeds. All Blessed and Undead status reaches other
        // entries via standard reverse-edge propagation.
        let n = self.entries.len();
        let mut is_closed_terminal = vec![false; n];
        for (i, entry) in self.entries.iter().enumerate() {
            if let NtEntry::Phase2(st) = entry
                && st.is_closed
            {
                is_closed_terminal[i] = true;
            }
        }

        let mut succ_count = vec![0usize; n];
        let mut preds: Vec<Vec<usize>> = vec![vec![]; n];
        let mut has_outgoing = vec![false; n];
        for t in &self.transitions {
            let src_idx = t.src_id - 1;
            let dst_idx = t.dst_id - 1;
            has_outgoing[src_idx] = true;
            succ_count[src_idx] += 1;
            preds[dst_idx].push(src_idx);
        }

        // Cursed propagation: an entry becomes cursed when all of its
        // successors are cursed. Closed terminals are never cursed
        // (they're seeded as Blessed instead), so any entry with a
        // closed-terminal successor has remaining > 0 permanently —
        // the "has-closing-escape" exemption is implicit.
        let mut cursed = vec![false; n];
        let mut remaining = succ_count.clone();
        let mut queue: VecDeque<usize> = VecDeque::new();
        for i in 0..n {
            if !has_outgoing[i] && !is_closed_terminal[i] {
                cursed[i] = true;
                queue.push_back(i);
            }
        }
        while let Some(v) = queue.pop_front() {
            for &p in &preds[v] {
                if cursed[p] {
                    continue;
                }
                remaining[p] -= 1;
                if remaining[p] == 0 && succ_count[p] > 0 {
                    cursed[p] = true;
                    queue.push_back(p);
                }
            }
        }

        // Blessed propagation: seed with closed terminals only.
        // Standard reverse-edge propagation marks each predecessor
        // Blessed once all of its successors are Blessed.
        let mut blessed = vec![false; n];
        let mut remaining = succ_count.clone();
        let mut queue: VecDeque<usize> = VecDeque::new();
        for i in 0..n {
            if is_closed_terminal[i] {
                blessed[i] = true;
                queue.push_back(i);
            }
        }
        while let Some(v) = queue.pop_front() {
            for &p in &preds[v] {
                if blessed[p] {
                    continue;
                }
                remaining[p] -= 1;
                if remaining[p] == 0 {
                    blessed[p] = true;
                    queue.push_back(p);
                }
            }
        }

        (0..n)
            .map(|i| {
                if cursed[i] && !has_outgoing[i] {
                    NtKind::Dead
                } else if cursed[i] {
                    NtKind::Undead
                } else if blessed[i] {
                    NtKind::Blessed
                } else {
                    NtKind::Free
                }
            })
            .collect()
    }

    /// Return the 1-based ids of entries that fail self-consistency:
    /// phase-1 entries that don't reconstruct from their CW-side
    /// fields. Phase-2 entries are validated by attempting
    /// [`SurroundedTile::to_patch`] — `from_parts` enforces the
    /// shape's basic invariants.
    pub fn validate(&self) -> Vec<usize> {
        let match_index = Arc::new(MatchTypeIndex::new(Arc::clone(&self.tileset)));
        let num_tiles = self.tileset.num_tiles();
        self.entries
            .iter()
            .enumerate()
            .filter_map(|(idx, entry)| {
                let ok = match entry {
                    NtEntry::Phase1(nt) => nt_is_valid(nt, &match_index),
                    NtEntry::Phase2(st) => {
                        st.central_tile_id < num_tiles
                            && !st.angles.is_empty()
                            && st.to_patch(Arc::clone(&match_index)).is_some()
                    }
                };
                if ok { None } else { Some(idx + 1) }
            })
            .collect()
    }

    /// Snapshot the catalog as a [`Collection`] suitable for
    /// `serde_json` round-trip. `ring` tags the cyclotomic ring so
    /// deserializers can dispatch to the right `T`. The tileset is
    /// stored as raw angle sequences in `tile_angles`; callers must
    /// rebuild a typed [`TileSet<T>`] from those before calling
    /// [`Self::from_collection`].
    ///
    /// `kinds[i]` is the precomputed classification of entry `i + 1`
    /// (= [`Self::classify_all`]); retained so `from_collection` can
    /// cross-check it against a fresh re-derivation and reject stale
    /// catalogs from before a classifier fix.
    pub fn to_collection(&self, ring: impl Into<String>) -> Collection {
        let tile_angles = self
            .tileset
            .rats()
            .iter()
            .map(|r| r.seq().to_vec())
            .collect();
        Collection {
            ring: ring.into(),
            tile_angles,
            entries: self.entries.clone(),
            transitions: self.transitions.clone(),
            kinds: self.classify_all(),
        }
    }

    /// Rebuild a catalog from a [`Collection`]. The caller supplies a
    /// tileset matching `c.tile_angles` (the ring `T` is checked
    /// against the angle sequences by [`crate::geom::rat::Rat`]'s
    /// usual validity rules at tile-set construction time, not here).
    ///
    /// Validation: the recorded `c.kinds` must agree with what
    /// [`Self::classify_all`] re-derives from the parsed transitions.
    /// A mismatch returns `Err`, catching stale serialized catalogs.
    pub fn from_collection(tileset: Arc<TileSet<T>>, c: Collection) -> Result<Self, String> {
        if c.kinds.len() != c.entries.len() {
            return Err(format!(
                "kinds.len()={} doesn't match entries.len()={}",
                c.kinds.len(),
                c.entries.len()
            ));
        }
        for t in &c.transitions {
            if t.src_id < 1 || t.src_id > c.entries.len() {
                return Err(format!(
                    "TRANS src_id {} out of range (have {} entries)",
                    t.src_id,
                    c.entries.len()
                ));
            }
            if t.dst_id < 1 || t.dst_id > c.entries.len() {
                return Err(format!(
                    "TRANS dst_id {} out of range (have {} entries)",
                    t.dst_id,
                    c.entries.len()
                ));
            }
        }
        let idx = NeighborhoodIndex {
            tileset,
            entries: c.entries,
            transitions: c.transitions,
        };
        let computed_kinds = idx.classify_all();
        for (i, (recorded, computed)) in c.kinds.iter().zip(computed_kinds.iter()).enumerate() {
            if recorded != computed {
                return Err(format!(
                    "entry id {} kind mismatch: file says {:?}, classify_all derives {:?}",
                    i + 1,
                    recorded,
                    computed
                ));
            }
        }
        Ok(idx)
    }
}

/// Serializable snapshot of a [`NeighborhoodIndex`]: the catalog
/// entries, transitions, and pre-computed kinds, plus the tileset as
/// raw angle sequences. Designed to round-trip via `serde_json`.
///
/// Non-generic — the typed tileset is reconstructed from
/// `tile_angles` by the consumer (see `ntype_bench`-style
/// collect/validate workflows), then handed to
/// [`NeighborhoodIndex::from_collection`].
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct Collection {
    /// Symbolic name of the cyclotomic ring (e.g. `"ZZ12"`, `"ZZ10"`).
    pub ring: String,
    /// Raw angle sequence of each tile, in `TileSet` order.
    pub tile_angles: Vec<Vec<i8>>,
    /// All catalog entries, in 1-based id order (= index `i` is id
    /// `i + 1`).
    pub entries: Vec<NtEntry>,
    /// All recorded transitions.
    pub transitions: Vec<NtTransition>,
    /// Precomputed [`NtKind`] for each entry; cross-checked on load.
    pub kinds: Vec<NtKind>,
}

/// Mutable state shared across the seed and BFS phases of
/// [`NeighborhoodIndex::new`].
#[derive(Default)]
struct BfsState {
    /// All discovered entries in BFS order. `entries[i]` has 1-based id
    /// `i + 1`. Phase-1 and phase-2 entries share one id space.
    entries: Vec<NtEntry>,
    /// All recorded transitions between entries.
    transitions: Vec<NtTransition>,
    /// `seen[entry]` = 1-based id of the entry in `entries`.
    seen: FxHashMap<NtEntry, usize>,
    /// BFS frontier of entry ids waiting to be explored.
    queue: VecDeque<usize>,
}

/// Phase 1: enumerate every two-tile patch from `MatchTypeIndex`, try
/// every third-tile glue against it, and accept each successful glue
/// as a seed NT (after a self-consistency check via [`nt_is_valid`]).
fn seed_phase<T: IsRing>(state: &mut BfsState, match_index: &Arc<MatchTypeIndex<T>>) {
    for id in 1..=match_index.num_types() {
        let mt = match_index.get(id);
        let seed = PatchSeed::new(Arc::clone(match_index.tileset()), mt.a.tile_id);
        let pm = PatchMatch::new(
            EdgeRange::new(mt.a.range.start_offset, mt.len()),
            Segment::new(
                mt.b.tile_id,
                EdgeRange::new(mt.b.range.start_offset, mt.len()),
            ),
        );
        let mut patch = match seed.grow(&pm) {
            Some(p) => p,
            None => continue,
        };
        patch.normalize();
        let patch_n = patch.boundary_len();

        // Collect all ctx-ctx junctions with their positions. Filtered
        // per third_pm to only those incident with the match.
        let all_juncs: Vec<(usize, OpenVertexType)> = (0..patch_n)
            .filter_map(|i| patch.junction_vertex_type_at(i).map(|vt| (i, vt)))
            .collect();

        for third_pm in patch.get_all_matches() {
            // get_all_matches returns edge-compatible glues but for
            // non-convex tiles (e.g. spectre) the central might still
            // collide with the existing two-tile patch. Try the glue
            // on a clone first; skip if it fails.
            let mut trial = patch.clone();
            if !trial.add_tile(&third_pm) {
                continue;
            }
            if let Some(nt) = build_seed_nt(&third_pm, patch_n, &all_juncs, match_index) {
                let entry = NtEntry::Phase1(nt);
                if state.seen.contains_key(&entry) {
                    continue;
                }
                let NtEntry::Phase1(ref nt_ref) = entry else {
                    unreachable!()
                };
                // trial.add_tile above verified the central glues into
                // the normalized two-tile patch. Also verify the
                // abstract NT reconstructs from its vt_seq (needed for
                // non-convex tiles where seed-gen and reconstruct can
                // diverge).
                if !nt_is_valid(nt_ref, match_index) {
                    continue;
                }
                let id = state.entries.len() + 1;
                state.seen.insert(entry.clone(), id);
                state.entries.push(entry);
                state.queue.push_back(id);
            }
        }
    }
}

/// Construct a candidate seed NT from `third_pm`'s glue position on a
/// two-tile patch. Returns `None` if no junction is incident with the
/// match (= the central tile shares no junction with the patch).
fn build_seed_nt<T: IsRing>(
    third_pm: &PatchMatch,
    patch_n: usize,
    all_juncs: &[(usize, OpenVertexType)],
    match_index: &Arc<MatchTypeIndex<T>>,
) -> Option<NeighborhoodType> {
    let central_tile_id = third_pm.b.tile_id;
    let central_n = match_index.tileset().rat(central_tile_id).seq().len();
    let cw_anchor_on_central = third_pm.b.range.start_offset;
    // Per the shared-edge correspondence (CCW on context = CW on
    // central), the CCW anchor vertex on context maps to tile offset
    // `start_b - match_len` mod central_n.
    let ccw_anchor_on_central = (cw_anchor_on_central + central_n - third_pm.len()) % central_n;

    // vt_seq is the junctions incident with the central match: those
    // at positions in [anchor, anchor + match_len], i.e. CCW distance
    // from the anchor is at most match_len.
    let filtered: Vec<&(usize, OpenVertexType)> = all_juncs
        .iter()
        .filter(|(pos, _)| {
            (pos + patch_n - third_pm.a_range.start_offset) % patch_n <= third_pm.len()
        })
        .collect();
    if filtered.is_empty() {
        return None;
    }
    let first_junc = filtered[0].0;
    let last_junc = filtered[filtered.len() - 1].0;
    let vt_seq: Vec<OpenVertexType> = filtered.iter().map(|(_, vt)| vt.clone()).collect();
    // cw_anchor_on_context = CW distance from first_junc to the CW
    // anchor on context. ccw_anchor_on_context = CCW distance from
    // last_junc to the CCW anchor. Both stay small as the BFS only
    // adds edges OUTSIDE [cw_anchor, ccw_anchor].
    let cw_anchor_on_context = (first_junc + patch_n - third_pm.a_range.start_offset) % patch_n;
    let ccw_anchor_pos = (third_pm.a_range.start_offset + third_pm.len()) % patch_n;
    let ccw_anchor_on_context = (ccw_anchor_pos + patch_n - last_junc) % patch_n;
    Some(NeighborhoodType {
        central_tile_id,
        cw_anchor_on_central,
        ccw_anchor_on_central,
        cw_anchor_on_context,
        ccw_anchor_on_context,
        num_ctx_tiles: 2,
        vt_seq,
    })
}

/// BFS growth: dequeue each entry id, enumerate one-petal successors
/// (phase-1 step for `NtEntry::Phase1`, phase-2 step for open
/// `NtEntry::Phase2`), dedup against `seen`, and record transitions.
/// Phase-1 entries grow `num_ctx_tiles` by 1 per step; phase-2 entries
/// grow corona by 1 per step. The transition graph is a DAG.
///
/// Closed `SurroundedTile` entries (`is_closed = true`) are pushed
/// into `entries` but not into the BFS queue — they are terminal.
/// [`NeighborhoodIndex::classify_all`] recognises them directly as
/// Blessed escape destinations.
fn bfs_phase<T: IsRing>(state: &mut BfsState, match_index: &Arc<MatchTypeIndex<T>>) {
    while let Some(src_id) = state.queue.pop_front() {
        let entry = state.entries[src_id - 1].clone();
        let outcomes = match &entry {
            NtEntry::Phase1(nt) => explore_phase1(nt, match_index),
            NtEntry::Phase2(st) => explore_phase2(st, match_index),
        };
        for outcome in outcomes {
            let new_entry = match outcome.kind {
                OutcomeKind::Phase1(nt) => NtEntry::Phase1(nt),
                OutcomeKind::Phase2(st) => NtEntry::Phase2(st),
            };
            let needs_bfs = matches!(
                &new_entry,
                NtEntry::Phase1(_)
                    | NtEntry::Phase2(SurroundedTile {
                        is_closed: false,
                        ..
                    })
            );
            let dst_id = if let Some(&id) = state.seen.get(&new_entry) {
                id
            } else {
                let id = state.entries.len() + 1;
                state.seen.insert(new_entry.clone(), id);
                state.entries.push(new_entry);
                // Phase-1 entries and open phase-2 entries get further
                // BFS exploration. Closed phase-2 entries are terminal
                // (= they carry the closed-corona data; no outgoing
                // transitions, recognised as escape by classify_all).
                if needs_bfs {
                    state.queue.push_back(id);
                }
                id
            };
            state.transitions.push(NtTransition {
                src_id,
                dst_id,
                side: outcome.side,
                tile_id: outcome.petal_pm.b.tile_id,
                tile_offset: outcome.petal_pm.b.range.start_offset,
            });
        }
    }
}

struct ExploreOutcome {
    side: TransitionSide,
    petal_pm: PatchMatch,
    kind: OutcomeKind,
}

/// The result of one BFS step: a new (or existing) catalog entry to
/// transition into. Phase-1 entries describe states where the central
/// is still on the boundary; phase-2 entries (`SurroundedTile`) describe
/// states where the central has been edge-absorbed, with a flag for
/// whether the surrounding corona has closed the final open vertex.
enum OutcomeKind {
    Phase1(NeighborhoodType),
    Phase2(SurroundedTile),
}

struct AttachedContext<T: IsRing> {
    aug: GrowingPatch<T>,
    central_ptid: usize,
    /// CCW frontier position on aug (gap_end vertex, always a junction).
    frontier_pos_on_aug: usize,
    /// Whether the CCW frontier vertex was already a junction on the
    /// pre-glue context boundary. Drives CCW Case A vs Case B in
    /// [`try_step_ccw`].
    frontier_is_junction_in_ctx: bool,
    /// Last context boundary edge covered by the central tile.
    /// Used as the `cw` edge of a freshly-appended vt in Case B.
    last_covered_ctx_edge: EdgeInfo,
    /// Number of context boundary edges on `aug` (= `ctx_n - match_len`).
    /// On `aug`, positions `[0, gap_start)` are surviving context edges
    /// and `[gap_start, aug_n)` are the central tile gap edges. Used
    /// by [`try_step_ccw`] to identify the CW frontier ctx edge for
    /// the phase-2 transition's `is_closed` check.
    gap_start: usize,
    aug_n: usize,
}

fn build_attached_context<T: IsRing>(
    nt: &NeighborhoodType,
    match_index: &Arc<MatchTypeIndex<T>>,
) -> Option<AttachedContext<T>> {
    let (ctx, junc_positions) =
        GrowingPatch::construct_witness_from_vt_sequence(&nt.vt_seq, Arc::clone(match_index))?;
    let ctx_n = ctx.boundary_len();
    if ctx_n == 0 {
        return None;
    }
    let first_junc = junc_positions[0];
    let anchor_pos = (first_junc + ctx_n - nt.cw_anchor_on_context) % ctx_n;

    let tileset = match_index.tileset();
    let central_seq = tileset.rat(nt.central_tile_id).seq();
    let central_n = central_seq.len();
    let match_len = crate::stringmatch::forward_match_length(
        ctx.angles(),
        anchor_pos,
        central_seq,
        nt.cw_anchor_on_central,
    );
    if match_len == 0 || match_len >= central_n {
        return None;
    }

    let frontier_on_ctx = (anchor_pos + match_len) % ctx_n;
    let frontier_is_junction_in_ctx = ctx.is_junction(frontier_on_ctx);
    let last_covered_ctx_edge = ctx.edges()[(anchor_pos + match_len - 1) % ctx_n];

    let central_pm = PatchMatch::new(
        EdgeRange::new(anchor_pos, match_len),
        Segment::new(
            nt.central_tile_id,
            EdgeRange::new(nt.cw_anchor_on_central, match_len),
        ),
    );
    let mut aug = ctx.clone();
    if !aug.add_tile(&central_pm) {
        return None;
    }

    let aug_n = aug.boundary_len();
    let gap_start = ctx_n - match_len;
    let central_ptid = aug.patch_tile_ids()[gap_start];

    // CCW frontier on aug: gap_end == 0 by construction.
    let mut frontier_pos_on_aug = 0usize;
    let mut found = false;
    for _ in 0..aug_n {
        if aug.is_junction(frontier_pos_on_aug) {
            found = true;
            break;
        }
        frontier_pos_on_aug = (frontier_pos_on_aug + 1) % aug_n;
    }
    if !found {
        return None;
    }

    Some(AttachedContext {
        aug,
        central_ptid,
        frontier_pos_on_aug,
        frontier_is_junction_in_ctx,
        last_covered_ctx_edge,
        gap_start,
        aug_n,
    })
}

fn explore_phase1<T: IsRing>(
    nt: &NeighborhoodType,
    match_index: &Arc<MatchTypeIndex<T>>,
) -> Vec<ExploreOutcome> {
    let ac = match build_attached_context(nt, match_index) {
        Some(a) => a,
        None => return Vec::new(),
    };

    let mut results = Vec::new();
    let target_edge = ac.frontier_pos_on_aug;
    let ccw_candidates = GrowingPatch::compute_candidates_covering_position(
        ac.aug.match_index(),
        ac.aug.angles(),
        ac.aug.edges(),
        ac.frontier_pos_on_aug,
    );
    for petal_pm in ccw_candidates {
        if !match_absorbs_edge(&petal_pm, target_edge, ac.aug_n) {
            continue;
        }
        if let Some(outcome) = try_step_ccw(nt, &ac, petal_pm, match_index) {
            results.push(outcome);
        }
    }
    results
}

/// Phase-2 BFS step from a `SurroundedTile`. Reconstructs the corona
/// patch via [`SurroundedTile::to_patch`] (which calls
/// [`GrowingPatch::from_parts`] directly — no `vt_seq` reconstruction,
/// so the closed-corona / fully-interior-tile pitfalls of
/// `construct_witness_from_vt_sequence` are avoided). Attempts to
/// attach a petal at the open vertex (= `st.open_vertex_pos`).
///
/// For each successful glue, builds the next `SurroundedTile`.
/// `is_closed` on the result is true iff the petal's match absorbed
/// both edges incident to the old open vertex (= the petal seals the
/// angle around it).
fn explore_phase2<T: IsRing>(
    st: &SurroundedTile,
    match_index: &Arc<MatchTypeIndex<T>>,
) -> Vec<ExploreOutcome> {
    debug_assert!(
        !st.is_closed,
        "explore_phase2 should not run on closed SurroundedTiles"
    );
    let corona = match st.to_patch(Arc::clone(match_index)) {
        Some(p) => p,
        None => return Vec::new(),
    };
    let corona_n = corona.boundary_len();
    if corona_n == 0 {
        return Vec::new();
    }
    let open_vertex_pos = st.open_vertex_pos;
    let ccw_edge = open_vertex_pos;
    let cw_edge = (open_vertex_pos + corona_n - 1) % corona_n;

    let candidates = GrowingPatch::compute_candidates_covering_position(
        corona.match_index(),
        corona.angles(),
        corona.edges(),
        ccw_edge,
    );
    let mut results = Vec::new();
    for petal_pm in candidates {
        if !match_absorbs_edge(&petal_pm, ccw_edge, corona_n) {
            continue;
        }
        let mut trial = corona.clone();
        if !trial.add_tile(&petal_pm) {
            continue;
        }
        let is_closed = match_absorbs_edge(&petal_pm, cw_edge, corona_n);
        let open_vertex_trial_pos = if is_closed {
            None
        } else {
            let ccw_on_corona = (petal_pm.a_range.start_offset + petal_pm.len()) % corona_n;
            Some((open_vertex_pos + corona_n - ccw_on_corona) % corona_n)
        };
        let new_st = build_surrounded_tile_from_trial(
            trial,
            st.central_tile_id,
            is_closed,
            open_vertex_trial_pos,
        );
        results.push(ExploreOutcome {
            side: TransitionSide::Ccw,
            petal_pm,
            kind: OutcomeKind::Phase2(new_st),
        });
    }
    results
}

/// Build a `SurroundedTile` from a trial patch. Normalizes the patch
/// (= lex-min rotation + dense `0..k` `patch_tile_ids`) and stores
/// its boundary state directly. For open entries, maps the original
/// open-vertex position into the normalized boundary via the rotation
/// offset that `normalize` reports.
fn build_surrounded_tile_from_trial<T: IsRing>(
    mut trial: GrowingPatch<T>,
    central_tile_id: usize,
    is_closed: bool,
    open_vertex_trial_pos: Option<usize>,
) -> SurroundedTile {
    let n = trial.boundary_len();
    let rot = trial.normalize();
    let open_vertex_pos = match open_vertex_trial_pos {
        Some(p) if n > 0 => (p + n - rot) % n,
        _ => 0,
    };
    let patch_tile_ids = trial.patch_tile_ids().to_vec();
    let num_tile_instances = patch_tile_ids.iter().max().map_or(0, |m| m + 1);
    SurroundedTile {
        central_tile_id,
        is_closed,
        open_vertex_pos,
        num_tile_instances,
        angles: trial.angles().to_vec(),
        edges: trial.edges().to_vec(),
        inner_chains: trial.inner_chains().to_vec(),
        patch_tile_ids,
    }
}

/// Whether the cyclic range of `pm.len()` edges starting at `pm.a_range.start_offset` in
/// a boundary of length `n` includes the edge at position `target_edge`.
///
/// **Edge-inclusive** check: `target_edge in [pm.a_range.start_offset, pm.a_range.start_offset +
/// pm.len() - 1]` (mod n). Compare to [`crate::geom::cyclic::cyclic_range_contains`]
/// which is **vertex-inclusive** (covers `len + 1` vertices). Don't
/// substitute one for the other: e.g. for `start=25, len=1, n=26`,
/// `match_absorbs_edge(target=0) = false` (edge 0 is not in
/// `[25, 25]`) but `cyclic_range_contains(0) = true` (vertex 0 is
/// the CCW endpoint of edge 25).
fn match_absorbs_edge(pm: &PatchMatch, target_edge: usize, n: usize) -> bool {
    if pm.is_empty() {
        return false;
    }
    let end_inclusive = (pm.a_range.start_offset + pm.len() - 1) % n;
    if pm.a_range.start_offset <= end_inclusive {
        target_edge >= pm.a_range.start_offset && target_edge <= end_inclusive
    } else {
        target_edge >= pm.a_range.start_offset || target_edge <= end_inclusive
    }
}

/// Try to apply a CCW petal to `nt` via the candidate `petal_pm`. Returns
/// `None` if the glue collides or the resulting vt_seq doesn't reconstruct.
fn try_step_ccw<T: IsRing>(
    nt: &NeighborhoodType,
    ac: &AttachedContext<T>,
    petal_pm: PatchMatch,
    match_index: &Arc<MatchTypeIndex<T>>,
) -> Option<ExploreOutcome> {
    let mut trial = ac.aug.clone();
    if !trial.add_tile(&petal_pm) {
        return None;
    }

    // Central edges fully absorbed → emit a phase-2 SurroundedTile.
    //
    // The CCW frontier ctx edge (aug position 0) is always in the
    // petal's match by the candidate filter, so the CCW anchor
    // (aug vertex 0) is always absorbed when the petal absorbs all
    // central. The CW anchor (aug vertex `gap_start`) survives iff
    // its outer ctx edge (= aug edge `gap_start - 1`) is not also
    // absorbed.
    //
    // - **Closed phase 2** (petal absorbs CW outer ctx too): both
    //   anchors gone; central is fully surrounded; terminal.
    // - **Open phase 2** (CW outer ctx not absorbed): CW anchor
    //   survives as the sole frontier vertex touching the central;
    //   phase-2 BFS continues there.
    if !trial.patch_tile_ids().contains(&ac.central_ptid) {
        let cw_outer_edge = (ac.gap_start + ac.aug_n - 1) % ac.aug_n;
        let is_closed = match_absorbs_edge(&petal_pm, cw_outer_edge, ac.aug_n);
        let canonical_open_trial_pos = if is_closed {
            None
        } else {
            let ccw_pos_on_aug = (petal_pm.a_range.start_offset + petal_pm.len()) % ac.aug_n;
            Some((ac.gap_start + ac.aug_n - ccw_pos_on_aug) % ac.aug_n)
        };
        let st = build_surrounded_tile_from_trial(
            trial,
            nt.central_tile_id,
            is_closed,
            canonical_open_trial_pos,
        );
        return Some(ExploreOutcome {
            side: TransitionSide::Ccw,
            petal_pm,
            kind: OutcomeKind::Phase2(st),
        });
    }

    let petal_n = match_index.tileset().rat(petal_pm.b.tile_id).seq().len();

    // The OLD CCW anchor vertex on aug is at position frontier_pos_on_aug
    // = 0. In the petal-vertex coordinate system, aug vertex (start_a + i)
    // ↔ petal vertex (start_b - i). So OLD CCW anchor ↔ petal vertex
    // (start_b - i_anchor) where i_anchor = (0 - start_a) mod aug_n. The
    // new ccw edge of vt_seq[-1] starts at this petal vertex going CCW =
    // petal edge[start_b - i_anchor].
    let i_anchor = (ac.aug_n - petal_pm.a_range.start_offset) % ac.aug_n;
    let petal_edge = EdgeInfo {
        tile_id: petal_pm.b.tile_id,
        tile_offset: (petal_pm.b.range.start_offset + petal_n - i_anchor) % petal_n,
    };

    let mut new_vt_seq = nt.vt_seq.clone();
    if ac.frontier_is_junction_in_ctx {
        // CCW Case A: extend last VT — petal becomes new ccw, old ccw goes
        // to the END of inner.
        let last = new_vt_seq.last_mut().expect("vt_seq is non-empty");
        let old_ccw = last.ccw;
        last.inner.push(old_ccw);
        last.ccw = petal_edge;
    } else {
        // CCW Case B: append new VT. cw = last covered ctx edge.
        new_vt_seq.push(OpenVertexType {
            cw: ac.last_covered_ctx_edge,
            inner: vec![],
            ccw: petal_edge,
        });
    }

    let new_nt = try_construct_nt_from_cw(
        nt.central_tile_id,
        nt.cw_anchor_on_central,
        nt.cw_anchor_on_context,
        nt.num_ctx_tiles + 1,
        new_vt_seq,
        match_index,
    )?;

    Some(ExploreOutcome {
        side: TransitionSide::Ccw,
        petal_pm,
        kind: OutcomeKind::Phase1(new_nt),
    })
}

/// Re-extract the canonical (vt_seq, cw_anchor_on_context, ccw_anchor_on_context)
/// from a reconstructed ctx + known anchor positions. Walks the covered
/// segment on ctx and collects junctions at each position via
/// `junction_vertex_type_at`. The resulting vt_seq is canonical — it
/// matches what `seed_gen` would have produced for the same geometric
/// state, regardless of which path the BFS took to reach it.
fn canonicalize_vt_seq_on_ctx<T: IsRing>(
    ctx: &GrowingPatch<T>,
    cw_anchor_pos: usize,
    ccw_anchor_pos: usize,
    ctx_n: usize,
) -> Option<(Vec<OpenVertexType>, usize, usize)> {
    let match_len = (ccw_anchor_pos + ctx_n - cw_anchor_pos) % ctx_n;
    let mut juncs: Vec<(usize, OpenVertexType)> = Vec::new();
    for off in 0..=match_len {
        let pos = (cw_anchor_pos + off) % ctx_n;
        if let Some(vt) = ctx.junction_vertex_type_at(pos) {
            juncs.push((pos, vt));
        }
    }
    if juncs.is_empty() {
        return None;
    }
    let first_junc = juncs[0].0;
    let last_junc = juncs[juncs.len() - 1].0;
    let cw_on_ctx = (first_junc + ctx_n - cw_anchor_pos) % ctx_n;
    let ccw_on_ctx = (ccw_anchor_pos + ctx_n - last_junc) % ctx_n;
    let vt_seq = juncs.into_iter().map(|(_, vt)| vt).collect();
    Some((vt_seq, cw_on_ctx, ccw_on_ctx))
}

/// Reconstruct an NT from its vt_seq + CW-side anchor fields, deriving the
/// CCW-side anchors from the geometry, and verifying the central can be
/// glued. The stored `vt_seq` is re-extracted from the reconstructed ctx
/// so that BFS dedup uses a canonical encoding regardless of how the NT
/// was assembled. Returns None if reconstruction fails, the match length
/// is 0, the match closes the central, or the central glue collides.
fn try_construct_nt_from_cw<T: IsRing>(
    central_tile_id: usize,
    cw_anchor_on_central: usize,
    cw_anchor_on_context: usize,
    num_ctx_tiles: usize,
    vt_seq: Vec<OpenVertexType>,
    match_index: &Arc<MatchTypeIndex<T>>,
) -> Option<NeighborhoodType> {
    let (mut ctx, jp) =
        GrowingPatch::construct_witness_from_vt_sequence(&vt_seq, Arc::clone(match_index))?;
    let ctx_n = ctx.boundary_len();
    if ctx_n == 0 || jp.is_empty() {
        return None;
    }
    let first_junc = jp[0];
    let cw_anchor_pos = (first_junc + ctx_n - cw_anchor_on_context) % ctx_n;
    let tileset = match_index.tileset();
    let central_seq = tileset.rat(central_tile_id).seq();
    let central_n = central_seq.len();
    let match_len = crate::stringmatch::forward_match_length(
        ctx.angles(),
        cw_anchor_pos,
        central_seq,
        cw_anchor_on_central,
    );
    if match_len == 0 || match_len >= central_n {
        return None;
    }
    let ccw_anchor_on_central = (cw_anchor_on_central + central_n - match_len) % central_n;
    let ccw_anchor_pos = (cw_anchor_pos + match_len) % ctx_n;
    let (canon_vt_seq, canon_cw_on_ctx, canon_ccw_on_ctx) =
        canonicalize_vt_seq_on_ctx(&ctx, cw_anchor_pos, ccw_anchor_pos, ctx_n)?;
    let pm = PatchMatch::new(
        EdgeRange::new(cw_anchor_pos, match_len),
        Segment::new(
            central_tile_id,
            EdgeRange::new(cw_anchor_on_central, match_len),
        ),
    );
    if !ctx.add_tile(&pm) {
        return None;
    }
    Some(NeighborhoodType {
        central_tile_id,
        cw_anchor_on_central,
        ccw_anchor_on_central,
        cw_anchor_on_context: canon_cw_on_ctx,
        ccw_anchor_on_context: canon_ccw_on_ctx,
        num_ctx_tiles,
        vt_seq: canon_vt_seq,
    })
}

/// Check that an NT is self-consistent: reconstruct from the CW-side
/// fields and verify the stored CCW-side fields agree with what the
/// geometry implies. Used as a post-hoc validator (see
/// [`NeighborhoodIndex::validate`]) and as a seed-acceptance filter
/// during BFS construction.
fn nt_is_valid<T: IsRing>(nt: &NeighborhoodType, match_index: &Arc<MatchTypeIndex<T>>) -> bool {
    let Some(reconstructed) = try_construct_nt_from_cw(
        nt.central_tile_id,
        nt.cw_anchor_on_central,
        nt.cw_anchor_on_context,
        nt.num_ctx_tiles,
        nt.vt_seq.clone(),
        match_index,
    ) else {
        return false;
    };
    reconstructed.ccw_anchor_on_central == nt.ccw_anchor_on_central
        && reconstructed.ccw_anchor_on_context == nt.ccw_anchor_on_context
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::analysis::matchtypes::MatchTypeIndex;
    use crate::cyclotomic::ZZ12;
    use crate::geom::patch::GrowingPatch;
    use crate::geom::tileset;
    use std::sync::OnceLock;

    fn square_tileset() -> Arc<TileSet<ZZ12>> {
        tileset::square::<ZZ12>()
    }

    fn hex_tileset() -> Arc<TileSet<ZZ12>> {
        tileset::hex::<ZZ12>()
    }

    /// Shared, lazy-initialized neighborhood indices. Tests should call
    /// these instead of `NeighborhoodIndex::new(...)` to avoid rebuilding
    /// expensive indices for every test. CCW-only direction is the
    /// established working baseline.
    fn square_idx() -> &'static NeighborhoodIndex<ZZ12> {
        static SQUARE_IDX: OnceLock<NeighborhoodIndex<ZZ12>> = OnceLock::new();
        SQUARE_IDX.get_or_init(|| NeighborhoodIndex::new(square_tileset()))
    }

    fn hex_idx() -> &'static NeighborhoodIndex<ZZ12> {
        static HEX_IDX: OnceLock<NeighborhoodIndex<ZZ12>> = OnceLock::new();
        HEX_IDX.get_or_init(|| NeighborhoodIndex::new(hex_tileset()))
    }

    fn spectre_idx() -> &'static NeighborhoodIndex<ZZ12> {
        static SPECTRE_IDX: OnceLock<NeighborhoodIndex<ZZ12>> = OnceLock::new();
        SPECTRE_IDX.get_or_init(|| NeighborhoodIndex::new(spectre_tileset()))
    }

    /// Helper for the baked-in count tests: assert
    /// `(num_types, transitions, dead, undead, blessed, free,
    /// closed_transitions)` exactly. Catches silent drift in
    /// seed generation, BFS exploration, or classification.
    #[allow(clippy::too_many_arguments)]
    fn assert_counts<T: IsRing>(
        idx: &NeighborhoodIndex<T>,
        expected_types: usize,
        expected_transitions: usize,
        expected_closed_phase2: usize,
        expected_dead: usize,
        expected_undead: usize,
        expected_blessed: usize,
        expected_free: usize,
    ) {
        let kinds = idx.classify_all();
        let dead = kinds.iter().filter(|k| **k == NtKind::Dead).count();
        let undead = kinds.iter().filter(|k| **k == NtKind::Undead).count();
        let blessed = kinds.iter().filter(|k| **k == NtKind::Blessed).count();
        let free = kinds.iter().filter(|k| **k == NtKind::Free).count();
        // Closed phase-2 SurroundedTile entries (= the terminal-good
        // states that classify_all treats as escape destinations).
        let closed_phase2 = idx
            .entries()
            .iter()
            .filter(|e| matches!(e, NtEntry::Phase2(st) if st.is_closed))
            .count();

        assert_eq!(idx.num_types(), expected_types, "num_types");
        assert_eq!(idx.transitions().len(), expected_transitions, "transitions");
        assert_eq!(closed_phase2, expected_closed_phase2, "closed_phase2");
        assert_eq!(dead, expected_dead, "dead");
        assert_eq!(undead, expected_undead, "undead");
        assert_eq!(blessed, expected_blessed, "blessed");
        assert_eq!(free, expected_free, "free");
        assert_eq!(dead + undead + blessed + free, expected_types, "kinds sum");
    }

    #[test]
    #[cfg_attr(
        debug_assertions,
        ignore = "release-only: square idx build ~21s in release, much slower in debug"
    )]
    fn square_counts() {
        // Square tiles convexly; every continuation closes. All
        // 240 256 entries are Blessed: 109 184 phase-1 + 131 072
        // phase-2 (split 65 536 closed terminals + 65 536 open
        // intermediates that phase-2 BFS eventually closes).
        // Unlike hex, square produces both open and closed phase-2
        // entries from phase-1 → phase-2 transitions.
        assert_counts(square_idx(), 240256, 698880, 65536, 0, 0, 240256, 0);
    }

    #[test]
    fn hex_counts() {
        // Hex tiles perfectly: every central-edge-absorption is a
        // closed corona (no open vertex). All 46656 phase-2 entries
        // are closed terminals, classified directly as Blessed.
        assert_counts(hex_idx(), 102600, 335664, 46656, 0, 0, 102600, 0);
    }

    #[test]
    fn spectre_counts() {
        // Spectre is non-convex; exercises every kind. Pinned counts
        // shrank from (num_types=10559, transitions=11742, dead=6001,
        // undead=1615) when the ZZ12 segment-intersection check was
        // fixed to reject T-touches (an endpoint of one boundary edge
        // lying on the strict interior of a non-adjacent edge). The
        // previously-admitted T-touch configurations were not valid
        // self-avoiding polygons. Closed-phase2 / blessed / free
        // categories are unchanged (the dropped entries were all
        // phase-1 dead/undead). See the OEIS A316192 test in
        // `bin::rat_enum::free_tests::test_oeis_a316192_zz12`
        // for the downstream confirmation.
        assert_counts(spectre_idx(), 9976, 11171, 251, 5561, 1472, 1029, 1914);
    }

    #[test]
    #[cfg_attr(
        debug_assertions,
        ignore = "release-only: iterates square_idx (~21s build in release)"
    )]
    fn seeds_are_well_formed() {
        for idx in [
            square_idx() as &NeighborhoodIndex<ZZ12>,
            hex_idx(),
            spectre_idx(),
        ] {
            assert!(idx.num_types() > 0, "expected non-empty seed collection");
            let num_tiles = idx.tileset().num_tiles();
            for entry in idx.entries() {
                assert!(
                    entry.central_tile_id() < num_tiles,
                    "central_tile_id {} out of range (have {} tiles)",
                    entry.central_tile_id(),
                    num_tiles
                );
                match entry {
                    NtEntry::Phase1(nt) => assert!(
                        !nt.vt_seq.is_empty(),
                        "phase-1 seeds must have non-empty vt_seq"
                    ),
                    NtEntry::Phase2(st) => assert!(
                        !st.angles.is_empty(),
                        "phase-2 entries must have non-empty boundary"
                    ),
                }
            }
        }
    }

    /// No two catalog entries are equal by `PartialEq`. This is the
    /// dedup contract of the BFS — not interface-level
    /// canonicalization. The catalog **does** contain multiple
    /// entries per interface class by design (different growth
    /// histories produce distinct entries with the same match-side
    /// interface); see the module doc on the interface-quotient view.
    #[test]
    #[cfg_attr(
        debug_assertions,
        ignore = "release-only: iterates square_idx (~21s build in release)"
    )]
    fn entries_have_no_partial_eq_duplicates() {
        for (name, idx) in [
            ("square", square_idx() as &NeighborhoodIndex<ZZ12>),
            ("hex", hex_idx()),
            ("spectre", spectre_idx()),
        ] {
            let mut keys: std::collections::HashSet<&NtEntry> = std::collections::HashSet::new();
            for (i, entry) in idx.entries().iter().enumerate() {
                assert!(
                    keys.insert(entry),
                    "{}: duplicate entry at id {} (vt_seq={:?})",
                    name,
                    i + 1,
                    entry.vt_seq()
                );
            }
        }
    }

    fn assert_roundtrip<T: IsRing>(idx: &NeighborhoodIndex<T>) {
        let collection = idx.to_collection("ZZ12");
        let json = serde_json::to_string(&collection).expect("serialize");
        let restored: Collection = serde_json::from_str(&json).expect("deserialize");
        let parsed = NeighborhoodIndex::from_collection(Arc::clone(idx.tileset()), restored)
            .expect("from_collection");
        assert_eq!(
            parsed.num_types(),
            idx.num_types(),
            "entries count mismatch"
        );
        for (i, (a, b)) in idx
            .entries()
            .iter()
            .zip(parsed.entries().iter())
            .enumerate()
        {
            assert_eq!(a, b, "entry {} mismatch", i);
        }
        assert_eq!(
            parsed.transitions().len(),
            idx.transitions().len(),
            "transitions count mismatch"
        );
        for (i, (a, b)) in idx
            .transitions()
            .iter()
            .zip(parsed.transitions().iter())
            .enumerate()
        {
            assert_eq!(a.src_id, b.src_id, "transition {} src", i);
            assert_eq!(a.dst_id, b.dst_id, "transition {} dst", i);
            assert_eq!(a.tile_id, b.tile_id, "transition {} tile_id", i);
            assert_eq!(a.tile_offset, b.tile_offset, "transition {} tile_offset", i);
        }
    }

    #[test]
    #[cfg_attr(
        debug_assertions,
        ignore = "release-only: square idx build ~21s in release, much slower in debug"
    )]
    fn square_roundtrip_collection() {
        let idx = square_idx();
        assert_roundtrip(idx);
    }

    #[test]
    fn hex_roundtrip_collection() {
        let idx = hex_idx();
        assert_roundtrip(idx);
    }

    /// `from_collection` must reject a snapshot whose recorded
    /// `kinds` disagree with what `classify_all` re-derives from the
    /// parsed transitions. Catches stale catalogs from before a
    /// classifier fix.
    /// Pure unit test for [`match_absorbs_edge`]. The function appears
    /// in both production (`explore_phase1` / `explore_phase2` filter)
    /// and in the brute side of `spectre_ccw_only_is_complete`, so a
    /// bug here would not be caught by the existing brute test
    /// (circular).
    /// Exhaustive cross-check against a brute reference for moderate
    /// `n`. The reference walks the edge set explicitly.
    #[test]
    fn match_absorbs_edge_unit() {
        fn brute(start: usize, len: usize, target: usize, n: usize) -> bool {
            if len == 0 || n == 0 {
                return false;
            }
            (0..len).any(|i| (start + i) % n == target)
        }

        for n in [1usize, 2, 5, 13, 26] {
            for start in 0..n {
                // len > n is a precondition violation (a match
                // cannot cover more edges than the boundary has).
                // Don't test those inputs.
                for len in 0..=n {
                    for target in 0..n {
                        let pm = PatchMatch::new(
                            EdgeRange::new(start, len),
                            Segment::new(0, EdgeRange::new(0, len)),
                        );
                        let got = match_absorbs_edge(&pm, target, n);
                        let want = brute(start, len, target, n);
                        assert_eq!(got, want, "n={n} start={start} len={len} target={target}");
                    }
                }
            }
        }

        // Pin the wrap regression case directly: edge n-1, len 1.
        let pm = PatchMatch::new(EdgeRange::new(25, 1), Segment::new(0, EdgeRange::new(0, 1)));
        assert!(match_absorbs_edge(&pm, 25, 26));
        assert!(!match_absorbs_edge(&pm, 0, 26));

        // Pin the wrap-spanning case: starts at n-1, len 2, covers
        // edges n-1 and 0.
        let pm = PatchMatch::new(EdgeRange::new(25, 2), Segment::new(0, EdgeRange::new(0, 2)));
        assert!(match_absorbs_edge(&pm, 25, 26));
        assert!(match_absorbs_edge(&pm, 0, 26));
        assert!(!match_absorbs_edge(&pm, 1, 26));
    }

    #[test]
    fn from_collection_rejects_kind_mismatch() {
        let idx = square_idx();
        let mut collection = idx.to_collection("ZZ12");
        // Square's NTs are all Blessed; swap the first one's kind to
        // Dead - that must fail to load.
        let original = collection.kinds[0];
        assert_eq!(original, NtKind::Blessed);
        collection.kinds[0] = NtKind::Dead;
        let err = match NeighborhoodIndex::from_collection(Arc::clone(idx.tileset()), collection) {
            Ok(_) => panic!("from_collection should reject kind mismatch"),
            Err(e) => e,
        };
        assert!(
            err.contains("kind mismatch"),
            "expected kind-mismatch error, got: {err}"
        );
    }

    fn spectre_tileset() -> Arc<TileSet<ZZ12>> {
        tileset::spectre::<ZZ12>()
    }

    #[test]
    #[cfg_attr(
        debug_assertions,
        ignore = "release-only: validate() reconstructs all square phase-2 patches (~28s in release)"
    )]
    fn validate_returns_empty_for_all_tilesets() {
        for (name, idx) in [
            ("square", square_idx() as &NeighborhoodIndex<ZZ12>),
            ("hex", hex_idx()),
            ("spectre", spectre_idx()),
        ] {
            let bad = idx.validate();
            assert!(
                bad.is_empty(),
                "{} has {}/{} invalid entries (first few: {:?})",
                name,
                bad.len(),
                idx.num_types(),
                &bad[..bad.len().min(5)]
            );
        }
    }

    /// Canonical fingerprint of the **augmented patch boundary** of
    /// an NT (= context + central glued together, lex_min_rot of the
    /// resulting cyclic angle sequence, paired with the central tile
    /// id and cw_anchor_on_central).
    ///
    /// **This is not the interface fingerprint.** The interface
    /// fingerprint would only canonicalize the matched edge run on
    /// the context boundary (the linear segment shared with the
    /// central), discarding everything else. The fingerprint here is
    /// finer than the interface (it distinguishes patches whose
    /// non-matched perimeters differ) and coarser than `PartialEq`
    /// on `NeighborhoodType` (it ignores growth-history-dependent
    /// fields like `num_ctx_tiles`).
    ///
    /// Used by the brute-force completeness + correctness tests as
    /// an independent canonical form for comparing trial patches to
    /// catalog entries.
    fn aug_boundary_fingerprint<T: IsRing>(
        nt: &NeighborhoodType,
        mi: &Arc<MatchTypeIndex<T>>,
    ) -> Option<(usize, usize, Vec<i8>)> {
        let (mut ctx, jp) =
            GrowingPatch::construct_witness_from_vt_sequence(&nt.vt_seq, Arc::clone(mi))?;
        let ctx_n = ctx.boundary_len();
        let first_junc = *jp.first()?;
        let cw_anchor_pos = (first_junc + ctx_n - nt.cw_anchor_on_context) % ctx_n;
        let pm = PatchMatch::new(
            EdgeRange::new(
                cw_anchor_pos,
                (nt.cw_anchor_on_central + mi.tileset().rat(nt.central_tile_id).seq().len()
                    - nt.ccw_anchor_on_central)
                    % mi.tileset().rat(nt.central_tile_id).seq().len(),
            ),
            Segment::new(
                nt.central_tile_id,
                EdgeRange::new(
                    nt.cw_anchor_on_central,
                    (nt.cw_anchor_on_central + mi.tileset().rat(nt.central_tile_id).seq().len()
                        - nt.ccw_anchor_on_central)
                        % mi.tileset().rat(nt.central_tile_id).seq().len(),
                ),
            ),
        );
        if !ctx.add_tile(&pm) {
            return None;
        }
        let angles = ctx.angles().to_vec();
        let rot = crate::geom::rat::lex_min_rot(&angles);
        let mut canon = angles;
        canon.rotate_left(rot);
        Some((nt.central_tile_id, nt.cw_anchor_on_central, canon))
    }

    /// **Canonical-class fingerprint of an NT**: the equivalence
    /// class that exactly preserves the four-kind classification.
    /// Two NTs with the same value here are physically identical
    /// configurations (modulo translation and reflection-free
    /// rotation in the plane), so their futures of growth and hence
    /// their kinds are identical.
    ///
    /// Components:
    ///   - `central_tile_id` - which tile is the central.
    ///   - `cw_anchor_on_central` - which edge of the central is the
    ///     CW endpoint of the matched segment (= identifies the
    ///     "first central-side gap edge" at the anchor).
    ///   - The **canonical (lex_min_rot) aug-boundary angle sequence** -
    ///     captures the shape of the entire post-glue (ctx + central)
    ///     patch.
    ///   - The **CW anchor's position on that canonical boundary** -
    ///     pins where the central is attached on the canonical
    ///     shape. Without this, two NTs differing only by where the
    ///     central is glued on the same shape would collapse to the
    ///     same class but have different futures (different
    ///     neighboring un-matched-ctx geometry near the anchor).
    ///
    /// Empirically (`diagnose_canonical_class_compression`):
    /// kind-constancy across this fingerprint holds on hex, square,
    /// and spectre (0 violations on all three). Compression vs the
    /// BFS catalog ranges from ~1x (spectre, near-canonical) to
    /// ~2300x (hex, massively redundant).
    /// **Extended-match-window fingerprint of a phase-1 NT**: a
    /// strictly coarser quotient than [`canonical_class_fingerprint`].
    /// Discards the deep-context boundary and keeps only the match
    /// interval padded by one segment of ctx on each side.
    ///
    /// # Geometric meaning
    ///
    /// A **segment** of the boundary is the run of edges between two
    /// consecutive junctions, all contributed by a single tile (= the
    /// untouched piece of one tile's perimeter on the boundary).
    /// Junctions are the vertices where two distinct tiles meet on
    /// the patch boundary; segments are the tile-owned arcs between
    /// them.
    ///
    /// On the aug boundary, the **match interval** is the run of
    /// central-tile free edges between the two **matched junctions**:
    ///   - **CW anchor** at vertex `gap_start` (= the junction where
    ///     the CW-most ctx tile meets the central tile),
    ///   - **CCW anchor / frontier** at vertex `0` (= the junction
    ///     where the central tile meets the CCW-most ctx tile).
    ///
    /// The window **extends the match interval outward through one
    /// segment of ctx on each side**, ending at the next junctions
    /// past the two matched ones:
    ///   - **j_cw** = next junction CW of `gap_start` (across one
    ///     ctx-side segment on the CW side of the match),
    ///   - **j_ccw** = next junction CCW of vertex `0` (across one
    ///     ctx-side segment on the CCW side of the match).
    ///
    /// So geometrically the window is:
    ///
    /// ```text
    ///  [ ctx tile X's tail-segment ] [ central's free edges ] [ ctx tile Y's head-segment ]
    ///  j_cw —— gap_start ———————————————————————————————— 0 —— j_ccw
    ///           ^ matched junction                  matched junction ^
    /// ```
    ///
    /// where tile X is the CW-most ctx tile and tile Y the CCW-most.
    /// If `gap_start` (or 0) is the only junction on its side of the
    /// match (= the adjacent ctx tile's segment wraps all the way to
    /// the opposite anchor), the extension reaches that opposite
    /// anchor instead.
    ///
    /// # Encoding
    ///
    /// The key is `(central_tile_id, cw_anchor_on_central, window,
    /// cw_anchor_in_window)`:
    ///   - `window`: CCW traversal `j_cw → ... → gap_start → ... →
    ///     aug_n-1 → 0 → ... → j_ccw`, length
    ///     `aug_n - j_cw + j_ccw + 1`. Not canonicalized — the
    ///     window is oriented and the anchor position pins the
    ///     match interval inside it.
    ///   - `cw_anchor_in_window = gap_start - j_cw` (= length of the
    ///     CW extension segment).
    ///
    /// # Hypothesis (checked by [`diagnose_extended_window_stats`])
    ///
    /// For some tilesets kind is already determined by this local
    /// padding alone — i.e., the deeper ctx doesn't matter. Verified
    /// on spectre: 0 mixed-kind classes across 4 522 distinct phase-1
    /// windows.
    fn extended_match_window_fingerprint<T: IsRing>(
        nt: &NeighborhoodType,
        mi: &Arc<MatchTypeIndex<T>>,
    ) -> Option<(usize, usize, Vec<i8>, usize)> {
        let ac = build_attached_context(nt, mi)?;
        let aug_n = ac.aug_n;
        let gap_start = ac.gap_start;
        let aug = &ac.aug;
        // No CW survivor strip → degenerate (shouldn't happen for
        // catalog entries since `num_ctx_tiles >= 2`).
        if gap_start == 0 {
            return None;
        }
        // j_cw: walk CW from gap_start (decreasing index), find next
        // junction. Skip gap_start itself.
        let mut j_cw: Option<usize> = None;
        let mut pos = (gap_start + aug_n - 1) % aug_n;
        for _ in 0..aug_n {
            if pos == gap_start {
                break;
            }
            if aug.is_junction(pos) {
                j_cw = Some(pos);
                break;
            }
            pos = (pos + aug_n - 1) % aug_n;
        }
        let j_cw = j_cw?;
        // j_ccw: walk CCW from vertex 0 (increasing index), find next
        // junction. Skip 0 itself.
        let mut j_ccw: Option<usize> = None;
        let mut pos = 1usize % aug_n;
        for _ in 0..aug_n {
            if pos == 0 {
                break;
            }
            if aug.is_junction(pos) {
                j_ccw = Some(pos);
                break;
            }
            pos = (pos + 1) % aug_n;
        }
        let j_ccw = j_ccw?;
        // Build window CCW from j_cw through gap_start, wrapping past
        // aug_n-1 to 0, then to j_ccw.
        let angles = aug.angles();
        let mut window: Vec<i8> = Vec::new();
        // j_cw..=gap_start (ctx CW extension into match start)
        window.extend_from_slice(&angles[j_cw..=gap_start]);
        // (gap_start+1)..aug_n  (central's free edges minus the
        // gap_start vertex which is already pushed)
        window.extend_from_slice(&angles[gap_start + 1..aug_n]);
        // 0..=j_ccw  (ctx CCW extension out of match end)
        window.extend_from_slice(&angles[0..=j_ccw]);
        let cw_anchor_in_window = gap_start - j_cw;
        Some((
            nt.central_tile_id,
            nt.cw_anchor_on_central,
            window,
            cw_anchor_in_window,
        ))
    }

    /// Canonical-class fingerprint of a phase-1 NT: `(central_tile_id,
    /// cw_anchor_on_central, canonical_aug_angles, cw_anchor_in_canon)`.
    type CanonicalClassFp = (usize, usize, Vec<i8>, usize);

    fn canonical_class_fingerprint<T: IsRing>(
        nt: &NeighborhoodType,
        mi: &Arc<MatchTypeIndex<T>>,
    ) -> Option<CanonicalClassFp> {
        let ac = build_attached_context(nt, mi)?;
        let aug_n = ac.aug_n;
        let angles = ac.aug.angles().to_vec();
        let rot = crate::geom::rat::lex_min_rot(&angles);
        let mut canon = angles;
        canon.rotate_left(rot);
        // canon[i] = aug.angles()[(i + rot) % aug_n]. The CW anchor
        // vertex on aug lives at index ac.gap_start (= first gap
        // edge's starting vertex). Its position on the canonical
        // boundary is (gap_start - rot) mod aug_n.
        let cw_anchor_in_canon = (ac.gap_start + aug_n - rot) % aug_n;
        Some((
            nt.central_tile_id,
            nt.cw_anchor_on_central,
            canon,
            cw_anchor_in_canon,
        ))
    }

    /// Count catalog entries that share a canonical-class fingerprint
    /// but disagree on kind. Returns `(violations, first_violation,
    /// total_classes)`.
    fn count_canonical_class_kind_violations<T: IsRing>(
        idx: &NeighborhoodIndex<T>,
    ) -> (usize, Option<String>, usize) {
        let mi = Arc::new(MatchTypeIndex::new(Arc::clone(idx.tileset())));
        let kinds = idx.classify_all();
        let mut fp_to_kind: FxHashMap<CanonicalClassFp, (NtKind, usize)> = FxHashMap::default();
        let mut violations = 0usize;
        let mut first_violation: Option<String> = None;
        for (i, entry) in idx.entries().iter().enumerate() {
            let Some(nt) = entry.as_phase1() else {
                continue;
            };
            let Some(fp) = canonical_class_fingerprint(nt, &mi) else {
                continue;
            };
            let kind = kinds[i];
            if let Some(&(prev_kind, prev_id)) = fp_to_kind.get(&fp) {
                if kind != prev_kind {
                    violations += 1;
                    if first_violation.is_none() {
                        first_violation = Some(format!(
                            "entry id {} kind={:?} shares canonical class with id {} kind={:?}",
                            i + 1,
                            kind,
                            prev_id,
                            prev_kind
                        ));
                    }
                }
            } else {
                fp_to_kind.insert(fp, (kind, i + 1));
            }
        }
        (violations, first_violation, fp_to_kind.len())
    }

    /// Pin the classification-preserving invariant: every catalog
    /// entry's kind is determined by its
    /// [`canonical_class_fingerprint`]. Two entries with the same
    /// fingerprint must classify the same. Holds on convex tilesets
    /// trivially (lots of redundancy in the BFS) and on non-convex
    /// tilesets non-trivially (the BFS is near-canonical but the
    /// frontier-position component matters).
    #[test]
    fn hex_kind_constant_per_canonical_class() {
        let (violations, msg, _) = count_canonical_class_kind_violations(hex_idx());
        assert_eq!(violations, 0, "{:?}", msg);
    }

    #[test]
    fn spectre_kind_constant_per_canonical_class() {
        let (violations, msg, _) = count_canonical_class_kind_violations(spectre_idx());
        assert_eq!(violations, 0, "{:?}", msg);
    }

    /// Square is the largest tileset; gated for cost.
    #[test]
    #[ignore]
    fn square_kind_constant_per_canonical_class() {
        let (violations, msg, _) = count_canonical_class_kind_violations(square_idx());
        assert_eq!(violations, 0, "{:?}", msg);
    }

    /// Data-only diagnostic: prints (entries, canonical-class count,
    /// compression ratio) per tileset. Useful for tracking the BFS's
    /// canonicalization quality over time without pinning fragile
    /// Data-only diagnostic: groups entries by a coarser-than-BFS
    /// equivalence and reports distinct-class counts per kind. The
    /// phase-1 key is [`extended_match_window_fingerprint`] (match
    /// interval + one ctx segment on each side); phase-2 keys are
    /// the lex_min_rot of the patch boundary, with open and closed
    /// tallied separately (open keeps the frontier vertex position;
    /// closed is bare shape).
    ///
    /// Useful for measuring how local the kind-classification
    /// invariant actually is: if the phase-1 mixed-kind count is 0,
    /// kind is determined by the immediate neighborhood alone (no
    /// deeper ctx needed).
    ///
    /// Run via:
    /// `cargo test --release geom::neighborhood::tests::diagnose_extended_window_stats -- --ignored --nocapture`.
    #[test]
    #[ignore]
    fn diagnose_extended_window_stats() {
        for (name, idx) in [
            ("square", square_idx() as &NeighborhoodIndex<ZZ12>),
            ("hex", hex_idx()),
            ("spectre", spectre_idx()),
        ] {
            let mi = Arc::new(MatchTypeIndex::new(Arc::clone(idx.tileset())));
            let kinds = idx.classify_all();

            // Phase-1 key: extended-match-window fingerprint
            //   = (central_tile_id, cw_anchor_on_central,
            //      window_angles, cw_anchor_in_window)
            //   — strictly coarser than canonical_class_fingerprint.
            // Phase-2 closed key: (central_tile_id,
            //              lex_min_rot(st.angles))
            //   — central is interior, no frontier; the bare shape
            //   suffices.
            // Phase-2 open key: (central_tile_id,
            //              lex_min_rot(st.angles), open_vertex_in_canon)
            //   — anchor by the frontier vertex's position on the
            //   canonical boundary.
            type P1Key = (usize, usize, Vec<i8>, usize);
            type P2OpenKey = (usize, Vec<i8>, usize);
            type P2ClosedKey = (usize, Vec<i8>);
            let mut p1: FxHashMap<P1Key, Vec<NtKind>> = FxHashMap::default();
            let mut p2_open: FxHashMap<P2OpenKey, Vec<NtKind>> = FxHashMap::default();
            let mut p2_closed: FxHashMap<P2ClosedKey, Vec<NtKind>> = FxHashMap::default();
            for (i, entry) in idx.entries().iter().enumerate() {
                let kind = kinds[i];
                match entry {
                    NtEntry::Phase1(nt) => {
                        let Some(fp) = extended_match_window_fingerprint(nt, &mi) else {
                            continue;
                        };
                        p1.entry(fp).or_default().push(kind);
                    }
                    NtEntry::Phase2(st) => {
                        let angles = st.angles.clone();
                        let n = angles.len();
                        let rot = crate::geom::rat::lex_min_rot(&angles);
                        let mut canon = angles;
                        canon.rotate_left(rot);
                        if st.is_closed {
                            p2_closed
                                .entry((st.central_tile_id, canon))
                                .or_default()
                                .push(kind);
                        } else {
                            let open_in_canon = if n > 0 {
                                (st.open_vertex_pos + n - rot) % n
                            } else {
                                0
                            };
                            p2_open
                                .entry((st.central_tile_id, canon, open_in_canon))
                                .or_default()
                                .push(kind);
                        }
                    }
                }
            }

            // Per bucket: distinct classes per kind (using class's
            // first-kind if uniform, else mark mixed).
            fn tally<K>(buckets: &FxHashMap<K, Vec<NtKind>>) -> (usize, usize, [usize; 4]) {
                let mut by_kind = [0usize; 4]; // dead, undead, blessed, free
                let mut mixed = 0usize;
                for kinds in buckets.values() {
                    let first = kinds[0];
                    if kinds.iter().any(|k| *k != first) {
                        mixed += 1;
                    }
                    let idx = match first {
                        NtKind::Dead => 0,
                        NtKind::Undead => 1,
                        NtKind::Blessed => 2,
                        NtKind::Free => 3,
                    };
                    by_kind[idx] += 1;
                }
                (buckets.len(), mixed, by_kind)
            }
            let (n_p1, mixed_p1, k_p1) = tally(&p1);
            let (n_p2o, mixed_p2o, k_p2o) = tally(&p2_open);
            let (n_p2c, mixed_p2c, k_p2c) = tally(&p2_closed);

            eprintln!("=== {name} ===");
            eprintln!("  total entries: {}", idx.num_types());
            eprintln!(
                "  phase-1 distinct aug-boundaries: {}  (mixed-kind classes: {})",
                n_p1, mixed_p1
            );
            eprintln!(
                "    dead={} undead={} blessed={} free={}",
                k_p1[0], k_p1[1], k_p1[2], k_p1[3]
            );
            eprintln!(
                "  phase-2 open distinct boundaries: {}  (mixed-kind classes: {})",
                n_p2o, mixed_p2o
            );
            eprintln!(
                "    dead={} undead={} blessed={} free={}",
                k_p2o[0], k_p2o[1], k_p2o[2], k_p2o[3]
            );
            eprintln!(
                "  phase-2 closed distinct boundaries: {}  (mixed-kind classes: {})",
                n_p2c, mixed_p2c
            );
            eprintln!(
                "    dead={} undead={} blessed={} free={}",
                k_p2c[0], k_p2c[1], k_p2c[2], k_p2c[3]
            );
        }
    }

    /// exact-count regressions. Run via
    /// `cargo test --release geom::neighborhood::tests::diagnose_canonical_class_compression -- --ignored --nocapture`.
    #[test]
    #[ignore]
    fn diagnose_canonical_class_compression() {
        for (name, idx) in [
            ("square", square_idx() as &NeighborhoodIndex<ZZ12>),
            ("hex", hex_idx()),
            ("spectre", spectre_idx()),
        ] {
            let (violations, _, n_classes) = count_canonical_class_kind_violations(idx);
            let n = idx.num_types();
            eprintln!(
                "{name}: entries={} canonical_classes={} ratio={:.2}x violations={}",
                n,
                n_classes,
                n as f64 / n_classes as f64,
                violations
            );
        }
    }

    /// Combined completeness + transition correctness check, using
    /// `rat.get_match` directly on each NT's augmented boundary as
    /// the independent reference.
    ///
    /// # Fingerprint level
    ///
    /// Comparison is at the **augmented-boundary fingerprint** level
    /// (see [`aug_boundary_fingerprint`]). That fingerprint is
    /// stricter than the interface fingerprint and looser than
    /// `PartialEq` on `NeighborhoodType`: it distinguishes patches
    /// whose full perimeters differ but treats two BFS entries with
    /// the same augmented patch as equivalent (= the BFS may produce
    /// multiple entries per geometric state via different
    /// `num_ctx_tiles` / `vt_seq` encodings, and we want to ignore
    /// that here).
    ///
    /// # Properties
    ///
    /// For each src, for each canonical petal placement
    /// (brute-enumerated via `rat.get_match`) absorbing the frontier
    /// edge:
    ///
    ///   1. **Completeness**: the trial's augmented-boundary
    ///      fingerprint is in the catalog, or the petal closed the
    ///      configuration. Catches "BFS missed a reachable state".
    ///   2. **Transition fingerprint coverage**: the set of distinct
    ///      destination fingerprints recorded for `(src, tile_id,
    ///      tile_offset)` includes the trial's destination
    ///      fingerprint. Catches "BFS recorded a transition pointing
    ///      to a geometrically-wrong destination".
    ///
    /// Failure modes NOT caught by this check:
    ///   - A bug at *interface* granularity where two distinct
    ///     interfaces collapse to the same augmented-boundary
    ///     fingerprint by accident (unlikely; geometrically rare).
    ///   - A bug at *id* granularity where two entries with the same
    ///     augmented fingerprint differ in some other respect that
    ///     matters to downstream consumers. (Currently no consumer
    ///     cares about anything other than the interface, so this
    ///     wouldn't matter.)
    ///
    /// Uses NO logic from `explore_phase1` / `explore_phase2` /
    /// `try_step_*` / `compute_candidates_covering_position` —
    /// pure brute force.
    fn assert_brute_completeness_and_transition_correctness<T>(idx: &NeighborhoodIndex<T>)
    where
        T: IsRing,
    {
        let mi = Arc::new(MatchTypeIndex::new(Arc::clone(idx.tileset())));
        // fp_set: set of canonical fingerprints in the catalog.
        // id_to_fp: per-entry fingerprint for transition cross-check.
        let mut fp_set: FxHashMap<(usize, usize, Vec<i8>), ()> = FxHashMap::default();
        let mut id_to_fp: Vec<Option<(usize, usize, Vec<i8>)>> =
            Vec::with_capacity(idx.num_types());
        for entry in idx.entries() {
            let fp = match entry {
                NtEntry::Phase1(nt) => aug_boundary_fingerprint(nt, &mi),
                // Phase-2 entries have no aug boundary to fingerprint
                // (central is interior). Skip; their classification
                // correctness is checked separately.
                NtEntry::Phase2(_) => None,
            };
            if let Some(ref fp) = fp {
                fp_set.insert(fp.clone(), ());
            }
            id_to_fp.push(fp);
        }
        // recorded_by_key: (src_id, tile_id, tile_offset) -> set of
        // destination fingerprints (or "CLOSED" sentinel = None).
        type DstFp = Option<(usize, usize, Vec<i8>)>;
        let mut recorded_by_key: FxHashMap<
            (usize, usize, usize),
            std::collections::HashSet<DstFp>,
        > = FxHashMap::default();
        for t in idx.transitions() {
            // id_to_fp[i] is None for phase-2 destinations (= closed
            // and open phase-2 entries don't have an aug-boundary
            // fingerprint), so transitions to phase-2 surface as
            // dst_fp = None.
            let dst_fp: DstFp = id_to_fp[t.dst_id - 1].clone();
            recorded_by_key
                .entry((t.src_id, t.tile_id, t.tile_offset))
                .or_default()
                .insert(dst_fp);
        }

        for (i, entry) in idx.entries().iter().enumerate() {
            let src_id = i + 1;
            let Some(nt) = entry.as_phase1() else {
                continue;
            };
            let Some(ac) = build_attached_context(nt, &mi) else {
                continue;
            };
            let target_edge = ac.frontier_pos_on_aug;
            let n_aug = ac.aug_n;
            let aug_rat = crate::geom::rat::Rat::from_slice_unchecked(ac.aug.angles());
            let mut seen: FxHashMap<(usize, usize, usize, usize), ()> = FxHashMap::default();
            for tile_b in 0..mi.tileset().num_tiles() {
                let other = mi.tileset().rat(tile_b);
                let n_b = other.seq().len();
                for pos in 0..n_aug {
                    for b_off in 0..n_b {
                        let (ns, len, ne) = aug_rat.get_match((pos as i64, b_off as i64), other);
                        if len < 1 {
                            continue;
                        }
                        let ns_u = ns.rem_euclid(n_aug as i64) as usize;
                        let ne_u = ne.rem_euclid(n_b as i64) as usize;
                        let pm = PatchMatch::new(
                            EdgeRange::new(ns_u, len),
                            Segment::new(tile_b, EdgeRange::new(ne_u, len)),
                        );
                        if !match_absorbs_edge(&pm, target_edge, n_aug) {
                            continue;
                        }
                        if seen.contains_key(&(ns_u, len, ne_u, tile_b)) {
                            continue;
                        }
                        let mut trial = ac.aug.clone();
                        if !trial.add_tile(&pm) {
                            continue;
                        }
                        seen.insert((ns_u, len, ne_u, tile_b), ());

                        let trial_dst_fp: DstFp =
                            if !trial.patch_tile_ids().contains(&ac.central_ptid) {
                                None
                            } else {
                                let trial_angles = trial.angles().to_vec();
                                let rot = crate::geom::rat::lex_min_rot(&trial_angles);
                                let mut canon = trial_angles;
                                canon.rotate_left(rot);
                                let fp = (nt.central_tile_id, nt.cw_anchor_on_central, canon);
                                assert!(
                                    fp_set.contains_key(&fp),
                                    "completeness violation: src={} brute glue \
                                     (tile={}, start_a={}, len={}, start_b={}) \
                                     produces state not in catalog",
                                    src_id,
                                    tile_b,
                                    ns_u,
                                    len,
                                    ne_u
                                );
                                Some(fp)
                            };

                        let key = (src_id, tile_b, ne_u);
                        let recorded_set = recorded_by_key.get(&key);
                        assert!(
                            recorded_set.is_some_and(|s| s.contains(&trial_dst_fp)),
                            "transition fingerprint mismatch: src={} brute glue \
                             (tile={}, start_a={}, len={}, start_b={}) -> {} but \
                             catalog has no transition with that destination \
                             fingerprint for (src, tile, tile_offset)",
                            src_id,
                            tile_b,
                            ns_u,
                            len,
                            ne_u,
                            if trial_dst_fp.is_none() {
                                "CLOSED".to_string()
                            } else {
                                "Open(fp)".to_string()
                            }
                        );
                    }
                }
            }
        }
    }

    #[test]
    fn spectre_brute_complete_and_correct() {
        assert_brute_completeness_and_transition_correctness(spectre_idx());
    }

    #[test]
    fn hex_brute_complete_and_correct() {
        assert_brute_completeness_and_transition_correctness(hex_idx());
    }

    /// Square has 109k entries and 437k transitions; gated behind
    /// `--ignored` because runtime is order minutes.
    #[test]
    #[ignore]
    fn square_brute_complete_and_correct() {
        assert_brute_completeness_and_transition_correctness(square_idx());
    }

    /// Re-derive the four-kind classification predicates from
    /// `idx.transitions()` and assert they agree with `classify_all`.
    ///
    /// Cross-checks each kind via global reachability computed
    /// independently of `classify_all`'s algorithm:
    ///   - `reaches_closed[i]` = exists a forward path from i to a
    ///     closed phase-2 terminal
    ///   - `reaches_dead[i]` = exists a forward path from i to a
    ///     stuck (no-outgoing, not closed-terminal) entry
    ///
    /// The four kinds are pinned by these reachability properties:
    ///   - Dead: no outgoing, not closed-terminal
    ///   - Undead: has outgoing AND NOT reaches_closed
    ///   - Blessed: has outgoing AND NOT reaches_dead (or IS
    ///     closed-terminal)
    ///   - Free: has outgoing AND reaches_closed AND reaches_dead
    ///
    /// Catches the V2b shape (closing-as-escape blindspot) AND the
    /// "Free is the trash bucket" shape where Free becomes vacuous.
    fn assert_classify_invariants<T: IsRing>(idx: &NeighborhoodIndex<T>) {
        let kinds = idx.classify_all();
        let n = idx.num_types();

        // Identify closed phase-2 entries (= terminal Blessed states).
        let is_closed_terminal: Vec<bool> = idx
            .entries()
            .iter()
            .map(|e| matches!(e, NtEntry::Phase2(st) if st.is_closed))
            .collect();

        let mut preds: Vec<Vec<usize>> = vec![Vec::new(); n];
        let mut has_outgoing = vec![false; n];
        for t in idx.transitions() {
            let src = t.src_id - 1;
            has_outgoing[src] = true;
            preds[t.dst_id - 1].push(src);
        }

        let propagate = |seeds: Vec<usize>| -> Vec<bool> {
            let mut reached = vec![false; n];
            let mut queue: VecDeque<usize> = VecDeque::new();
            for s in seeds {
                if !reached[s] {
                    reached[s] = true;
                    queue.push_back(s);
                }
            }
            while let Some(v) = queue.pop_front() {
                for &p in &preds[v] {
                    if !reached[p] {
                        reached[p] = true;
                        queue.push_back(p);
                    }
                }
            }
            reached
        };

        // "reaches_closed": there's a forward path from i to a
        // closed-terminal entry (Blessed escape).
        let closing_seeds: Vec<usize> = (0..n).filter(|&i| is_closed_terminal[i]).collect();
        let reaches_closed = propagate(closing_seeds);

        // "reaches_dead": there's a forward path from i to an entry
        // that's stuck (= has no outgoing AND is not closed-terminal).
        let dead_seeds: Vec<usize> = (0..n)
            .filter(|&i| !has_outgoing[i] && !is_closed_terminal[i])
            .collect();
        let reaches_dead = propagate(dead_seeds);

        for (i, &kind) in kinds.iter().enumerate() {
            let id = i + 1;
            // Closed-terminal entries are always Blessed (no
            // outgoing but reachable-as-closed trivially).
            let expected = if is_closed_terminal[i] {
                NtKind::Blessed
            } else if !has_outgoing[i] {
                NtKind::Dead
            } else if !reaches_closed[i] {
                NtKind::Undead
            } else if !reaches_dead[i] {
                NtKind::Blessed
            } else {
                NtKind::Free
            };
            assert_eq!(
                kind,
                expected,
                "NT id {id} classify_all says {:?} but reachability says {:?} \
                 (has_outgoing={} reaches_closed={} reaches_dead={} closed_terminal={})",
                kind,
                expected,
                has_outgoing[i],
                reaches_closed[i],
                reaches_dead[i],
                is_closed_terminal[i]
            );
        }
    }

    #[test]
    #[cfg_attr(
        debug_assertions,
        ignore = "release-only: square idx build ~21s in release, much slower in debug"
    )]
    fn square_classify_invariants() {
        assert_classify_invariants(square_idx());
    }

    #[test]
    fn hex_classify_invariants() {
        assert_classify_invariants(hex_idx());
    }

    #[test]
    fn spectre_classify_invariants() {
        assert_classify_invariants(spectre_idx());
    }

    #[test]
    fn classify_all_returns_one_per_entry() {
        for idx in [square_idx(), hex_idx()] {
            let kinds = idx.classify_all();
            assert_eq!(kinds.len(), idx.num_types());
            // BFS reaches a frontier where every petal closes, so there must
            // be at least one Blessed entry (= all outgoing transitions go to
            // closed).
            let n_blessed = kinds.iter().filter(|k| **k == NtKind::Blessed).count();
            assert!(n_blessed > 0, "expected at least one Blessed entry");
        }
    }

    #[test]
    fn bfs_produces_transitions() {
        let sq_idx = square_idx();
        assert!(sq_idx.num_types() > 0);
        assert!(
            !sq_idx.transitions().is_empty(),
            "BFS should produce transitions"
        );
        // Both src_id and dst_id are 1-based entry ids.
        for t in sq_idx.transitions() {
            assert!(t.src_id >= 1 && t.src_id <= sq_idx.num_types());
            assert!(t.dst_id >= 1 && t.dst_id <= sq_idx.num_types());
        }

        let hex_idx = hex_idx();
        assert!(hex_idx.num_types() > 0);
        assert!(!hex_idx.transitions().is_empty());
        for t in hex_idx.transitions() {
            assert!(t.src_id >= 1 && t.src_id <= hex_idx.num_types());
            assert!(t.dst_id >= 1 && t.dst_id <= hex_idx.num_types());
        }
    }

    fn validate_seeds<T: IsRing>(idx: &NeighborhoodIndex<T>) -> Vec<String> {
        let mi = Arc::new(MatchTypeIndex::new(Arc::clone(idx.tileset())));
        let mut errors = Vec::new();
        for entry in idx.entries() {
            let Some(nt) = entry.as_phase1() else {
                continue;
            };
            let Some((mut ctx, junc_positions)) =
                GrowingPatch::construct_witness_from_vt_sequence(&nt.vt_seq, Arc::clone(&mi))
            else {
                errors.push(format!(
                    "nt c={} ac={} ax={}: reconstruct failed",
                    nt.central_tile_id, nt.cw_anchor_on_central, nt.cw_anchor_on_context
                ));
                continue;
            };
            let ctx_n = ctx.boundary_len();
            let first_junc = junc_positions[0];
            let anchor_pos = (first_junc + ctx_n - nt.cw_anchor_on_context) % ctx_n;
            // Reconstruction must be unique: collect all PatchMatches
            // that satisfy the metadata, not just the first one. A
            // `.find` that silently accepts ambiguity is exactly how
            // the asymmetric-convention tile_offset bug stayed hidden
            // (see `vertextypes::spectre_old_encoding_*`).
            let matching: Vec<_> = ctx
                .get_all_matches()
                .into_iter()
                .filter(|pm| {
                    pm.b.tile_id == nt.central_tile_id
                        && pm.a_range.start_offset == anchor_pos
                        && pm.b.range.start_offset == nt.cw_anchor_on_central
                })
                .collect();
            let pm = match matching.len() {
                0 => {
                    errors.push(format!(
                        "nt c={} ac={} ax={}: no match at anchor positions",
                        nt.central_tile_id, nt.cw_anchor_on_central, nt.cw_anchor_on_context
                    ));
                    continue;
                }
                1 => matching.into_iter().next().unwrap(),
                k => {
                    errors.push(format!(
                        "nt c={} ac={} ax={}: ambiguous reconstruction \
                         ({} PatchMatches share the recorded anchor)",
                        nt.central_tile_id, nt.cw_anchor_on_central, nt.cw_anchor_on_context, k
                    ));
                    continue;
                }
            };
            if !ctx.add_tile(&pm) {
                errors.push(format!(
                    "nt c={} ac={} ax={}: add_tile failed",
                    nt.central_tile_id, nt.cw_anchor_on_central, nt.cw_anchor_on_context
                ));
            }
        }
        errors
    }

    #[test]
    #[cfg_attr(
        debug_assertions,
        ignore = "release-only: square idx build ~21s in release, much slower in debug"
    )]
    fn square_seeds_validate() {
        let idx = square_idx();
        let errors = validate_seeds(idx);
        assert!(
            errors.is_empty(),
            "validation errors:\n{}",
            errors.join("\n")
        );
    }

    #[test]
    fn hex_seeds_validate() {
        let idx = hex_idx();
        let errors = validate_seeds(idx);
        assert!(
            errors.is_empty(),
            "validation errors:\n{}",
            errors.join("\n")
        );
    }

    /// Generic over the tileset: build_attached_context succeeds for
    /// every seed, the gap is non-empty, and gap_start is in range.
    fn assert_seed_geometry<T: IsRing>(idx: &NeighborhoodIndex<T>) {
        let mi = Arc::new(MatchTypeIndex::new(Arc::clone(idx.tileset())));
        for (i, entry) in idx.entries().iter().enumerate() {
            let Some(nt) = entry.as_phase1() else {
                continue;
            };
            let ac = build_attached_context(nt, &mi).unwrap_or_else(|| {
                panic!("seed {}: build_attached_context failed for nt {:?}", i, nt)
            });
            let gap_len = ac.aug_n - ac.gap_start;
            assert!(gap_len > 0, "seed {}: gap should be non-empty", i);
            assert!(
                ac.gap_start < ac.aug_n,
                "seed {}: gap_start out of range",
                i
            );
            let central_len = idx.tileset().rat(nt.central_tile_id).seq().len();
            assert!(
                gap_len < central_len,
                "seed {}: gap_len {} should be < central_len {}",
                i,
                gap_len,
                central_len
            );
            assert!(
                !explore_phase1(nt, &mi).is_empty(),
                "seed {}: should have at least one successful petal",
                i
            );
        }
    }

    #[test]
    #[cfg_attr(
        debug_assertions,
        ignore = "release-only: square idx build ~21s in release, much slower in debug"
    )]
    fn square_seed_geometry() {
        assert_seed_geometry(square_idx());
    }

    #[test]
    fn hex_seed_geometry() {
        assert_seed_geometry(hex_idx());
    }

    /// Brute-enumerate every legal 3-tile seed configuration via
    /// `rat.get_match` directly (independent of `MatchTypeIndex` and
    /// `patch.get_all_matches`, which `seed_phase` uses internally),
    /// canonicalize each, and assert the resulting set equals the
    /// catalog's seed entries (= entries with `num_ctx_tiles == 2`).
    ///
    /// Catches seed-completeness regressions of the V2c shape: if
    /// the production match enumerator misses canonical matches, the
    /// seed phase would silently under-produce, and downstream
    /// closure tests (which iterate over existing entries) couldn't
    /// recover the missing seeds.
    fn assert_seeds_match_brute<T: IsRing>(tileset: Arc<TileSet<T>>, idx: &NeighborhoodIndex<T>) {
        type Class = (usize, usize, Vec<i8>, usize);
        let mi = Arc::new(MatchTypeIndex::new(Arc::clone(&tileset)));

        // Brute side: enumerate canonical 3-tile patches via direct
        // get_match, applying the same filters seed_phase does.
        let mut brute: FxHashMap<Class, ()> = FxHashMap::default();
        let num_tiles = tileset.num_tiles();
        for a in 0..num_tiles {
            let tile_a = tileset.rat(a);
            let n_a = tile_a.seq().len();
            for b in 0..num_tiles {
                let tile_b = tileset.rat(b);
                let n_b = tile_b.seq().len();
                let mut seen_ab: FxHashMap<(usize, usize, usize), ()> = FxHashMap::default();
                for ia in 0..n_a {
                    for ib in 0..n_b {
                        let (ns, len, ne) = tile_a.get_match((ia as i64, ib as i64), tile_b);
                        if len == 0 {
                            continue;
                        }
                        let ns_u = ns.rem_euclid(n_a as i64) as usize;
                        let ne_u = ne.rem_euclid(n_b as i64) as usize;
                        if seen_ab.contains_key(&(ns_u, len, ne_u)) {
                            continue;
                        }
                        seen_ab.insert((ns_u, len, ne_u), ());
                        if !crate::geom::glue::junctions_glueable(
                            tile_a.seq(),
                            ns_u,
                            len,
                            tile_b.seq(),
                            ne_u,
                        ) {
                            continue;
                        }
                        if tile_a
                            .try_glue_precomputed((ns, len, ne), tile_b, true)
                            .is_err()
                        {
                            continue;
                        }
                        // Build the 2-tile patch.
                        let seed = PatchSeed::new(Arc::clone(&tileset), a);
                        let pm1 = PatchMatch::new(
                            EdgeRange::new(ns_u, len),
                            Segment::new(b, EdgeRange::new(ne_u, len)),
                        );
                        let mut patch = match seed.grow(&pm1) {
                            Some(p) => p,
                            None => continue,
                        };
                        patch.normalize();
                        let patch_n = patch.boundary_len();
                        let patch_rat = crate::geom::rat::Rat::from_slice_unchecked(patch.angles());

                        // Brute third-tile candidates over the 2-tile boundary.
                        let mut seen_third: FxHashMap<(usize, usize, usize, usize), ()> =
                            FxHashMap::default();
                        for c in 0..num_tiles {
                            let tile_c = tileset.rat(c);
                            let n_c = tile_c.seq().len();
                            for ic in 0..patch_n {
                                for jc in 0..n_c {
                                    let (ns3, len3, ne3) =
                                        patch_rat.get_match((ic as i64, jc as i64), tile_c);
                                    if len3 == 0 {
                                        continue;
                                    }
                                    let ns3_u = ns3.rem_euclid(patch_n as i64) as usize;
                                    let ne3_u = ne3.rem_euclid(n_c as i64) as usize;
                                    if seen_third.contains_key(&(ns3_u, len3, ne3_u, c)) {
                                        continue;
                                    }
                                    seen_third.insert((ns3_u, len3, ne3_u, c), ());
                                    let pm3 = PatchMatch::new(
                                        EdgeRange::new(ns3_u, len3),
                                        Segment::new(c, EdgeRange::new(ne3_u, len3)),
                                    );
                                    let mut trial = patch.clone();
                                    if !trial.add_tile(&pm3) {
                                        continue;
                                    }
                                    // Filter: match must touch at least one
                                    // junction of the 2-tile patch (else
                                    // build_seed_nt returns None).
                                    let touches_junction = (0..patch_n).any(|jp| {
                                        if !patch.is_junction(jp) {
                                            return false;
                                        }
                                        (jp + patch_n - ns3_u) % patch_n <= len3
                                    });
                                    if !touches_junction {
                                        continue;
                                    }
                                    // Compute canonical class fingerprint.
                                    let aug_angles = trial.angles().to_vec();
                                    let aug_n = aug_angles.len();
                                    let rot = crate::geom::rat::lex_min_rot(&aug_angles);
                                    let mut canon = aug_angles;
                                    canon.rotate_left(rot);
                                    let gap_start = patch_n - len3;
                                    let cw_anchor_in_canon = (gap_start + aug_n - rot) % aug_n;
                                    brute.insert((c, ne3_u, canon, cw_anchor_in_canon), ());
                                }
                            }
                        }
                    }
                }
            }
        }

        // Catalog side: canonical class of every entry with
        // num_ctx_tiles == 2 (= seed entries). Phase-2 entries have no
        // num_ctx_tiles; skip them.
        let mut catalog: FxHashMap<Class, ()> = FxHashMap::default();
        for entry in idx.entries() {
            let Some(nt) = entry.as_phase1() else {
                continue;
            };
            if nt.num_ctx_tiles != 2 {
                continue;
            }
            if let Some(fp) = canonical_class_fingerprint(nt, &mi) {
                catalog.insert(fp, ());
            }
        }

        let brute_only: Vec<&Class> = brute.keys().filter(|k| !catalog.contains_key(*k)).collect();
        let catalog_only: Vec<&Class> =
            catalog.keys().filter(|k| !brute.contains_key(*k)).collect();
        assert!(
            brute_only.is_empty(),
            "seed completeness: {} canonical seed classes found by brute but missing from catalog",
            brute_only.len()
        );
        assert!(
            catalog_only.is_empty(),
            "seed soundness: {} catalog seed classes not produced by brute",
            catalog_only.len()
        );
    }

    #[test]
    fn hex_seeds_match_brute() {
        assert_seeds_match_brute(Arc::clone(hex_idx().tileset()), hex_idx());
    }

    #[test]
    #[cfg_attr(
        debug_assertions,
        ignore = "release-only: square idx build ~21s in release, much slower in debug"
    )]
    fn square_seeds_match_brute() {
        assert_seeds_match_brute(Arc::clone(square_idx().tileset()), square_idx());
    }

    #[test]
    fn spectre_seeds_match_brute() {
        assert_seeds_match_brute(Arc::clone(spectre_idx().tileset()), spectre_idx());
    }

    #[test]
    fn gap_edges_are_central_tile() {
        let idx = square_idx();
        let mi = Arc::new(MatchTypeIndex::new(Arc::clone(idx.tileset())));
        for (i, entry) in idx.entries().iter().enumerate() {
            let Some(nt) = entry.as_phase1() else {
                continue;
            };
            let ac = build_attached_context(nt, &mi)
                .unwrap_or_else(|| panic!("seed {}: build_attached_context failed", i));
            let edges = ac.aug.edges();
            let ptids = ac.aug.patch_tile_ids();
            let central_ptid = ptids[ac.gap_start];
            for k in ac.gap_start..ac.aug_n {
                assert_eq!(
                    edges[k].tile_id, nt.central_tile_id,
                    "seed {}: gap edge at pos {} should be central tile",
                    i, k
                );
                assert_eq!(
                    ptids[k], central_ptid,
                    "seed {}: gap edge at pos {} should have same ptid",
                    i, k
                );
            }
        }
    }

    #[test]
    fn ccw_frontier_at_gap_end() {
        // After `build_attached_context`, the boundary is rotated so
        // gap_end == 0. The CCW frontier vertex must therefore be at
        // position 0 - confirming gap_end is itself a junction.
        let idx = hex_idx();
        let mi = Arc::new(MatchTypeIndex::new(Arc::clone(idx.tileset())));
        for (i, entry) in idx.entries().iter().enumerate() {
            let Some(nt) = entry.as_phase1() else {
                continue;
            };
            let ac = build_attached_context(nt, &mi)
                .unwrap_or_else(|| panic!("seed {}: build_attached_context failed", i));
            assert_eq!(
                ac.frontier_pos_on_aug, 0,
                "seed {}: gap_end (pos 0 on aug) should be the CCW frontier junction",
                i
            );
            assert!(
                ac.aug.is_junction(0),
                "seed {}: position 0 must be junction",
                i
            );
        }
    }

    #[test]
    fn explore_one_square_has_petals() {
        let idx = square_idx();
        let mi = Arc::new(MatchTypeIndex::new(Arc::clone(idx.tileset())));
        let nt = idx.entries()[0]
            .as_phase1()
            .expect("first entry should be phase-1");
        assert!(
            !explore_phase1(nt, &mi).is_empty(),
            "should have at least one petal outcome"
        );
    }

    #[test]
    fn explore_one_hex_seeds_reconstruct() {
        let idx = hex_idx();
        let mi = Arc::new(MatchTypeIndex::new(Arc::clone(idx.tileset())));
        let mut checked = 0usize;
        let mut errors = Vec::new();
        for (i, entry) in idx.entries().iter().enumerate() {
            let Some(nt) = entry.as_phase1() else {
                continue;
            };
            for outcome in explore_phase1(nt, &mi) {
                let new_nt = match &outcome.kind {
                    OutcomeKind::Phase2(_) => continue,
                    OutcomeKind::Phase1(nt) => nt.clone(),
                };
                let (mut ctx, junc_pos) = GrowingPatch::construct_witness_from_vt_sequence(
                    &new_nt.vt_seq,
                    Arc::clone(&mi),
                )
                .unwrap_or_else(|| {
                    panic!(
                        "seed {} result: reconstruct failed for new_nt {:?}",
                        i, new_nt
                    )
                });
                let first_junc = junc_pos[0];
                let ctx_n = ctx.boundary_len();
                let anchor_pos = (first_junc + ctx_n - new_nt.cw_anchor_on_context) % ctx_n;
                // See `validate_seeds` for why we collect rather than `.find`.
                let matching: Vec<_> = ctx
                    .get_all_matches()
                    .into_iter()
                    .filter(|pm| {
                        pm.b.tile_id == new_nt.central_tile_id
                            && pm.a_range.start_offset == anchor_pos
                            && pm.b.range.start_offset == new_nt.cw_anchor_on_central
                    })
                    .collect();
                let pm = match matching.len() {
                    0 => {
                        errors.push(format!(
                            "seed {}: no match c={} ac={} ax={} (ctx_n={})",
                            i,
                            new_nt.central_tile_id,
                            new_nt.cw_anchor_on_central,
                            new_nt.cw_anchor_on_context,
                            ctx.boundary_len()
                        ));
                        continue;
                    }
                    1 => matching.into_iter().next().unwrap(),
                    k => {
                        errors.push(format!(
                            "seed {}: ambiguous reconstruction \
                             ({} PatchMatches share anchor)",
                            i, k
                        ));
                        continue;
                    }
                };
                if !ctx.add_tile(&pm) {
                    errors.push(format!(
                        "seed {}: add_tile failed for new_nt {:?}",
                        i, new_nt
                    ));
                    continue;
                }
                checked += 1;
            }
        }
        assert!(checked > 0, "should have validated at least one new NT");
        assert!(
            errors.is_empty(),
            "{} reattach errors (first few): {}",
            errors.len(),
            errors[..errors.len().min(10)].join("; ")
        );
    }

    #[test]
    fn explore_one_square_seeds_reconstruct() {
        let idx = square_idx();
        let mi = Arc::new(MatchTypeIndex::new(Arc::clone(idx.tileset())));
        let mut checked = 0usize;
        let mut errors = Vec::new();
        for (i, entry) in idx.entries().iter().enumerate() {
            let Some(nt) = entry.as_phase1() else {
                continue;
            };
            for outcome in explore_phase1(nt, &mi) {
                let new_nt = match &outcome.kind {
                    OutcomeKind::Phase2(_) => continue,
                    OutcomeKind::Phase1(nt) => nt.clone(),
                };
                let (mut ctx, junc_pos) = GrowingPatch::construct_witness_from_vt_sequence(
                    &new_nt.vt_seq,
                    Arc::clone(&mi),
                )
                .unwrap_or_else(|| {
                    panic!(
                        "seed {} result: reconstruct failed for new_nt {:?}",
                        i, new_nt
                    )
                });
                let first_junc = junc_pos[0];
                let ctx_n = ctx.boundary_len();
                let anchor_pos = (first_junc + ctx_n - new_nt.cw_anchor_on_context) % ctx_n;
                // See `validate_seeds` for why we collect rather than `.find`.
                let matching: Vec<_> = ctx
                    .get_all_matches()
                    .into_iter()
                    .filter(|pm| {
                        pm.b.tile_id == new_nt.central_tile_id
                            && pm.a_range.start_offset == anchor_pos
                            && pm.b.range.start_offset == new_nt.cw_anchor_on_central
                    })
                    .collect();
                let pm = match matching.len() {
                    0 => {
                        errors.push(format!(
                            "seed {}: no match c={} ac={} ax={} (ctx_n={})",
                            i,
                            new_nt.central_tile_id,
                            new_nt.cw_anchor_on_central,
                            new_nt.cw_anchor_on_context,
                            ctx.boundary_len()
                        ));
                        continue;
                    }
                    1 => matching.into_iter().next().unwrap(),
                    k => {
                        errors.push(format!(
                            "seed {}: ambiguous reconstruction \
                             ({} PatchMatches share anchor)",
                            i, k
                        ));
                        continue;
                    }
                };
                if !ctx.add_tile(&pm) {
                    errors.push(format!(
                        "seed {}: add_tile failed for new_nt {:?}",
                        i, new_nt
                    ));
                    continue;
                }
                checked += 1;
            }
        }
        assert!(checked > 0, "should have validated at least one new NT");
        assert!(
            errors.is_empty(),
            "{} reattach errors (first few): {}",
            errors.len(),
            errors[..errors.len().min(10)].join("; ")
        );
    }
}