ferro-hgvs 1.0.0

HGVS variant normalizer - part of the ferro bioinformatics toolkit
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
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
//! An exhaustive, spec-derived conformance corpus, enumerated deterministically.
//!
//! # The measurement gap this closes
//!
//! Conformance is currently measured by the generated spec fixture, which
//! harvests HGVS strings out of the recommendations: 934 rows, of which **52 are
//! multi-member cis alleles** and **40 carry a spec-stated answer**. That ceiling
//! is set by the spec, not by us — "matches the form the spec publishes" needs
//! the spec to have published one. So a change to the multi-member partitioner
//! measures `0 gained, 0 lost`, which is measurement blindness rather than
//! neutrality.
//!
//! The way past it is to stop needing a published answer. Generate a variant,
//! then generate *many spellings of the same variant* by re-partitioning it and
//! shifting each partition within its ambiguous run. Every spelling in such a
//! family denotes the same sequence **by construction**, which makes four
//! properties checkable with no oracle at all:
//!
//! 1. **Validity** — the output must parse, and must not violate an absolute
//!    prohibition. Two members claiming the same territory denote no sequence.
//! 2. **Confluence** — every spelling in a family must reach one output.
//! 3. **Idempotency** — each output must be its own fixed point.
//! 4. **Sequence preservation** — each output must denote the input's bases,
//!    verified through [`hgvs_to_spdi`] rather than through the normalizer.
//!
//! # Why this lives in the library
//!
//! For the same reason the rest of `conformance/` does: so `examples/` and
//! `tests/` share one definition. It buys something extra here — the corpus is
//! **enumerated at test time** rather than read from a generated artifact, so
//! every case runs on every `cargo test` with no fixture to stage, no CI artifact
//! to plumb, and no committed data file (which the project's "generate test data
//! programmatically" rule forbids anyway).
//!
//! # Multi-member is deliberately overweighted
//!
//! Real corpora contain 592 multi-member cis alleles in 9,949,738 rows
//! (0.006%, `examples/harvest_multi_member_cis.rs`). They are simultaneously the
//! rarest shape in nature and the most intricate in the code: partitioning,
//! separation, member ordering, overlap detection, coalescing and typing
//! interact *only* there. So this corpus samples them at roughly four orders of
//! magnitude above their natural rate — see [`SpecCorpus::multi_member_rows`],
//! which the axis test pins.
//!
//! # The three recorded blindnesses, and where each is varied
//!
//! This repository has been bitten three times by a corpus that could not vary
//! the property under test, each invisible to the one before. Every generator
//! added here must state where it varies all three:
//!
//! | blindness | what could not vary | varied by |
//! |---|---|---|
//! | #1456 | member **geometry** — all families paired members on disjoint territory, so no conflicting allele existed | [`Geometry`], including four geometries that denote *no* sequence and must be refused |
//! | #1460 | **scale** — 20-mer cores, so nothing reached `MAX_SPLIT_BLOCK` (1024) | [`BLOCK_LADDER`] and [`SEPARATION_LADDER`], which straddle every reachable threshold |
//! | #1478 | **transcript geometry** — `Exon::with_genomic(1, 1, tx_len, …)` builds one exon with `CDS_START = 1`, so no row crossed a junction or sat in the 5'UTR | [`RefShape::CodingMultiExon`] on both strands, with [`Region`] placing rows in the 5'UTR, across each junction, and in the 3'UTR |
//!
//! [`RefShape::CodingSingleExon`] is retained on purpose as the **control**: it
//! is exactly the shape #1478 names, so a divergence that appears only on the
//! multi-exon shapes is attributable.

use std::collections::BTreeMap;
use std::fmt;

use crate::reference::transcript::{Exon, GenomeBuild, ManeStatus, Strand, Transcript};
use crate::reference::MockProvider;
use crate::spdi::hgvs_to_spdi;
use crate::{parse_hgvs, HgvsVariant};

// ---------------------------------------------------------------------------
// Synthetic reference conventions
// ---------------------------------------------------------------------------

/// Bases of period-4 `ACGT` padding either side of a genomic core.
///
/// Shared with `tests/it/common/synthetic.rs` and
/// `examples/generate_cis_confluence_corpus.rs`: the base immediately 5' of the
/// core is `T` and the one immediately 3' of it is `A`, so a core that neither
/// starts with `A` nor ends with `T` cannot extend the pad's own rotation and a
/// repeat tract is bounded to the core.
pub const PAD_OFFSET: usize = 256;

/// The genomic contig a `g.` row is drawn against.
pub const GENOMIC_CONTIG: &str = "NC_TEST.1";
/// The coding transcript a `c.` row is drawn against.
pub const CODING_ACCESSION: &str = "NM_TEST.1";
/// The non-coding transcript an `n.` row is drawn against.
pub const NONCODING_ACCESSION: &str = "NR_TEST.1";
/// The contig every synthetic transcript is placed on.
///
/// Spelled as an accession rather than `chr_synth` so the genomic-wrapper form
/// `NC_SYNTH.1(NM_TEST.1):c.20+2del` is expressible. That matters because
/// `checklist.md:20`'s note makes the wrapper **mandatory** for an intronic
/// position: "NM reference sequences … can only be used to describe variants in
/// introns using a `c.` prefix when a genomic reference sequence is given on
/// which the coding DNA reference sequence is annotated".
pub const TRANSCRIPT_CONTIG: &str = "NC_SYNTH.1";

/// Genomic bases between consecutive exons of a synthetic multi-exon
/// transcript.
///
/// Wide enough that an intronic offset ladder up to `±5` stays inside the
/// intron, and wide enough that a 3'-shift inside one exon cannot reach the
/// next.
const INTRON_LEN: usize = 60;

/// How far either way [`equivalent_placements`] searches for an equivalent
/// placement of one member.
///
/// A brute-force search rather than a re-derivation of the shift rules: the
/// question asked is exactly "does this denote the same sequence", and answering
/// it with the normalizer's own rules would make the corpus agree with the
/// normalizer by construction.
const SHIFT_SEARCH: isize = 24;

// ---------------------------------------------------------------------------
// The declared shape space
// ---------------------------------------------------------------------------

/// Block lengths the scale stratum enumerates, straddling every threshold the
/// canonicalizer keys on that is reachable inside a bounded corpus.
///
/// `CANONICAL_PAD` (128), `MAX_TIE_BREAK_SWEEP` (256), `MAX_SPLIT_BLOCK` (1024)
/// and `MAX_CANONICAL_WINDOW` (4096) each get a value below, on and above them,
/// because every one of those is an inclusive-or-exclusive boundary whose side
/// matters. `MAX_SHIFT_TRACT` (32768) and `MAX_APPLY_WINDOW` (100000) are
/// **declared out of bounds** rather than silently absent: see
/// [`CorpusBounds::extended_scale`].
pub const BLOCK_LADDER: &[usize] = &[
    1, 2, 4, 8, 120, 128, 136, 248, 256, 264, 1016, 1024, 1032, 4088, 4096, 4104,
];

/// Separations the scale stratum enumerates. Separation drives the *window*
/// rather than the block: the canonicalizer fetches the members' hull widened by
/// `CANONICAL_PAD` either side and refuses past `MAX_CANONICAL_WINDOW`, so a
/// large separation exercises the refusal-and-fall-back path that a large block
/// does not.
pub const SEPARATION_LADDER: &[usize] = &[
    0, 1, 2, 3, 5, 8, 120, 128, 136, 1016, 1024, 1032, 3832, 3968, 4104,
];

/// Block lengths added by [`CorpusBounds::extended_scale`], crossing
/// `MAX_SHIFT_TRACT` (32768) and approaching `MAX_APPLY_WINDOW` (100000).
///
/// Off by default and stated as a bound rather than omitted: one cell here costs
/// a ~200 kB synthetic reference and, measured, two orders of magnitude more
/// normalization time than the whole rest of the stratum, so including it by
/// default would make the corpus's runtime a property of three cells.
pub const EXTENDED_BLOCK_LADDER: &[usize] = &[32_760, 32_768, 32_776, 65_536];

/// Separations between consecutive members in the dense multi-member strata.
///
/// `0` is flush adjacency — members sharing a block with nothing between them —
/// and `8` is far enough that no partitioner should merge them. `1` and `2` are
/// the two values `general.md:34` and `general.md:35` disagree about.
pub const DENSE_SEPARATIONS: &[usize] = &[0, 1, 2, 3, 5, 8];

/// Member footprint / payload sizes in the dense strata.
pub const DENSE_PAYLOADS: &[usize] = &[1, 2, 4];

/// Member counts the dense **multi-member** strata enumerate.
///
/// Two is the floor because two is the smallest allele: these strata exist to
/// vary how members sit relative to one another — [`Geometry`], separation,
/// payload — and a one-member design has no such relation to vary. It is **not**
/// because one member cannot reach the partitioner. It can:
/// `canonicalize_from_sequence` admits two routes, a multi-member `Cis` allele
/// (`members.len() >= 2`) *and* a single-member `g.`/`m.`/`c.`/`n.`/`r.` variant
/// with a present edit (`is_splittable_single_member`, which is
/// `edit.inner().is_some()`, so `?` is refused). The premise that
/// `members.len() > 1` is the gate was stated here and in five sibling files
/// until #1709; it is false.
///
/// **Single-member rows are therefore in this corpus, just not from these
/// strata.** At `CorpusBounds::default()`, **450** of 12,946 rows carry one
/// member — 402 [`Mechanism::Lone`], 24 [`Mechanism::CompositePayload`] and 24
/// [`Mechanism::RepeatCount`], the last two being single-member shapes that only
/// look otherwise. Of the 450, **404** parse and satisfy
/// `is_splittable_single_member`; the other 46 are [`RowKind::Prohibited`]
/// spellings deliberately malformed enough that no parse succeeds, so they reach
/// nothing.
///
/// The 450 is guarded rather than merely asserted here: `spec_conformance_axis`'s
/// `CorpusShape` pins `rows` at 12,946 and `multi_member_rows` at 12,496, and no
/// row has `members > 1` under a non-combining mechanism, so their difference
/// *is* this figure. The 402/24/24 and 404/46 splits are measurements at those
/// bounds and are not pinned anywhere.
///
/// Four is the ceiling because four is where the bulk corpora run out of
/// evidence entirely — the real-data harvest found seven three-member and three
/// four-member rows in 9.9M.
pub const MEMBER_COUNTS: &[usize] = &[2, 3, 4];

/// The bounds of one corpus. Every pinned number is measured over these, so
/// changing one re-rolls the census.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CorpusBounds {
    /// Reference-sequence seeds. Two cores per seed (an `AT` and an `ACGT`
    /// alphabet). Prefix-stable: a smaller count is a strict prefix of a larger
    /// one, so a reduced run enumerates a strict subset of the full run's cases.
    pub seeds: u32,
    /// Include [`EXTENDED_BLOCK_LADDER`].
    pub extended_scale: bool,
}

impl Default for CorpusBounds {
    fn default() -> Self {
        Self {
            seeds: 1,
            extended_scale: false,
        }
    }
}

// ---------------------------------------------------------------------------
// Row taxonomy
// ---------------------------------------------------------------------------

/// Which properties a row can be asked about.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum RowKind {
    /// Two or more spellings verified to denote one sequence. All four
    /// properties apply.
    Family,
    /// One spelling whose denoted sequence is not recoverable by the corpus's
    /// oracle — an intronic offset, which SPDI cannot express. **Validity and
    /// idempotency only**; confluence and sequence preservation are reported
    /// `VACUOUS` for these rather than silently counted as passes.
    Single,
    /// A description that denotes no single sequence. The property is that the
    /// implementation **refuses** it.
    Conflict,
    /// A description the recommendations prohibit outright — a genomic offset, a
    /// hyphen range, an `X` base, an intronic position on a bare transcript
    /// accession. The property is again that the implementation **refuses** it,
    /// and the row carries the clause and its [`Strength`].
    Prohibited,
}

/// How strongly the recommendations state a prohibition.
///
/// The split exists because "is not allowed" and "can only be used … when" are
/// not the same claim, and this repository's own `CLAUDE.md` records that
/// **uppercase RFC 2119 keywords appear exactly once outside `style.md`** — so
/// keyword strength cannot rank clauses and the wording has to be quoted instead.
/// The axis test pins the two counts separately and asserts on neither: a
/// [`Strength::Conditional`] acceptance is a finding to adjudicate, not a
/// regression to fail.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Strength {
    /// The spec says "is not allowed", "is not correct", "is invalid", or
    /// "MUST NOT" in as many words.
    Absolute,
    /// The spec states a condition or a preference from which a prohibition
    /// follows, without using prohibitive words.
    Conditional,
}

impl Strength {
    /// Stable label, used in censuses.
    #[must_use]
    pub fn label(self) -> &'static str {
        match self {
            Self::Absolute => "absolute",
            Self::Conditional => "conditional",
        }
    }
}

impl fmt::Display for RowKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let text = match self {
            Self::Family => "family",
            Self::Single => "single",
            Self::Conflict => "conflict",
            Self::Prohibited => "prohibited",
        };
        f.write_str(text)
    }
}

/// How a row's members are laid out relative to one another (#1456).
///
/// The first three denote a sequence and produce [`RowKind::Family`] rows; the
/// last four denote none and produce [`RowKind::Conflict`] rows. Before #1456
/// every generated family was [`Geometry::Disjoint`], so a conflicting allele
/// could not exist in the corpus and `0 of 18,432` was reported three times as
/// though it were evidence.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Geometry {
    /// One or more unchanged reference bases between consecutive footprints.
    Disjoint,
    /// Zero unchanged bases between consecutive footprints.
    FlushAdjacent,
    /// A pure insertion at the interbase immediately 5' of another member's
    /// footprint. Legal — the footprints do not intersect — but the two members
    /// share an endpoint, which is where an off-by-one in overlap detection
    /// lives.
    CoincidentEndpoint,
    /// One member's footprint lies strictly inside another's.
    Nested,
    /// Two footprints partially intersect.
    Overlapping,
    /// Two pure insertions at one interbase, whose joint denotation is
    /// undefined because they have no order.
    CoincidentInsertions,
    /// A deletion of a span and a duplication drawn from inside it —
    /// `general.md:58`'s "descriptions removing part of a reference sequence and
    /// replacing it with part of the same sequence are not allowed".
    SelfReplacement,
}

impl Geometry {
    /// Whether a design with this geometry denotes a single sequence.
    #[must_use]
    pub fn denotes_a_sequence(self) -> bool {
        matches!(
            self,
            Self::Disjoint | Self::FlushAdjacent | Self::CoincidentEndpoint
        )
    }

    /// Stable label, used in row ids and censuses.
    #[must_use]
    pub fn label(self) -> &'static str {
        match self {
            Self::Disjoint => "disjoint",
            Self::FlushAdjacent => "flush",
            Self::CoincidentEndpoint => "coincident-endpoint",
            Self::Nested => "nested",
            Self::Overlapping => "overlapping",
            Self::CoincidentInsertions => "coincident-insertions",
            Self::SelfReplacement => "self-replacement",
        }
    }
}

/// The syntactic mechanism a row's members are combined by.
///
/// **Enumerated by mechanism, never by scanning for `[`.** A bracket scan is
/// wrong in both directions, measured over the DNA slice of the recommendations:
/// of 14 bracket-bearing entries only 9 use the allele-membership mechanism —
/// repeat-count `[n]` and composite insertion payload `ins[a;b]` are
/// **single-member** shapes that merely look multi-member — while five genuinely
/// multi-member rules carry no brackets at all, the unknown-phase `(;)` operator
/// (`DNA/alleles.md:20`) among them. Keying on `[` would therefore inflate the
/// multi-member share with single-member shapes *and* leave `(;)` ungenerated
/// while the report showed the axis covered. That is the same blindness class as
/// #1456/#1460/#1478.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Mechanism {
    /// One variant, no combining operator.
    Lone,
    /// `[a;b]` — two or more variants in cis on one allele
    /// (`DNA/alleles.md:16`).
    Cis,
    /// `[a](;)[b]` / `a(;)b` — phase unknown (`DNA/alleles.md:20`).
    UnknownPhase,
    /// `[a];[b]` — in trans, on different chromosomes
    /// (`DNA/alleles.md:17`).
    Trans,
    /// `ins[a;b]` — a composite insertion payload. **Single-member.**
    CompositePayload,
    /// `<span><unit>[n]` — a repeat count. **Single-member.**
    RepeatCount,
}

impl Mechanism {
    /// Whether the mechanism combines two or more *allele members*.
    ///
    /// `false` for [`Self::CompositePayload`] and [`Self::RepeatCount`], which is
    /// the whole point of the type.
    #[must_use]
    pub fn combines_members(self) -> bool {
        matches!(self, Self::Cis | Self::UnknownPhase | Self::Trans)
    }

    /// Stable label, used in row ids and censuses.
    #[must_use]
    pub fn label(self) -> &'static str {
        match self {
            Self::Lone => "lone",
            Self::Cis => "cis",
            Self::UnknownPhase => "unknown-phase",
            Self::Trans => "trans",
            Self::CompositePayload => "composite-payload",
            Self::RepeatCount => "repeat-count",
        }
    }
}

/// Where in a transcript's structure a row sits (#1478).
///
/// Only [`Region::Anywhere`] is meaningful on a genomic axis. The rest are the
/// placements a single-exon `CDS_START = 1` transcript makes structurally
/// impossible.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Region {
    /// Genomic, or a transcript row placed without regard to structure.
    Anywhere,
    /// Wholly inside the 5'UTR — `c.-n` positions.
    Utr5,
    /// Straddling `c.-1` / `c.1`.
    CdsStart,
    /// Interior of the CDS, inside one exon.
    MidCds,
    /// Straddling the exon 1 / exon 2 junction.
    ExonJunction1,
    /// Straddling the exon 2 / exon 3 junction.
    ExonJunction2,
    /// Straddling the last CDS base and the first 3'UTR base.
    CdsEnd,
    /// Wholly inside the 3'UTR — `c.*n` positions.
    Utr3,
    /// An intronic offset position — `c.n+m` / `c.n-m`.
    Intronic,
}

impl Region {
    /// Stable label, used in row ids and censuses.
    #[must_use]
    pub fn label(self) -> &'static str {
        match self {
            Self::Anywhere => "anywhere",
            Self::Utr5 => "utr5",
            Self::CdsStart => "cds-start",
            Self::MidCds => "mid-cds",
            Self::ExonJunction1 => "junction-1",
            Self::ExonJunction2 => "junction-2",
            Self::CdsEnd => "cds-end",
            Self::Utr3 => "utr3",
            Self::Intronic => "intronic",
        }
    }
}

/// Which synthetic reference a row is drawn against.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RefShape {
    /// A padded synthetic contig addressed with `g.`.
    Genomic,
    /// One exon, `CDS_START == 1` — the exact shape #1478 names, retained as the
    /// control so a multi-exon-only divergence is attributable.
    CodingSingleExon,
    /// Three exons with a real 5'UTR, CDS and 3'UTR, on the given strand.
    CodingMultiExon(Strand),
    /// Three exons and no CDS, addressed with `n.`, on the given strand.
    NonCodingMultiExon(Strand),
}

impl RefShape {
    /// Every shape the corpus draws against, in a deterministic order.
    #[must_use]
    pub fn all() -> Vec<Self> {
        vec![
            Self::Genomic,
            Self::CodingSingleExon,
            Self::CodingMultiExon(Strand::Plus),
            Self::CodingMultiExon(Strand::Minus),
            Self::NonCodingMultiExon(Strand::Plus),
            Self::NonCodingMultiExon(Strand::Minus),
        ]
    }

    /// The shapes that carry transcript structure, so a [`Region`] means
    /// something.
    #[must_use]
    pub fn structured() -> Vec<Self> {
        Self::all()
            .into_iter()
            .filter(|shape| !matches!(shape, Self::Genomic))
            .collect()
    }

    /// Stable label, used in row ids and censuses.
    #[must_use]
    pub fn label(self) -> &'static str {
        match self {
            Self::Genomic => "g",
            Self::CodingSingleExon => "c1",
            Self::CodingMultiExon(Strand::Minus) => "c3m",
            Self::CodingMultiExon(_) => "c3p",
            Self::NonCodingMultiExon(Strand::Minus) => "n3m",
            Self::NonCodingMultiExon(_) => "n3p",
        }
    }

    /// The HGVS coordinate prefix.
    #[must_use]
    pub fn prefix(self) -> &'static str {
        match self {
            Self::Genomic => "g",
            Self::CodingSingleExon | Self::CodingMultiExon(_) => "c",
            Self::NonCodingMultiExon(_) => "n",
        }
    }

    /// Whether the shape has more than one exon, so a junction exists.
    #[must_use]
    pub fn is_multi_exon(self) -> bool {
        matches!(self, Self::CodingMultiExon(_) | Self::NonCodingMultiExon(_))
    }
}

/// One corpus row: a synthetic reference, what it denotes, and the spellings.
#[derive(Debug, Clone)]
pub struct Row {
    /// Deterministic identifier, derived from the design parameters. Unique
    /// within a corpus and independent of iteration order, so a failing row can
    /// be named in a committed regression test.
    pub id: String,
    /// Which properties apply.
    pub kind: RowKind,
    /// Which stratum enumerated it.
    pub stratum: &'static str,
    /// The synthetic reference.
    pub shape: RefShape,
    /// The variable part of the reference sequence.
    pub core: String,
    /// The sequence after the design is applied, on the axis's own reference —
    /// the row's ground truth. `None` for [`RowKind::Single`] and
    /// [`RowKind::Conflict`].
    pub denoted: Option<String>,
    /// Distinct spellings. At least two for a [`RowKind::Family`], exactly one
    /// otherwise.
    pub spellings: Vec<String>,
    /// Members in the authored design.
    pub members: usize,
    /// Unchanged reference bases between consecutive members.
    pub separation: usize,
    /// Reference bases the union of the members spans.
    pub block_len: usize,
    /// How the members are combined syntactically. Never inferred from
    /// brackets; see [`Mechanism`].
    pub mechanism: Mechanism,
    /// The clause a [`RowKind::Prohibited`] row cites, and how strongly it is
    /// stated.
    pub prohibition: Option<(&'static str, Strength)>,
    /// Guards this row would catch a violation of: behaviour that would
    /// implement a **rejected** consultation proposal.
    ///
    /// `general.md:36-39` announces a "new recommendation" that "two variants
    /// separated by less than two nucleotides should be described as a
    /// 'delins'". That is SVD-WG010, opened 2021-05-15 and **closed rejected**
    /// 2021-07-31 (`consultation/SVD-WG010.md:5-8`) — the note in the
    /// recommendations is stale and announces a change that did not happen. A
    /// separation floor of two on a **frameless** axis is that rejected proposal,
    /// and ferro has shipped it before: `coalesce_coding_frame_separation`
    /// emitted SVD-WG010's own worked example. So the shape is generated with the
    /// guard attached rather than left to be re-discovered.
    pub negative_guards: Vec<&'static str>,
    /// Whether this row is in the population a **coding-axis** merge across
    /// **two or more** unchanged nucleotides could be observed on. See
    /// [`is_coding_axis_separation_two_or_more_shape`], which carries the
    /// reasoning — including why the floor is two rather than one.
    ///
    /// # An instrument's denominator, not a guard and not a ruling
    ///
    /// [`Self::negative_guards`] marks a row whose merge would implement a
    /// **rejected** proposal, so a violation there is a verdict. This flag marks
    /// a row where a merge is merely *interesting*, and its counter reports how
    /// many such merges happen. It asserts nothing about whether they are right.
    ///
    /// What makes the population worth counting is that `general.md:34` and
    /// `DNA/delins.md:17` speak to it in as many words — "two variants separated
    /// by one or more nucleotides should be described individually and **not**
    /// as a "delins"" — and that three ruling records govern parts of it. Both
    /// halves are on [`is_coding_axis_separation_two_or_more_shape`]; do not
    /// argue from the two clauses without the records.
    ///
    /// # Why it exists as a separate flag
    ///
    /// [`is_svd_wg010_shape`]'s domain and this one's are **disjoint by
    /// construction**: that guard admits only the two frameless shapes
    /// ([`RefShape::Genomic`], [`RefShape::NonCodingMultiExon`]) at a separation
    /// of exactly one with exactly two members, so it cannot count a coding-axis
    /// merge at any separation, for any member count. Widening it would silently
    /// re-scope a guard for a rejected proposal into something else, so this is a
    /// second marker beside it rather than a change to it.
    ///
    /// Set by [`build_family`] alone, so it is a property of family rows;
    /// single, conflicting and prohibited rows carry `false`.
    pub coding_axis_separation_two_or_more: bool,
    /// Member layout (#1456).
    pub geometry: Geometry,
    /// Transcript placement (#1478).
    pub region: Region,
    /// Thresholds this row's block or window straddles (#1460).
    pub scale_bands: Vec<&'static str>,
    /// Rule tags this row exercises. Joined against the committed rule
    /// inventory, which is what turns "we generate a lot" into "we generate
    /// *this clause*".
    pub rules: Vec<&'static str>,
}

impl Row {
    /// The design as authored — the first spelling, by construction of
    /// [`candidate_spellings`], which emits the authored form before any
    /// respelling.
    ///
    /// Load-bearing for the negative guard: the *spanning `delins`* respelling of
    /// a two-member design is itself a single member, so a guard evaluated over
    /// every spelling would report the corpus's own candidate as a merge and
    /// count 575 violations where the question was only ever about what the
    /// normalizer does to the authored pair.
    #[must_use]
    pub fn authored_spelling(&self) -> &str {
        self.spellings
            .first()
            .map_or("", std::string::String::as_str)
    }

    /// Whether the row has more than one authored **allele member**.
    ///
    /// Both halves are required: a composite insertion payload or a repeat count
    /// has one member however many `;`-separated fragments it holds, and a
    /// bracket-free `(;)` row has two however few brackets it holds.
    #[must_use]
    pub fn is_multi_member(&self) -> bool {
        self.members > 1 && self.mechanism.combines_members()
    }

    /// The provider the row's coordinates resolve against, and the sequence they
    /// address.
    ///
    /// Rebuilt from [`Self::core`] and [`Self::shape`] rather than stored, so a
    /// corpus of 14,000 rows does not carry 14,000 copies of a padded contig.
    /// Rows sharing a `(shape, core)` share a provider, which is what makes the
    /// axis test's cost linear in rows rather than in bases.
    #[must_use]
    pub fn frame(&self) -> Frame {
        Frame::build(self.shape, &self.core)
    }

    /// The key rows sharing one provider agree on.
    #[must_use]
    pub fn frame_key(&self) -> (RefShape, &str) {
        (self.shape, self.core.as_str())
    }
}

// ---------------------------------------------------------------------------
// Frames: a synthetic reference, plus the coordinate arithmetic for it
// ---------------------------------------------------------------------------

/// A materialized synthetic reference: the provider, the sequence HGVS
/// coordinates address, and the mapping from an index into that sequence to an
/// HGVS position label.
///
/// The served sequence is the padded contig for a `g.` row and the *transcript*
/// for a `c.`/`n.` row, because that is the frame `hgvs_to_spdi` reports
/// positions in for each axis (0-based, verified by
/// [`tests::spdi_positions_are_zero_based_on_the_served_sequence`]).
#[derive(Clone)]
pub struct Frame {
    shape: RefShape,
    accession: &'static str,
    served: String,
    /// 0-based offset of the core within [`Self::served`].
    core_offset: usize,
    /// 1-based inclusive transcript CDS bounds, for a coding shape.
    cds: Option<(usize, usize)>,
    /// 1-based inclusive transcript bounds of each exon, in transcript order.
    exons: Vec<(usize, usize)>,
    provider: MockProvider,
}

impl Frame {
    /// Build the reference for `shape` over `core`.
    ///
    /// # Panics
    ///
    /// If `core` is shorter than 24 bases, which no stratum generates: the
    /// multi-exon layouts need three non-empty exons plus a 5'UTR and a 3'UTR.
    #[must_use]
    pub fn build(shape: RefShape, core: &str) -> Self {
        assert!(
            core.len() >= 24,
            "a synthetic core must be at least 24 bases, got {}",
            core.len()
        );
        match shape {
            RefShape::Genomic => {
                let served = padded(core);
                let mut provider = MockProvider::new();
                provider.add_genomic_sequence(GENOMIC_CONTIG, served.clone());
                Self {
                    shape,
                    accession: GENOMIC_CONTIG,
                    served,
                    core_offset: PAD_OFFSET,
                    cds: None,
                    exons: Vec::new(),
                    provider,
                }
            }
            RefShape::CodingSingleExon => {
                // The #1478 control: one exon, `CDS_START == 1`, so `c.p` is the
                // core's 1-based position `p` and no row can cross a junction or
                // reach the 5'UTR.
                let cds = (1usize, core.len() - 1);
                let exons = vec![(1usize, core.len())];
                let provider = transcript_provider(
                    CODING_ACCESSION,
                    Strand::Plus,
                    core,
                    Some(cds),
                    &[(1, core.len())],
                );
                Self {
                    shape,
                    accession: CODING_ACCESSION,
                    served: core.to_string(),
                    core_offset: 0,
                    cds: Some(cds),
                    exons,
                    provider,
                }
            }
            RefShape::CodingMultiExon(strand) | RefShape::NonCodingMultiExon(strand) => {
                let exons = three_exon_layout(core.len());
                let coding = matches!(shape, RefShape::CodingMultiExon(_));
                let cds = coding.then(|| cds_layout(core.len()));
                let accession = if coding {
                    CODING_ACCESSION
                } else {
                    NONCODING_ACCESSION
                };
                let provider = transcript_provider(accession, strand, core, cds, &exons);
                Self {
                    shape,
                    accession,
                    served: core.to_string(),
                    core_offset: 0,
                    cds,
                    exons,
                    provider,
                }
            }
        }
    }

    /// The provider.
    #[must_use]
    pub fn provider(&self) -> &MockProvider {
        &self.provider
    }

    /// The sequence the row's HGVS coordinates address.
    #[must_use]
    pub fn served(&self) -> &str {
        &self.served
    }

    /// 0-based offset of the core within [`Self::served`].
    #[must_use]
    pub fn core_offset(&self) -> usize {
        self.core_offset
    }

    /// The accession spellings are written against.
    #[must_use]
    pub fn accession(&self) -> &'static str {
        self.accession
    }

    /// The accession an **intronic** position must be written against:
    /// `NC_SYNTH.1(NM_TEST.1)`.
    ///
    /// `checklist.md:20`'s note makes the genomic wrapper mandatory there — "NM
    /// reference sequences cover mature transcripts and **do not contain** intron
    /// and gene flanking sequences, and can only be used to describe variants in
    /// introns using a `c.` prefix when a genomic reference sequence is given on
    /// which the coding DNA reference sequence is annotated". `None` for a
    /// genomic frame, which has no introns and admits no offsets at all.
    #[must_use]
    pub fn wrapped_accession(&self) -> Option<String> {
        self.shape
            .is_multi_exon()
            .then(|| format!("{TRANSCRIPT_CONTIG}({})", self.accession))
    }

    /// The HGVS position label for a 0-based index into [`Self::served`].
    ///
    /// For a coding shape this is where `-n` / `n` / `*n` is decided, which is
    /// the whole point of [`Region::Utr5`] and [`Region::Utr3`] being reachable
    /// at all.
    #[must_use]
    pub fn label(&self, index: usize) -> String {
        let one_based = index + 1;
        match self.cds {
            None => one_based.to_string(),
            Some((cds_start, cds_end)) => {
                if one_based < cds_start {
                    format!("-{}", cds_start - one_based)
                } else if one_based <= cds_end {
                    (one_based - cds_start + 1).to_string()
                } else {
                    format!("*{}", one_based - cds_end)
                }
            }
        }
    }

    /// An intronic position label: the offset `delta` from the exonic base at
    /// `index`, spelled `+`/`-` per HGVS.
    ///
    /// Returns `None` when the shape has no introns, or when `index` is not an
    /// exon boundary in the direction asked for — an intronic offset is only
    /// meaningful hanging off the last base of an exon (`+`) or the first base of
    /// the next (`-`).
    #[must_use]
    pub fn intronic_label(&self, index: usize, delta: isize) -> Option<String> {
        if !self.shape.is_multi_exon() || delta == 0 {
            return None;
        }
        let one_based = index + 1;
        let boundary_ok = self.exons.iter().any(|&(start, end)| {
            (delta > 0 && one_based == end && end != self.served.len())
                || (delta < 0 && one_based == start && start != 1)
        });
        if !boundary_ok {
            return None;
        }
        let base = self.label(index);
        Some(if delta > 0 {
            format!("{base}+{delta}")
        } else {
            format!("{base}{delta}")
        })
    }

    /// A 0-based served index inside `region`, or `None` when the region does not
    /// exist on this shape.
    ///
    /// `width` is how many bases the design needs from that index onward; a
    /// region too narrow for the design yields `None` rather than a silently
    /// clamped placement.
    #[must_use]
    pub fn region_start(&self, region: Region, width: usize) -> Option<usize> {
        let len = self.served.len();
        let (cds_start, cds_end) = self.cds.unwrap_or((1, len));
        let fits = |start: usize| (start + width <= len).then_some(start);
        match region {
            // Eight bases into the **core**, so a 5'-shifting member has
            // somewhere to travel that is still inside the core.
            //
            // `core_offset` is not decoration: a genomic frame's served sequence
            // begins with 256 bases of period-4 `ACGT` padding, so an offset
            // measured from the served sequence would place every genomic row
            // inside a perfect tandem repeat rather than in the drawn core. That
            // was the first revision's behaviour and it silently turned the whole
            // genomic half of the corpus into a repeat-tract measurement.
            Region::Anywhere | Region::MidCds => {
                let start = if self.shape.is_multi_exon() {
                    let mid = self.exons.get(1).map_or((1, len), |&e| e);
                    mid.0 + 3 - 1
                } else {
                    self.core_offset + 8
                };
                fits(start)
            }
            Region::Utr5 => {
                if cds_start < 4 {
                    return None;
                }
                fits(1).filter(|&start| start + width < cds_start - 1)
            }
            Region::CdsStart => {
                // Straddle `c.-1` / `c.1`: the design's first base is the last
                // 5'UTR base.
                (cds_start >= 2).then_some(())?;
                fits(cds_start.saturating_sub(2))
            }
            Region::ExonJunction1 | Region::ExonJunction2 => {
                let which = if region == Region::ExonJunction1 {
                    0
                } else {
                    1
                };
                let exon = *self.exons.get(which)?;
                // Straddle the junction: start one base before the exon's last
                // base, so a design of width ≥ 2 crosses into the next exon.
                (width >= 2).then_some(())?;
                (exon.1 >= 2).then_some(())?;
                fits(exon.1 - 1)
            }
            Region::CdsEnd => {
                self.cds?;
                (cds_end >= 2).then_some(())?;
                fits(cds_end - 1)
            }
            Region::Utr3 => {
                self.cds?;
                fits(cds_end + 1).filter(|&start| start + width <= len)
            }
            // An intronic row is not placed by served index; see
            // [`Self::intronic_label`].
            Region::Intronic => None,
        }
    }

    /// The exon boundaries, 1-based inclusive transcript coordinates.
    #[must_use]
    pub fn exons(&self) -> &[(usize, usize)] {
        &self.exons
    }

    /// The 1-based inclusive CDS bounds, for a coding shape.
    #[must_use]
    pub fn cds(&self) -> Option<(usize, usize)> {
        self.cds
    }
}

/// Wrap `core` in [`PAD_OFFSET`] bases of period-4 `ACGT` on each side.
#[must_use]
pub fn padded(core: &str) -> String {
    let pad = "ACGT".repeat(PAD_OFFSET / 4);
    format!("{pad}{core}{pad}")
}

/// Three exons over a transcript of `tx_len` bases, 1-based inclusive.
///
/// Proportional rather than fixed so the scale stratum's long cores still get a
/// junction in the middle of the design's reach.
///
/// `pub(crate)` so [`crate::conformance::synthetic_protein`] draws its exon
/// layout from the same function rather than a second copy of the arithmetic.
pub(crate) fn three_exon_layout(tx_len: usize) -> Vec<(usize, usize)> {
    let first = (tx_len / 3).max(8);
    let second = (tx_len / 3).max(8);
    vec![
        (1, first),
        (first + 1, first + second),
        (first + second + 1, tx_len),
    ]
}

/// CDS bounds leaving a real 5'UTR and 3'UTR, 1-based inclusive.
///
/// The 5'UTR is at least 4 bases so `c.-1`..`c.-4` exist, and the 3'UTR at least
/// 4 so `c.*1`..`c.*4` do.
fn cds_layout(tx_len: usize) -> (usize, usize) {
    let utr5 = (tx_len / 8).clamp(4, tx_len / 3);
    let utr3 = (tx_len / 8).clamp(4, tx_len / 3);
    (utr5 + 1, tx_len - utr3)
}

/// Reverse complement, uppercase DNA.
fn reverse_complement(sequence: &str) -> String {
    sequence
        .chars()
        .rev()
        .map(|base| match base.to_ascii_uppercase() {
            'A' => 'T',
            'C' => 'G',
            'G' => 'C',
            'T' => 'A',
            other => other,
        })
        .collect()
}

/// Build a provider holding one synthetic transcript and the contig it sits on.
///
/// The contig interleaves the exon blocks with [`INTRON_LEN`] intronic bases. On
/// the minus strand the exon blocks are reverse-complemented and laid out in
/// reverse exon order, so exon 1 occupies the highest genomic coordinates — the
/// arrangement `tests/it/issue_214_repeat_unit_divides.rs` and
/// `tests/it/coverage_gap_tests.rs` build by hand.
///
/// `pub(crate)` so [`crate::conformance::synthetic_protein`] builds its
/// transcript through this one function: a protein frame whose contig, exon
/// records and strand handling came from a second implementation would not be
/// the same molecule the corpus's `c.` rows are drawn against.
pub(crate) fn transcript_provider(
    accession: &'static str,
    strand: Strand,
    tx: &str,
    cds: Option<(usize, usize)>,
    exons: &[(usize, usize)],
) -> MockProvider {
    let pad = "ACGT".repeat(PAD_OFFSET / 4);
    let intron = "GATTACA".repeat(INTRON_LEN / 7 + 1);
    let intron = &intron[..INTRON_LEN];

    // Exon blocks in genomic order.
    let mut blocks: Vec<String> = exons
        .iter()
        .map(|&(start, end)| tx[start - 1..end].to_string())
        .collect();
    if strand == Strand::Minus {
        blocks = blocks.iter().rev().map(|b| reverse_complement(b)).collect();
    }

    let mut contig = String::with_capacity(2 * PAD_OFFSET + tx.len() + 2 * INTRON_LEN);
    contig.push_str(&pad);
    // 0-based genomic offsets of each block, in genomic order.
    let mut block_starts = Vec::with_capacity(blocks.len());
    for (index, block) in blocks.iter().enumerate() {
        if index > 0 {
            contig.push_str(intron);
        }
        block_starts.push(contig.len());
        contig.push_str(block);
    }
    contig.push_str(&pad);

    // Back to transcript order, and 1-based.
    let mut exon_records = Vec::with_capacity(exons.len());
    for (index, &(tx_start, tx_end)) in exons.iter().enumerate() {
        let genomic_index = if strand == Strand::Minus {
            exons.len() - 1 - index
        } else {
            index
        };
        let g_start = block_starts[genomic_index] as u64 + 1;
        let g_end = g_start + (tx_end - tx_start) as u64;
        let number = u32::try_from(index + 1).unwrap_or(u32::MAX);
        exon_records.push(Exon::with_genomic(
            number,
            tx_start as u64,
            tx_end as u64,
            g_start,
            g_end,
        ));
    }

    let span_start = *block_starts.first().expect("at least one exon") as u64 + 1;
    let span_end = contig.len() as u64 - PAD_OFFSET as u64;
    let transcript = Transcript::new(
        accession.to_string(),
        Some("SYNTH".to_string()),
        strand,
        tx.to_string(),
        cds.map(|(start, _)| start as u64),
        cds.map(|(_, end)| end as u64),
        exon_records,
        Some(TRANSCRIPT_CONTIG.to_string()),
        Some(span_start),
        Some(span_end),
        GenomeBuild::GRCh38,
        ManeStatus::None,
        None,
        None,
    );

    let mut provider = MockProvider::new();
    provider.add_genomic_sequence(TRANSCRIPT_CONTIG, contig);
    provider.add_transcript(transcript);
    provider
}

// ---------------------------------------------------------------------------
// Edit kinds and members
// ---------------------------------------------------------------------------

/// The edit types a member can take.
///
/// `Repeat` is only emitted where the reference genuinely holds a tandem array,
/// which is why it has its own stratum: `hgvs_to_spdi` refuses to expand a
/// repeat whose unit is not spelled out, and refuses a spelled unit that does not
/// match the span, so a repeat member drawn against arbitrary sequence would be
/// dropped rather than measured.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Kind {
    /// `del`.
    Del,
    /// `ins`.
    Ins,
    /// `delins`.
    Delins,
    /// A single-base substitution.
    Sub,
    /// `dup`.
    Dup,
    /// `inv`.
    Inv,
    /// A tandem repeat count, `<span><unit>[<n>]`.
    Repeat,
}

/// The kinds the dense strata pair exhaustively. `Repeat` is excluded; see
/// [`Kind`].
pub const PAIRED_KINDS: &[Kind] = &[
    Kind::Del,
    Kind::Ins,
    Kind::Delins,
    Kind::Sub,
    Kind::Dup,
    Kind::Inv,
];

impl Kind {
    /// Stable label, used in row ids and censuses.
    #[must_use]
    pub fn label(self) -> &'static str {
        match self {
            Self::Del => "del",
            Self::Ins => "ins",
            Self::Delins => "delins",
            Self::Sub => "sub",
            Self::Dup => "dup",
            Self::Inv => "inv",
            Self::Repeat => "repeat",
        }
    }

    /// Reference bases the member occupies for a design of `payload` size.
    fn span(self, payload: usize) -> usize {
        match self {
            Self::Ins => 0,
            Self::Sub => 1,
            Self::Del | Self::Delins | Self::Dup | Self::Inv | Self::Repeat => payload,
        }
    }
}

/// One member of a design, in 0-based served coordinates.
#[derive(Debug, Clone)]
struct Member {
    kind: Kind,
    /// Start of the reference footprint. For [`Kind::Ins`] this is the interbase
    /// the payload goes into and the footprint is empty.
    start: usize,
    /// Reference bases occupied. Zero for [`Kind::Ins`].
    span: usize,
    /// Inserted bases, for the kinds that state them.
    payload: String,
    /// Repeat unit and copy count, for [`Kind::Repeat`].
    repeat: Option<(String, usize)>,
}

/// Deterministic replacement bases that differ from the reference base for base,
/// so a substitution's alt is never its ref and a `delins` is never an identity.
fn payload_bases(served: &str, at: usize, size: usize) -> String {
    let bytes = served.as_bytes();
    (0..size)
        .map(|k| match bytes.get(at + k).copied().unwrap_or(b'A') {
            b'A' => 'C',
            b'C' => 'G',
            b'G' => 'T',
            _ => 'A',
        })
        .collect()
}

// ---------------------------------------------------------------------------
// The ground-truth applier — independent of the normalizer
// ---------------------------------------------------------------------------

/// Each member's `(position, deletion, insertion)` in the served frame, in
/// authored order. `None` when the description does not parse or a member has no
/// SPDI triple.
///
/// The whole corpus rests on this being normalizer-independent: `hgvs_to_spdi`
/// resolves coordinates and reads reference bases, and does not consult the
/// shuffler.
#[must_use]
pub fn triples_of(
    provider: &MockProvider,
    descriptor: &str,
) -> Option<Vec<(usize, String, String)>> {
    let members: Vec<HgvsVariant> = match parse_hgvs(descriptor).ok()? {
        HgvsVariant::Allele(allele) => allele.variants.clone(),
        single => vec![single],
    };
    let mut triples = Vec::with_capacity(members.len());
    for member in &members {
        let triple = hgvs_to_spdi(member, provider).ok()?;
        triples.push((
            usize::try_from(triple.position).ok()?,
            triple.deletion.clone(),
            triple.insertion.clone(),
        ));
    }
    Some(triples)
}

/// Apply `triples` to `reference`, or decline.
///
/// The three rules that make this an oracle rather than a formatter, carried over
/// from `tests/it/common/cis_apply_oracle.rs::apply_reason`:
///
/// - a 3'→5' walk with a `claimed` cursor, so an overlapping description is
///   declined rather than double-spliced;
/// - a longer-deletion-first tie-break, without which a zero-width member flush
///   against a deletion reads as an overlap;
/// - rejection of two pure insertions at one interbase, whose joint denotation is
///   undefined.
#[must_use]
pub fn apply_triples(reference: &str, triples: &[(usize, String, String)]) -> Option<String> {
    let mut ordered: Vec<&(usize, String, String)> = triples.iter().collect();
    ordered.sort_by_key(|t| (std::cmp::Reverse(t.0), std::cmp::Reverse(t.1.len())));
    let bytes = reference.as_bytes();
    let mut edited = bytes.to_vec();
    let mut claimed = reference.len();
    let mut insertion_at: Option<usize> = None;
    for (position, deletion, insertion) in ordered {
        let end = position.checked_add(deletion.len())?;
        if end > reference.len() || end > claimed {
            return None;
        }
        if deletion.is_empty() && insertion_at == Some(*position) {
            return None;
        }
        if !bytes[*position..end].eq_ignore_ascii_case(deletion.as_bytes()) {
            return None;
        }
        edited.splice(*position..end, insertion.bytes());
        if deletion.is_empty() {
            insertion_at = Some(*position);
        }
        claimed = *position;
    }
    String::from_utf8(edited).ok()
}

/// What the oracle can say about `descriptor`.
///
/// The distinction between [`Self::NoSequence`] and [`Self::Inexpressible`] is
/// load-bearing and collapsing it produced a wrong headline once already: an
/// intronic `c.` position has no SPDI triple at all ("SPDI is positional and has
/// no offset notation"), so a single `Option<String>` reported 381 outputs as
/// "denoting no sequence" when the great majority were outputs that had *left the
/// transcript* — a different and separately-citable defect
/// (`general.md:44`, `checklist.md:20`), not two members claiming one territory.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Denotation {
    /// The description denotes this sequence.
    Sequence(String),
    /// `parse_hgvs` rejected it.
    Unparseable,
    /// A member has no SPDI triple on this axis — an intronic offset, or a repeat
    /// whose unit is not spelled. A limit of the instrument, **not** a verdict on
    /// the description. For an output whose input was exonic it does carry
    /// information: the description has left the transcript.
    Inexpressible,
    /// Every member has a triple, but applying them overlaps or is ordered
    /// undefinably, so the description denotes no single sequence.
    NoSequence,
}

/// What `descriptor` denotes on `reference`, with the reason when it denotes
/// nothing.
#[must_use]
pub fn denotation_of(provider: &MockProvider, reference: &str, descriptor: &str) -> Denotation {
    if parse_hgvs(descriptor).is_err() {
        return Denotation::Unparseable;
    }
    let Some(triples) = triples_of(provider, descriptor) else {
        return Denotation::Inexpressible;
    };
    match apply_triples(reference, &triples) {
        Some(sequence) => Denotation::Sequence(sequence),
        None => Denotation::NoSequence,
    }
}

/// The sequence `descriptor` denotes on `reference`, or `None` when it denotes
/// none. A convenience over [`denotation_of`] for callers that only need the
/// yes/no.
#[must_use]
pub fn denoted_by(provider: &MockProvider, reference: &str, descriptor: &str) -> Option<String> {
    match denotation_of(provider, reference, descriptor) {
        Denotation::Sequence(sequence) => Some(sequence),
        _ => None,
    }
}

// ---------------------------------------------------------------------------
// Equivalent placements
// ---------------------------------------------------------------------------

/// The extreme equivalent placements of one member's edit, furthest 5' and
/// furthest 3' of where it is written.
///
/// A placement is equivalent when applying it *alone* yields the sequence the
/// original does alone. Brute force over offsets within [`SHIFT_SEARCH`], for the
/// reason given on that constant. An unambiguous member yields none.
fn equivalent_placements(
    served: &str,
    position: usize,
    deletion: &str,
    insertion: &str,
) -> Vec<(usize, String, String)> {
    let Some(target) = splice(served, position, deletion.len(), insertion) else {
        return Vec::new();
    };
    let mut lowest: Option<(usize, String, String)> = None;
    let mut highest: Option<(usize, String, String)> = None;
    for delta in -SHIFT_SEARCH..=SHIFT_SEARCH {
        if delta == 0 {
            continue;
        }
        let Ok(candidate) = usize::try_from(position as isize + delta) else {
            continue;
        };
        let end = candidate + deletion.len();
        if end > served.len() {
            continue;
        }
        if !target.starts_with(&served[..candidate]) || !target.ends_with(&served[end..]) {
            continue;
        }
        let tail = served.len() - end;
        if target.len() < candidate + tail {
            continue;
        }
        let new_deletion = served[candidate..end].to_string();
        let new_insertion = target[candidate..target.len() - tail].to_string();
        if splice(served, candidate, new_deletion.len(), &new_insertion).as_deref() != Some(&target)
        {
            continue;
        }
        let placement = (candidate, new_deletion, new_insertion);
        if delta < 0 {
            if lowest.is_none() {
                lowest = Some(placement);
            }
        } else {
            highest = Some(placement);
        }
    }
    lowest.into_iter().chain(highest).collect()
}

/// `sequence[..at] + insertion + sequence[at + deleted..]`, or `None` when the
/// span runs off the end.
fn splice(sequence: &str, at: usize, deleted: usize, insertion: &str) -> Option<String> {
    let end = at.checked_add(deleted)?;
    if end > sequence.len() {
        return None;
    }
    Some(format!(
        "{}{insertion}{}",
        &sequence[..at],
        &sequence[end..]
    ))
}

// ---------------------------------------------------------------------------
// Sequences
// ---------------------------------------------------------------------------

/// Deterministic cores, two per seed (an `AT` and an `ACGT` alphabet).
///
/// The same xorshift64 as `tests/it/common/cis_apply_oracle.rs::sweep_sequences`
/// and `examples/dump_normalized_corpus.rs::corpus_sequences`, with the draw
/// length lifted into a parameter. Prefix-stable on both axes: a smaller `seeds`
/// is a strict prefix of a larger one, and a shorter `length` is a strict prefix
/// of each core, because the stream is re-seeded per `(seed, alphabet)` and
/// consumed one base at a time.
///
/// Prefix stability is load-bearing, not cosmetic: it is what makes a reduced
/// run a strict *subset* of a full run's cases, so a zero measured at a prefix
/// cannot be non-zero at the full corpus.
#[must_use]
pub fn corpus_cores(seeds: u32, length: usize) -> Vec<String> {
    let mut cores = Vec::with_capacity(2 * seeds as usize);
    for seed in 0..seeds {
        for alphabet in [b"AT".as_slice(), b"ACGT".as_slice()] {
            let mut state = u64::from(seed).wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1;
            cores.push(
                (0..length)
                    .map(|_| {
                        state ^= state << 13;
                        state ^= state >> 7;
                        state ^= state << 17;
                        alphabet[(state % alphabet.len() as u64) as usize] as char
                    })
                    .collect(),
            );
        }
    }
    cores
}

/// Core length for the dense strata.
///
/// Long enough for four members of payload 4 separated by eight unchanged bases,
/// plus shift room either side, plus a three-exon layout with a 5'UTR and a
/// 3'UTR at each end.
pub const DENSE_CORE_LEN: usize = 96;

/// A core holding a tandem array of `copies` copies of a `unit_len`-base unit,
/// flanked by non-matching sequence so the array's extent is unambiguous.
///
/// The flanks are drawn from a different xorshift stream than the unit, and the
/// unit is rotated so it cannot be a homopolymer for `unit_len > 1`.
#[must_use]
pub fn repeat_core(unit_len: usize, copies: usize, seed: u32) -> Option<(String, String, usize)> {
    if unit_len == 0 || copies < 2 {
        return None;
    }
    let unit: String = "ACGTAC"
        .chars()
        .skip(seed as usize % 3)
        .take(unit_len)
        .collect();
    if unit.len() != unit_len {
        return None;
    }
    // A homopolymer unit of length > 1 is really a shorter unit repeated, which
    // makes the array's unit ambiguous; reject rather than measure it.
    if unit_len > 1
        && unit
            .chars()
            .all(|c| c == unit.chars().next().unwrap_or('A'))
    {
        return None;
    }
    let flank_len = 24usize;
    let flanks = corpus_cores(seed + 7, flank_len * 2);
    let flank = flanks.into_iter().nth(1)?;
    let array = unit.repeat(copies);
    // Break any accidental continuation of the array into the flanks.
    let left: String = flank[..flank_len].to_string();
    let right: String = flank[flank_len..].to_string();
    let core = format!("{left}{array}{right}");
    Some((core, unit, left.len()))
}

// ---------------------------------------------------------------------------
// The corpus
// ---------------------------------------------------------------------------

/// Why a design produced no row.
///
/// Every variant is a *legitimate* outcome of a deliberately-adversarial
/// enumeration, which is precisely why they are counted rather than skipped: a
/// generator whose designs all collapsed into one of these would produce an empty
/// corpus that reads as "nothing to find".
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum DropReason {
    /// The design ran past the end of the reference, or a region was too narrow
    /// for it.
    OutOfRange,
    /// The authored spelling denotes no single sequence, in a stratum that
    /// expected one.
    NoDenotedSequence,
    /// The members cancel out and the design denotes the reference, so every
    /// spelling of it is a family about no variant.
    DenotesTheReference,
    /// Fewer than two spellings survived the ground-truth filter, so confluence
    /// is not decidable.
    Singleton,
    /// An `inv` whose span is its own reverse complement, which denotes nothing.
    PalindromicInversion,
    /// A shape the axis cannot express — an intronic offset where the reference
    /// has no introns, or a region a genomic frame does not have.
    UnavailableOnThisAxis,
    /// A geometry that does not conflict, reached from the conflict stratum.
    ///
    /// Recorded rather than skipped because the alternative was a bare
    /// `_ => continue`, which produced nothing and said nothing. That arm was
    /// unreachable while `GEOMETRIES` listed exactly the four conflicting
    /// geometries — but it is the arm someone hits by adding a fifth to that
    /// list, and the failure it would have produced is the silent one this
    /// module exists to make impossible: a design that vanishes without
    /// appearing in `designs_considered` or `dropped_by_reason`.
    NotAConflictingGeometry,
}

impl DropReason {
    /// Stable label, grouped in the census and in the ledger's `dropped_by_reason`.
    #[must_use]
    pub fn label(self) -> &'static str {
        match self {
            Self::OutOfRange => "out of range",
            Self::NoDenotedSequence => "no denoted sequence",
            Self::DenotesTheReference => "denotes the reference",
            Self::Singleton => "fewer than two spellings",
            Self::PalindromicInversion => "palindromic inversion",
            Self::UnavailableOnThisAxis => "shape unavailable on this axis",
            Self::NotAConflictingGeometry => "not a conflicting geometry",
        }
    }
}

impl fmt::Display for DropReason {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.label())
    }
}

/// One enumerated design: either a row, or the reason it produced none.
///
/// Returned as a `Vec` of these rather than pre-folded so a consumer can route
/// the population through [`CaptureLedger`](crate::conformance::completeness::CaptureLedger)
/// — the *last* fallible step before an artifact is written, per that module's
/// contract.
pub type Attempt = Result<Row, (String, DropReason)>;

/// A corpus, folded from [`enumerate`].
#[derive(Debug, Clone)]
pub struct SpecCorpus {
    /// The bounds it was enumerated over.
    pub bounds: CorpusBounds,
    /// Designs the enumeration proposed, before any filtering.
    pub designs_considered: usize,
    /// Drops, by reason.
    pub drops: BTreeMap<&'static str, usize>,
    /// The rows.
    pub rows: Vec<Row>,
}

impl SpecCorpus {
    /// Fold [`enumerate`]'s attempts.
    #[must_use]
    pub fn from_attempts(bounds: CorpusBounds, attempts: Vec<Attempt>) -> Self {
        let designs_considered = attempts.len();
        let mut drops: BTreeMap<&'static str, usize> = BTreeMap::new();
        let mut rows = Vec::new();
        for attempt in attempts {
            match attempt {
                Ok(row) => rows.push(row),
                Err((_, reason)) => *drops.entry(reason.label()).or_default() += 1,
            }
        }
        rows.sort_by(|a, b| a.id.cmp(&b.id));
        Self {
            bounds,
            designs_considered,
            drops,
            rows,
        }
    }

    /// Rows with more than one authored member — the priority axis.
    #[must_use]
    pub fn multi_member_rows(&self) -> usize {
        self.rows.iter().filter(|row| row.is_multi_member()).count()
    }

    /// Spellings across every row, which is the number of normalizations a
    /// consumer will perform.
    #[must_use]
    pub fn spellings(&self) -> usize {
        self.rows.iter().map(|row| row.spellings.len()).sum()
    }

    /// Rows in the coding-axis merge instrument's population — the denominator
    /// its count is `n of` (see [`Row::coding_axis_separation_two_or_more`]).
    ///
    /// Reported so a consumer can fail as VACUOUS rather than read `0` as a
    /// result: a corpus that stopped generating coding-axis separated designs
    /// would otherwise report no merges and look like a clean bill of health.
    #[must_use]
    pub fn coding_axis_separation_two_or_more_rows(&self) -> usize {
        self.rows
            .iter()
            .filter(|row| row.coding_axis_separation_two_or_more)
            .count()
    }

    /// Rows of each kind.
    #[must_use]
    pub fn by_kind(&self) -> BTreeMap<RowKind, usize> {
        let mut counts = BTreeMap::new();
        for row in &self.rows {
            *counts.entry(row.kind).or_default() += 1;
        }
        counts
    }

    /// Rows per stratum.
    #[must_use]
    pub fn by_stratum(&self) -> BTreeMap<&'static str, usize> {
        let mut counts = BTreeMap::new();
        for row in &self.rows {
            *counts.entry(row.stratum).or_default() += 1;
        }
        counts
    }

    /// Rows per combining mechanism, and how many of each the corpus counts as
    /// genuinely multi-member.
    ///
    /// Reported per mechanism rather than as one share because the two
    /// look-alike mechanisms — [`Mechanism::CompositePayload`] and
    /// [`Mechanism::RepeatCount`] — are exactly what a bracket scan would
    /// miscount, so a reader has to be able to see them separately.
    #[must_use]
    pub fn by_mechanism(&self) -> BTreeMap<&'static str, RuleCoverage> {
        let mut counts: BTreeMap<&'static str, RuleCoverage> = BTreeMap::new();
        for row in &self.rows {
            let entry = counts.entry(row.mechanism.label()).or_default();
            entry.rows += 1;
            if row.is_multi_member() {
                entry.multi_member_rows += 1;
            }
        }
        counts
    }

    /// [`RowKind::Prohibited`] rows per [`Strength`].
    #[must_use]
    pub fn by_prohibition_strength(&self) -> BTreeMap<&'static str, usize> {
        let mut counts = BTreeMap::new();
        for row in &self.rows {
            if let Some((_, strength)) = row.prohibition {
                *counts.entry(strength.label()).or_default() += 1;
            }
        }
        counts
    }

    /// Rows carrying each negative guard.
    #[must_use]
    pub fn by_negative_guard(&self) -> BTreeMap<&'static str, usize> {
        let mut counts = BTreeMap::new();
        for row in &self.rows {
            for guard in &row.negative_guards {
                *counts.entry(*guard).or_default() += 1;
            }
        }
        counts
    }

    /// Rows per member geometry (#1456).
    #[must_use]
    pub fn by_geometry(&self) -> BTreeMap<&'static str, usize> {
        let mut counts = BTreeMap::new();
        for row in &self.rows {
            *counts.entry(row.geometry.label()).or_default() += 1;
        }
        counts
    }

    /// Rows per transcript region (#1478).
    #[must_use]
    pub fn by_region(&self) -> BTreeMap<&'static str, usize> {
        let mut counts = BTreeMap::new();
        for row in &self.rows {
            *counts.entry(row.region.label()).or_default() += 1;
        }
        counts
    }

    /// Rows per reference shape.
    #[must_use]
    pub fn by_shape(&self) -> BTreeMap<&'static str, usize> {
        let mut counts = BTreeMap::new();
        for row in &self.rows {
            *counts.entry(row.shape.label()).or_default() += 1;
        }
        counts
    }

    /// Rows per scale band (#1460). A row with no band crossed is counted under
    /// `below-all`.
    #[must_use]
    pub fn by_scale_band(&self) -> BTreeMap<&'static str, usize> {
        let mut counts = BTreeMap::new();
        for row in &self.rows {
            if row.scale_bands.is_empty() {
                *counts.entry("below-all").or_default() += 1;
            }
            for band in &row.scale_bands {
                *counts.entry(*band).or_default() += 1;
            }
        }
        counts
    }

    /// For each rule tag: how many rows exercise it, and how many of those are
    /// multi-member.
    ///
    /// The second half is the point. A rule only ever exercised on a
    /// single-member row is a gap even though it reads as covered, and
    /// multi-member is where partitioning, separation, ordering, overlap
    /// detection, coalescing and typing interact.
    #[must_use]
    pub fn by_rule(&self) -> BTreeMap<&'static str, RuleCoverage> {
        let mut counts: BTreeMap<&'static str, RuleCoverage> = BTreeMap::new();
        for row in &self.rows {
            for rule in &row.rules {
                let entry = counts.entry(*rule).or_default();
                entry.rows += 1;
                if row.is_multi_member() {
                    entry.multi_member_rows += 1;
                }
            }
        }
        counts
    }
}

/// How thoroughly one rule tag is exercised.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct RuleCoverage {
    /// Rows carrying the tag.
    pub rows: usize,
    /// Of those, rows with more than one authored member.
    pub multi_member_rows: usize,
}

// ---------------------------------------------------------------------------
// Enumeration
// ---------------------------------------------------------------------------

/// Enumerate every design in the declared shape space, deterministically.
///
/// The order is fixed by the loop nesting and does not depend on hashing, so two
/// runs at the same [`CorpusBounds`] produce byte-identical output.
#[must_use]
pub fn enumerate(bounds: &CorpusBounds) -> Vec<Attempt> {
    let mut attempts = Vec::new();
    enumerate_members(bounds, &mut attempts);
    enumerate_regions(bounds, &mut attempts);
    enumerate_scale(bounds, &mut attempts);
    enumerate_repeats(bounds, &mut attempts);
    enumerate_conflicts(bounds, &mut attempts);
    enumerate_intronic(bounds, &mut attempts);
    enumerate_mechanisms(bounds, &mut attempts);
    enumerate_prohibited(bounds, &mut attempts);
    enumerate_ambiguity(bounds, &mut attempts);
    attempts
}

/// Build a corpus at `bounds`.
#[must_use]
pub fn corpus(bounds: &CorpusBounds) -> SpecCorpus {
    SpecCorpus::from_attempts(bounds.clone(), enumerate(bounds))
}

/// The rule tags a design exercises, derived from its shape.
///
/// Kept in one place so the join against the committed rule inventory has a
/// single definition, and so a reviewer can see the whole mapping at once
/// instead of hunting it across six enumerators.
fn rules_for(
    kinds: &[Kind],
    geometry: Geometry,
    separation: usize,
    region: Region,
    shape: RefShape,
    members: usize,
) -> Vec<&'static str> {
    let mut rules = vec!["general.md:40-three-prime-rule"];
    if members > 1 {
        rules.push("general.md:79-allele-semicolon-separator");
        match separation {
            0 => rules.push("DNA/delins.md:17-adjacent-members-merge"),
            1 => {
                rules.push("general.md:33-separation-split");
                rules.push("general.md:34-codon-exception");
            }
            _ => rules.push("general.md:33-separation-split"),
        }
    }
    // Only geometries that denote NO sequence claim `general.md:58`.
    //
    // `CoincidentEndpoint` used to claim it too, on a separate branch above.
    // That was a false coverage claim: the variant's own doc calls it "Legal —
    // the footprints do not intersect", `denotes_a_sequence()` returns true for
    // it, and `:58` prohibits "removing part of a reference sequence and
    // replacing it with part of the same sequence" — which a pure insertion
    // beside another member's footprint does not do. Because rule tags are what
    // the committed inventory joins against, tagging a clause on rows that do
    // not exercise it made coverage of `:58` read as satisfied by rows that
    // demonstrate nothing about it. The flattering direction again.
    //
    // `:58` is still covered: `SelfReplacement` is not in `denotes_a_sequence`,
    // so its rows reach this branch, and those rows ARE the clause's own
    // example shape (`NM_004006.2:c.[762_768del;767_774dup]`).
    if !geometry.denotes_a_sequence() {
        rules.push("general.md:57-no-self-replacement");
        rules.push("checklist.md:6-most-offended");
    }
    for kind in kinds {
        rules.push(match kind {
            Kind::Del => "DNA/deletion.md:5-del-format",
            Kind::Ins => "DNA/insertion.md:5-ins-flanking-format",
            Kind::Delins => "DNA/delins.md:5-delins-format",
            Kind::Sub => "DNA/substitution.md:5-sub-format",
            Kind::Dup => "DNA/duplication.md:5-dup-format",
            Kind::Inv => "DNA/inversion.md:5-inv-format",
            Kind::Repeat => "DNA/repeated.md:5-repeat-format",
        });
    }
    if kinds.contains(&Kind::Dup) && kinds.contains(&Kind::Ins) {
        rules.push("general.md:56-dup-outranks-ins");
    }
    if kinds.contains(&Kind::Inv) {
        rules.push("general.md:55-type-priority");
    }
    match region {
        Region::Utr5 | Region::CdsStart => rules.push("checklist.md:17-cds-numbering-from-atg"),
        Region::Utr3 | Region::CdsEnd => rules.push("checklist.md:17-cds-numbering-from-atg"),
        Region::ExonJunction1 | Region::ExonJunction2 => {
            rules.push("general.md:43-junction-exception");
        }
        Region::Intronic => rules.push("checklist.md:24-intronic-positions-not-exon-numbers"),
        Region::Anywhere | Region::MidCds => {}
    }
    if shape == RefShape::Genomic {
        rules.push("checklist.md:16-genomic-has-no-offsets");
    }
    rules.sort_unstable();
    rules.dedup();
    rules
}

/// Which thresholds a block of `block_len` reference bases and a window of
/// `window` bases straddle (#1460).
fn scale_bands(block_len: usize, window: usize) -> Vec<&'static str> {
    let mut bands = Vec::new();
    for (threshold, label) in [
        (128usize, "canonical-pad-128"),
        (256, "tie-break-sweep-256"),
        (1024, "split-block-1024"),
        (4096, "canonical-window-4096"),
        (32_768, "shift-tract-32768"),
    ] {
        if block_len >= threshold {
            bands.push(label);
        }
    }
    if window >= 4096 {
        bands.push("window-past-canonical-4096");
    }
    bands.sort_unstable();
    bands.dedup();
    bands
}

/// A design resolved against one reference, ready to be turned into a row.
struct Design<'a> {
    id: String,
    stratum: &'static str,
    frame: &'a Frame,
    core: &'a str,
    members: Vec<Member>,
    separation: usize,
    geometry: Geometry,
    region: Region,
    mechanism: Mechanism,
    /// Whether the design's *shape* is the rejected-SVD-WG010 shape. Still
    /// subject to the irreducibility check in [`build_family`]: see
    /// [`negative_guards_for`].
    negative_guard_candidate: bool,
    rules: Vec<&'static str>,
}

/// Lay out `kinds.len()` members from `start`, each separated from the next by
/// `separation` unchanged reference bases.
///
/// Returns the *reason* rather than a bare `None`, because the two reasons are
/// not interchangeable: an earlier revision attributed every failure containing
/// an `inv` to a palindrome, so a corpus with no `inv` rows at all would have
/// looked like a corpus full of palindromes. Misattributed accounting is the same
/// defect as no accounting.
fn layout(
    frame: &Frame,
    start: usize,
    kinds: &[Kind],
    payload: usize,
    separation: usize,
) -> Result<Vec<Member>, DropReason> {
    let served = frame.served();
    let mut members = Vec::with_capacity(kinds.len());
    let mut cursor = start;
    for &kind in kinds {
        let span = kind.span(payload);
        if cursor == 0 {
            // An insertion needs a base 5' of its interbase to name, and a
            // footprint at index 0 has no 5' shift room.
            return Err(DropReason::OutOfRange);
        }
        let highest = if span == 0 { cursor } else { cursor + span - 1 };
        if highest >= served.len() {
            return Err(DropReason::OutOfRange);
        }
        let bases = match kind {
            Kind::Del | Kind::Dup | Kind::Inv | Kind::Repeat => String::new(),
            Kind::Ins | Kind::Delins => payload_bases(served, cursor, payload.max(1)),
            Kind::Sub => payload_bases(served, cursor, 1),
        };
        if kind == Kind::Inv {
            // `inversion.md:5` requires "**more than one nucleotide**", and a
            // span that is its own reverse complement denotes no change at all.
            if span < 2 {
                return Err(DropReason::OutOfRange);
            }
            let span_bases = &served[cursor..cursor + span];
            if reverse_complement(span_bases) == span_bases {
                return Err(DropReason::PalindromicInversion);
            }
        }
        members.push(Member {
            kind,
            start: cursor,
            span,
            payload: bases,
            repeat: None,
        });
        cursor = cursor + span + separation;
    }
    Ok(members)
}

/// Render one member as HGVS, on the frame's axis.
fn render_member(frame: &Frame, member: &Member) -> Option<String> {
    let served = frame.served();
    let label = |index: usize| frame.label(index);
    let last = member.start + member.span.saturating_sub(1);
    Some(match member.kind {
        Kind::Del if member.span == 1 => format!("{}del", label(member.start)),
        Kind::Del => format!("{}_{}del", label(member.start), label(last)),
        Kind::Dup if member.span == 1 => format!("{}dup", label(member.start)),
        Kind::Dup => format!("{}_{}dup", label(member.start), label(last)),
        Kind::Inv => format!("{}_{}inv", label(member.start), label(last)),
        Kind::Sub => format!(
            "{}{}>{}",
            label(member.start),
            &served[member.start..member.start + 1],
            member.payload
        ),
        Kind::Delins if member.span == 1 => {
            format!("{}delins{}", label(member.start), member.payload)
        }
        Kind::Delins => format!(
            "{}_{}delins{}",
            label(member.start),
            label(last),
            member.payload
        ),
        Kind::Ins => format!(
            "{}_{}ins{}",
            label(member.start - 1),
            label(member.start),
            member.payload
        ),
        Kind::Repeat => {
            let (unit, copies) = member.repeat.as_ref()?;
            format!(
                "{}_{}{unit}[{copies}]",
                label(member.start),
                label(member.start + unit.len() - 1)
            )
        }
    })
}

/// `accession:prefix.[m1;m2;…]`, or `accession:prefix.m` for one member.
fn render_allele(frame: &Frame, rendered: &[String]) -> String {
    render_allele_as(
        frame.accession(),
        frame.shape.prefix(),
        Mechanism::Cis,
        rendered,
    )
}

/// Render an allele under a chosen accession and combining mechanism.
///
/// Split out because two shapes need a different accession from the frame's own:
/// the genomic-wrapper form `NC_(NM_):c.…`, which `checklist.md:20` makes
/// mandatory for an intronic position, and the bare form that is the prohibited
/// counterpart of it.
fn render_allele_as(
    accession: &str,
    prefix: &str,
    mechanism: Mechanism,
    rendered: &[String],
) -> String {
    if rendered.len() == 1 {
        return format!("{accession}:{prefix}.{}", rendered[0]);
    }
    match mechanism {
        // `[a];[b]` — different chromosomes (`DNA/alleles.md:17`).
        Mechanism::Trans => format!(
            "{accession}:{prefix}.{}",
            rendered
                .iter()
                .map(|member| format!("[{member}]"))
                .collect::<Vec<_>>()
                .join(";")
        ),
        // `a(;)b` — phase unknown, and `DNA/alleles.md:20` says "i.e. without
        // using `[ ]`" in as many words.
        Mechanism::UnknownPhase => {
            format!("{accession}:{prefix}.{}", rendered.join("(;)"))
        }
        _ => format!("{accession}:{prefix}.[{}]", rendered.join(";")),
    }
}

/// Render an arbitrary `(position, deletion, insertion)` triple in served
/// coordinates, choosing the plainest spelling its shape admits.
fn render_triple(
    frame: &Frame,
    position: usize,
    deletion: &str,
    insertion: &str,
) -> Option<String> {
    let label = |index: usize| frame.label(index);
    match (deletion.is_empty(), insertion.is_empty()) {
        (true, true) => None,
        (true, false) => {
            if position == 0 {
                return None;
            }
            Some(format!(
                "{}_{}ins{insertion}",
                label(position - 1),
                label(position)
            ))
        }
        (false, true) if deletion.len() == 1 => Some(format!("{}del", label(position))),
        (false, true) => Some(format!(
            "{}_{}del",
            label(position),
            label(position + deletion.len() - 1)
        )),
        (false, false) if deletion.len() == 1 => {
            Some(format!("{}delins{insertion}", label(position)))
        }
        (false, false) => Some(format!(
            "{}_{}delins{insertion}",
            label(position),
            label(position + deletion.len() - 1)
        )),
    }
}

/// Every spelling that might denote the design, before the ground-truth filter.
///
/// Six families, which between them are what makes confluence measurable without
/// a published answer:
///
/// 1. the design as authored;
/// 2. the spanning `delins` over the union block, which always exists for a
///    block with reference bases;
/// 3. each member independently moved to either end of its own ambiguous run;
/// 4. the members authored in the opposite order — order-independence is its own
///    property and is the cheapest respelling there is;
/// 5. each member with a footprint of two or more split into two *touching*
///    members, which is a different **partition** of the same variant rather
///    than a different typing of one member;
/// 6. the union block retyped as an `inv` or a `dup` where the alt block admits
///    it, since `general.md:56`'s priority list makes those the preferred forms
///    and a family that cannot reach them cannot measure whether ferro does.
fn candidate_spellings(
    design: &Design<'_>,
    triples: &[(usize, String, String)],
    block: (usize, usize),
    alt_block: &str,
) -> Vec<String> {
    let frame = design.frame;
    let served = frame.served();
    let (lo, hi) = block;
    let Some(rendered) = design
        .members
        .iter()
        .map(|member| render_member(frame, member))
        .collect::<Option<Vec<String>>>()
    else {
        return Vec::new();
    };

    let mut out = vec![render_allele(frame, &rendered)];

    // 2. The spanning form.
    if let Some(spanning) = render_triple(frame, lo, &served[lo..hi], alt_block) {
        out.push(render_allele(frame, std::slice::from_ref(&spanning)));
    }

    // 3. Each member at either end of its own run.
    for (index, triple) in triples.iter().enumerate() {
        for shifted in equivalent_placements(served, triple.0, &triple.1, &triple.2) {
            let Some(text) = render_triple(frame, shifted.0, &shifted.1, &shifted.2) else {
                continue;
            };
            let mut variant = rendered.clone();
            variant[index] = text;
            out.push(render_allele(frame, &variant));
        }
    }

    // 4. The opposite authored order.
    if rendered.len() > 1 {
        let mut reversed = rendered.clone();
        reversed.reverse();
        out.push(render_allele(frame, &reversed));
    }

    // 5. One member re-partitioned into two touching members.
    for (index, triple) in triples.iter().enumerate() {
        let (position, deletion, insertion) = triple;
        if deletion.len() < 2 {
            continue;
        }
        let cut = deletion.len() / 2;
        let insert_cut = insertion.len().min(cut);
        let Some(left) =
            render_triple(frame, *position, &deletion[..cut], &insertion[..insert_cut])
        else {
            continue;
        };
        let Some(right) = render_triple(
            frame,
            position + cut,
            &deletion[cut..],
            &insertion[insert_cut..],
        ) else {
            continue;
        };
        let mut variant = Vec::with_capacity(rendered.len() + 1);
        variant.extend_from_slice(&rendered[..index]);
        variant.push(left);
        variant.push(right);
        variant.extend_from_slice(&rendered[index + 1..]);
        out.push(render_allele(frame, &variant));
    }

    // 6. Retyping the union block.
    let reference_block = &served[lo..hi];
    if !reference_block.is_empty() {
        if alt_block == reverse_complement(reference_block) && reference_block.len() >= 2 {
            let inv = format!("{}_{}inv", frame.label(lo), frame.label(hi - 1));
            out.push(render_allele(frame, std::slice::from_ref(&inv)));
        }
        if alt_block == format!("{reference_block}{reference_block}") {
            let dup = if reference_block.len() == 1 {
                format!("{}dup", frame.label(lo))
            } else {
                format!("{}_{}dup", frame.label(lo), frame.label(hi - 1))
            };
            out.push(render_allele(frame, std::slice::from_ref(&dup)));
        }
    }

    out
}

/// Turn a design into a [`RowKind::Family`] row, or say why it did not.
fn build_family(design: Design<'_>) -> Attempt {
    let frame = design.frame;
    let served = frame.served();
    let rendered: Option<Vec<String>> = design
        .members
        .iter()
        .map(|member| render_member(frame, member))
        .collect();
    let Some(rendered) = rendered else {
        return Err((design.id, DropReason::NoDenotedSequence));
    };
    let authored = render_allele(frame, &rendered);

    let Some(triples) = triples_of(frame.provider(), &authored) else {
        return Err((design.id, DropReason::NoDenotedSequence));
    };
    let Some(denoted) = apply_triples(served, &triples) else {
        return Err((design.id, DropReason::NoDenotedSequence));
    };
    if denoted == served {
        return Err((design.id, DropReason::DenotesTheReference));
    }

    // The union block, in served coordinates.
    let lo = triples.iter().map(|t| t.0).min().unwrap_or(0);
    let hi = triples.iter().map(|t| t.0 + t.1.len()).max().unwrap_or(0);
    if hi > served.len() || lo > hi {
        return Err((design.id, DropReason::NoDenotedSequence));
    }
    let suffix = served.len() - hi;
    if denoted.len() < lo + suffix
        || !denoted.starts_with(&served[..lo])
        || !denoted.ends_with(&served[hi..])
    {
        return Err((design.id, DropReason::NoDenotedSequence));
    }
    let alt_block = denoted[lo..denoted.len() - suffix].to_string();

    let mut spellings = Vec::new();
    let mut seen = std::collections::BTreeSet::new();
    for candidate in candidate_spellings(&design, &triples, (lo, hi), &alt_block) {
        if !seen.insert(candidate.clone()) {
            continue;
        }
        if denoted_by(frame.provider(), served, &candidate).as_deref() == Some(denoted.as_str()) {
            spellings.push(candidate);
        }
    }
    if spellings.len() < 2 {
        return Err((design.id, DropReason::Singleton));
    }

    // Both the negative guard and the coding-axis merge instrument want the same
    // property of the design: that the unchanged bases between the members
    // cannot be shifted away. Two members separated by one `T` inside a `T`-tract
    // are the *same variant* as two adjacent members, so a merge there is the 3'
    // rule rather than a merge across a separation. Computed once and read twice;
    // see `is_svd_wg010_shape`'s "This is only half the test".
    let irreducible = triples
        .iter()
        .all(|t| equivalent_placements(served, t.0, &t.1, &t.2).is_empty());

    // The negative guard survives only when the intervening base is
    // irreducible: see `is_svd_wg010_shape`.
    let negative_guards = if design.negative_guard_candidate && triples.len() == 2 && irreducible {
        vec![SVD_WG010_GUARD]
    } else {
        Vec::new()
    };

    // The coding-axis merge instrument's population. `triples.len()` must equal
    // the member count for `irreducible` to be a statement about every member —
    // a design whose members collapsed into fewer triples has already been
    // re-read by the applier, so its separations are not the authored ones.
    let coding_axis_separation_two_or_more = triples.len() == design.members.len()
        && irreducible
        && is_coding_axis_separation_two_or_more_shape(
            frame.shape,
            &design.members,
            design.separation,
            design.mechanism,
        );

    let window = hi - lo + 2 * 128;
    Ok(Row {
        id: design.id,
        kind: RowKind::Family,
        stratum: design.stratum,
        shape: frame.shape,
        core: design.core.to_string(),
        denoted: Some(denoted),
        spellings,
        members: design.members.len(),
        separation: design.separation,
        block_len: hi - lo,
        mechanism: design.mechanism,
        prohibition: None,
        negative_guards,
        coding_axis_separation_two_or_more,
        geometry: design.geometry,
        region: design.region,
        scale_bands: scale_bands(hi - lo, window),
        rules: design.rules,
    })
}

/// Stratum 1: dense multi-member designs — every ordered pair of edit kinds for
/// two members, and rotations for three and four.
///
/// This is the priority axis and is where the corpus spends most of its cells.
fn enumerate_members(bounds: &CorpusBounds, out: &mut Vec<Attempt>) {
    for (core_index, core) in corpus_cores(bounds.seeds, DENSE_CORE_LEN)
        .into_iter()
        .enumerate()
    {
        for shape in RefShape::all() {
            let frame = Frame::build(shape, &core);
            // Two members: every ordered pair of kinds, exhaustively.
            for &first in PAIRED_KINDS {
                for &second in PAIRED_KINDS {
                    for &payload in DENSE_PAYLOADS {
                        for &separation in DENSE_SEPARATIONS {
                            let geometry = if separation == 0 {
                                Geometry::FlushAdjacent
                            } else {
                                Geometry::Disjoint
                            };
                            let kinds = [first, second];
                            let id = format!(
                                "s{core_index:02}-{}-pair-{}-{}-p{payload}-sep{separation}",
                                shape.label(),
                                first.label(),
                                second.label()
                            );
                            push_design(
                                out,
                                &frame,
                                &core,
                                id,
                                "members-pairs",
                                &kinds,
                                payload,
                                separation,
                                geometry,
                                Region::MidCds,
                            );
                        }
                    }
                }
            }
            // Two members sharing an endpoint: a pure insertion at the interbase
            // immediately 5' of the second member's footprint. Legal, and the
            // shape an off-by-one in overlap detection lives in.
            for &second in PAIRED_KINDS {
                for &payload in DENSE_PAYLOADS {
                    let kinds = [Kind::Ins, second];
                    let id = format!(
                        "s{core_index:02}-{}-endpoint-ins-{}-p{payload}",
                        shape.label(),
                        second.label()
                    );
                    push_design(
                        out,
                        &frame,
                        &core,
                        id,
                        "members-endpoint",
                        &kinds,
                        payload,
                        0,
                        Geometry::CoincidentEndpoint,
                        Region::MidCds,
                    );
                }
            }
            // Three and four members: rotations and uniforms over the paired
            // kinds. The ordered-pair enumeration above does not scale to three
            // members (216 cells per parameter combination), and a rotation
            // still covers every ordered *adjacent* pair.
            for &count in &MEMBER_COUNTS[1..] {
                for pattern in kind_patterns() {
                    for &payload in DENSE_PAYLOADS {
                        for &separation in DENSE_SEPARATIONS {
                            let kinds: Vec<Kind> =
                                (0..count).map(|index| pattern.kind(index)).collect();
                            let geometry = if separation == 0 {
                                Geometry::FlushAdjacent
                            } else {
                                Geometry::Disjoint
                            };
                            let id = format!(
                                "s{core_index:02}-{}-m{count}-{}-p{payload}-sep{separation}",
                                shape.label(),
                                pattern.label()
                            );
                            push_design(
                                out,
                                &frame,
                                &core,
                                id,
                                "members-rotations",
                                &kinds,
                                payload,
                                separation,
                                geometry,
                                Region::MidCds,
                            );
                        }
                    }
                }
            }
        }
    }
}

/// How a design with three or more members assigns edit kinds.
#[derive(Debug, Clone, Copy)]
enum KindPattern {
    /// Member `j` gets `PAIRED_KINDS[(r + j) % 6]`, so over `r` every ordered
    /// adjacent pair of kinds is covered.
    Rotate(usize),
    /// Every member gets the same kind, which is what a systematic design
    /// walking one window actually looks like.
    Uniform(Kind),
}

impl KindPattern {
    fn kind(self, member: usize) -> Kind {
        match self {
            Self::Rotate(r) => PAIRED_KINDS[(r + member) % PAIRED_KINDS.len()],
            Self::Uniform(kind) => kind,
        }
    }

    fn label(self) -> String {
        match self {
            Self::Rotate(r) => format!("rot{r}"),
            Self::Uniform(kind) => format!("all-{}", kind.label()),
        }
    }
}

fn kind_patterns() -> Vec<KindPattern> {
    let mut patterns: Vec<KindPattern> = (0..PAIRED_KINDS.len()).map(KindPattern::Rotate).collect();
    patterns.extend(PAIRED_KINDS.iter().copied().map(KindPattern::Uniform));
    patterns
}

/// Lay a design out and push the resulting attempt.
#[allow(clippy::too_many_arguments)]
fn push_design(
    out: &mut Vec<Attempt>,
    frame: &Frame,
    core: &str,
    id: String,
    stratum: &'static str,
    kinds: &[Kind],
    payload: usize,
    separation: usize,
    geometry: Geometry,
    region: Region,
) {
    let width: usize = kinds
        .iter()
        .map(|kind| kind.span(payload) + separation)
        .sum::<usize>()
        + 2;
    let Some(start) = frame.region_start(region, width) else {
        out.push(Err((id, DropReason::UnavailableOnThisAxis)));
        return;
    };
    let members = match layout(frame, start, kinds, payload, separation) {
        Ok(members) => members,
        Err(reason) => {
            out.push(Err((id, reason)));
            return;
        }
    };
    let mut rules = rules_for(
        kinds,
        geometry,
        separation,
        region,
        frame.shape,
        kinds.len(),
    );
    let mechanism = if kinds.len() > 1 {
        Mechanism::Cis
    } else {
        Mechanism::Lone
    };
    let negative_guard_candidate = is_svd_wg010_shape(frame.shape, kinds, separation);
    if negative_guard_candidate {
        rules.push("rejected:svd-wg010-frameless-floor-two");
        rules.sort_unstable();
        rules.dedup();
    }
    out.push(build_family(Design {
        id,
        stratum,
        frame,
        core,
        members,
        separation,
        geometry,
        region,
        mechanism,
        negative_guard_candidate,
        rules,
    }));
}

/// The one negative guard: the rejected-SVD-WG010 shape.
///
/// A design on a **frameless** axis (`g.`, or `n.` on a non-coding transcript)
/// whose two members each consume reference and sit exactly one unchanged base
/// apart. `general.md:34` says such a pair "should be described individually and
/// **not** as a 'delins'"; merging it is rejected SVD-WG010
/// (`consultation/SVD-WG010.md:8`, "The proposal has been **rejected**"), whose
/// stated ground was that needing to know "whether the two variants are in a
/// coding sequence and affecting one amino acid" is undesirable — the condition
/// `general.md:35` actually imposes.
///
/// `general.md:35`'s codon exception cannot reach a frameless axis at all, since
/// it is conditioned on "together affecting one amino acid". So a merge here is
/// not the exception applied broadly; it is the rejected proposal.
///
/// # This is only half the test — the other half is irreducibility
///
/// A separation of one is not necessarily a separation of one. Inside a run, both
/// members can shift, and two deletions separated by one `T` in a `T`-tract are
/// the *same variant* as two adjacent deletions — merging them is the 3' rule,
/// not SVD-WG010. The first revision of this guard reported 575 violations,
/// almost all of that shape. [`build_family`] therefore keeps the guard only when
/// **neither** member has any equivalent placement, i.e. the intervening base
/// cannot be shifted away. Conservative on purpose: a false negative here costs
/// coverage, a false positive costs a wrong published number.
fn is_svd_wg010_shape(shape: RefShape, kinds: &[Kind], separation: usize) -> bool {
    let frameless = matches!(shape, RefShape::Genomic | RefShape::NonCodingMultiExon(_));
    let all_consume_reference = kinds.iter().all(|kind| *kind != Kind::Ins);
    frameless && separation == 1 && kinds.len() == 2 && all_consume_reference
}

/// The guard label a design earns once irreducibility is confirmed.
const SVD_WG010_GUARD: &str = "svd-wg010-frameless-separation-floor-of-two";

/// The coding-axis merge instrument's population: a **coding** multi-member cis
/// design whose members each consume reference and sit **two or more** unchanged
/// nucleotides apart.
///
/// # This doc comment is the single authoritative statement of the argument
///
/// `Census::coding_axis_separation_two_or_more_merges` and
/// `spec_conformance_axis`'s module docs point **here** rather than restating
/// any of what follows. An earlier revision of this change carried the
/// floor-of-two rationale in seven places and the sub-floor figure in three, and
/// two of those copies had already drifted into contradicting each other 406
/// lines apart inside one file — the repository `CLAUDE.md` names that as this
/// project's recurring failure mode, and it had happened within a single change.
///
/// # This is an instrument, not a holding — and read the ledger before it
///
/// It says which rows are worth *counting a merge on*. It does not say a merge
/// there is wrong. What makes the population interesting is that a clause speaks
/// to it in as many words: `general.md:34` and `DNA/delins.md:17`, "two variants
/// separated by one or more nucleotides should be described individually and
/// **not** as a "delins"".
///
/// **Those two clauses are not the whole authority over this population**, and
/// citing them alone is the mistake the repository `CLAUDE.md` warns about
/// first: do not adjudicate from spec text before reading the ruling ledger.
/// `tests/it/clause_ruling_index.rs` marks both clauses `[MULTI]`, and three
/// records in `tests/fixtures/grammar/hgvs_spec_normalization_overrides.json`
/// govern parts of exactly these rows:
///
/// - the `delins-payload-coincidence-carve-out-is-coding-dna-scoped` ruling is
///   **decided**: `delins.md:47`'s payload-coincidence carve-out is scoped to the
///   **coding DNA axis** — this population's axis, and the one axis on which
///   `general.md:34` is overridden for that shape.
/// - the `delins-merge-vs-individual-gap-two-or-more` ruling is **decided** and
///   scoped twice: to the alignment-coincidence shape `:44-47` describes, and
///   (2026-08-11) to the **net-deletion** direction. Outside that shape
///   `general.md:34` still governs.
/// - the `delins-recommendation-reach-when-the-input-arrives-split` ruling is
///   the genuinely unsettled residue — which clause a *re-derivation* lands on.
///   It is narrower than "may ferro merge an authored split", which
///   `canonical-form-choice-when-both-legal` already answers.
///
/// **So neither a rise nor a given value means one thing.** Within the
/// payload-coincidence subclass the first record *ratifies* the merge on this
/// axis, so a rise there is a decided ruling arriving on the shipped rule, and
/// the shipping arm's original `0` was that ruling **not yet implemented**
/// rather than a clean bill. That figure is no longer zero: **#1835 took it to
/// 3**, pinned on `spec_conformance_axis::THREE_PRIME` with its three rows named
/// and adjudicated individually there. The operator ruling of 2026-08-13 —
/// `coding-axis-merges-are-a-disclosed-general-34-deviation` — holds a merge of
/// this shape to be a disclosed `general.md:34` deviation rather than the
/// ratified one whenever no member of it is gap-bearing. Read that record before
/// reading anything into the number. Outside that shape `general.md:34` governs
/// and a rise is a population that needs explaining. The counter cannot separate them, which is
/// precisely why it counts and does not adjudicate. The sharpest illustration is
/// that the pass producing every merge this counter sees on the
/// `canonical-coalesced` arm, `merge::coalesce_payload_alignment_split`, cites
/// the first of those records in its own doc comment.
///
/// # Why the floor is TWO, which is the conjunct that keeps this honest
///
/// `general.md:35` and `DNA/delins.md:18` carve out an exception on this very
/// axis — two variants "separated by **one** nucleotide, together affecting one
/// amino acid", which needs a reading frame and so can be met **only** here.
/// Measured on the shipping rule at `origin/main` `e98fa77e`: **41 of 340** rows
/// separated by exactly one merge, and **0 of 997** at two or more. (Both were
/// first derived at `1ea75334` and re-derived unchanged after the rebase;
/// `git diff 1ea75334 origin/main -- src/` is empty, so no figure on this axis
/// could have moved between the two.) **Both figures predate #1835's default
/// flip. The second is now 3 of 997, pinned on
/// `spec_conformance_axis::THREE_PRIME`, and this branch leaves it there — the
/// whole census is asserted equal to that pin.** The floor-of-two argument below
/// is unaffected either way: it turns on which rows the exception's own conjunct
/// can reach, not on how many of them merge.
///
/// A floor of one would therefore have to open at a non-zero pin, summing rows
/// with three different verdicts into one figure no later reader could take
/// apart. The floor of two is read straight off the exception's own stated
/// conjunct ("separated by one nucleotide"), which is a textual scope rather
/// than a ruling: at two or more the exception cannot reach, whatever anyone
/// decides about how it applies at one.
///
/// ## What the sub-floor 41 are, and why the number moved from 16
///
/// The 41 decompose by how far each row collapsed, measured directly rather than
/// argued — the finding line reports `<authored> members -> <observed>`:
///
/// | shape | rows | seen by the old `< 2` numerator? |
/// |---|---:|---|
/// | 2 authored members -> 1 | 15 | yes |
/// | 3 authored members -> 1 (a whole-span `inv`, `s00-c1-m3-all-inv-p4-sep1`) | 1 | yes |
/// | 4 authored members -> 3 (a **partial** merge) | 25 | **no** |
///
/// So the earlier figure of **16** is the first two rows of that table and is
/// **unchanged** — #1698 moved it not at all. The other 25 are merges the
/// instrument's original numerator could not represent; see
/// `spec_conformance_axis::coding_axis_merge_observed`, which is why it now tests
/// `< row.members` rather than `< 2`. Read "16 -> 41" as an instrument that got
/// less blind, not as behaviour that changed.
///
/// ## The 16 are not the codon exception firing — an earlier revision said so
///
/// This comment used to read "Ferro implements it, and it fires", which treated
/// all 16 as the licensed shape. Knocking out each merge pass singly shows
/// `apply_coding_codon_exception` produces **none** of them: they come from the
/// per-member codon-frame merge in `merge_consecutive_edits` (`merge.rs:188`,
/// from #79/#275) and one from `coalesce_whole_block_inversion` — which is the
/// 15 / 1 split the table above measures independently. The verdicts are
/// **9 licensed / 5 unlicensed / 2 filed as #1716**:
///
/// | verdict | rows | what they are |
/// |---|---:|---|
/// | licensed | 9 | two lone substitutions in one codon, net length 0 — the exception's own shape; plus one whole-span `inv` |
/// | **unlicensed** | **5** | a frameshift *inside* one codon; filed as **#1744**, see below |
/// | **unlicensed, filed** | **2** | the merged span crosses two codons, so the exception's second conjunct fails under every reading of it — issue **#1716**, reproducing on the prepared reference as `LRG_199t1:c.[18_19del;21A>C]` -> `c.18_21delinsTC` |
///
/// ### None of the 7 is a rule 1 violation — corrected on the rebase
///
/// The last row read "**rule 1 violation**" until this change was rebased onto
/// `origin/main` `e98fa77e`, which carries #1725's
/// `separation-rule-force-modal-or-negation`. That record is **decided**
/// (operator ruling 2026-08-12) and grades `general.md:34` — the clause these
/// rows fall back to once `general.md:35`'s exception declines — as README
/// **rule 2** in its entirety: "'and not Y' names the excluded alternative; it
/// does not grade the clause. The modal grades the clause." So an output
/// merging across unchanged nucleotides where the exception cannot reach is a
/// deviation to **disclose and pin with a tripwire**, not the rule-7 bug a rule
/// 1 violation would be, and it does not by itself block a release.
///
/// What the record does *not* license is re-pinning such a counter to zero for
/// a green build — in its own words, "the one move this record forbids". This
/// counter is pinned at its measured value on a population that sits **above**
/// these rows — 8 since #1616, disclosed by
/// `coding-axis-merges-are-a-disclosed-general-34-deviation` under exactly that
/// rule-2 remedy — so nothing here is being pinned away; the 7 are named
/// precisely because they are below its floor and it cannot see them.
///
/// ## The 5 were filed under a status word, and the record answers them
///
/// A previous revision filed those 5 as unresolved, on the strength of the
/// `codon-carve-out-shape-restriction` ruling — which is **decided** (WIDEN,
/// operator ruling 2026-08-10), and which settles this very sub-case rather than
/// leaving it. Two different claims were being run together: what is *not yet
/// implemented* is the widening's effect on `apply_coding_codon_exception`; what
/// is *not* unsettled is whether the exception reaches a frameshift pair. It does
/// not. The record's own words are that "together affecting one amino acid"
/// cannot cover a frameshift pair, "so the widened rule declines there for the
/// reason the spec gives rather than by a shape test".
///
/// Ferro merges those 5 anyway. They are therefore in the same category as the 2
/// filed as #1716 — output no cited clause licenses — and on this corpus the
/// **sub-floor count of unlicensed merges is 7, not 2**. Under
/// `separation-rule-force-modal-or-negation` all 7 are rule-2 deviations to
/// disclose rather than rule-7 bugs. That changes what they cost a release; it
/// does **not** settle whether they should be accepted-and-disclosed or closed,
/// which is a rule-2 trade nobody has made and which #1744 holds open. Do not
/// read the word "unlicensed" here as that verdict — it says only that no cited
/// clause licenses the merge. Note the 9 / 5 / 2 decomposition is over the 16
/// full collapses only; the 25 partial merges are unclassified, so 7 is a floor
/// on that floor.
///
/// ### What of that is RECORDED, and what is only written here
///
/// The repository policy is that an adjudication lands in a committed test or
/// ruling record in the same change, so be exact about which this is. The
/// *authority* is already committed and decided — `codon-carve-out-shape-restriction`
/// for the reach of the exception and `separation-rule-force-modal-or-negation`
/// for the force of the clause it falls back to, each with its own clauses and
/// quotes — and the 2 cross-codon rows already have their artifact in **#1716**.
/// What is written here and **nowhere else** is the application of those
/// records to the 5 frameshift rows.
///
/// That is deliberately not turned into a new ruling record: no clause conflict
/// is being adjudicated, the governing record already exists, and a second
/// record restating a decided one is how this ledger has drifted before. It is
/// also not turned into a pinned regression test, because this instrument does
/// not identify those rows individually — they sit **below its floor** by
/// construction, so it can count them only by moving the floor, which is the one
/// thing the floor exists to prevent. **The artifact for the 5 is an issue,
/// filed the way #1716 was for the 2: #1744.** That is what carries the rows,
/// the measurement and the open classification question out of this comment;
/// read it rather than this paragraph for their current status, because a
/// comment is the one place a status cannot be updated from.
///
/// The cost, stated rather than hidden: a coding-axis merge at separation
/// **one** is invisible to this counter, and `is_svd_wg010_shape` does not cover
/// it either (that guard is frameless-only). **That gap conceals known defects**,
/// not merely an unsettled question. Closing it properly means fixing #1716,
/// implementing the widening the ruling above decided, and only then deciding
/// what remains — the last of which is an adjudication an instrument must not
/// make, which is why the gap is disclosed here rather than papered over with a
/// wider predicate.
///
/// # Why the domain is stated positively rather than as "not frameless"
///
/// [`is_svd_wg010_shape`] admits `Genomic | NonCodingMultiExon` only, at a
/// separation of exactly one, with exactly two members. This admits
/// `CodingSingleExon | CodingMultiExon` only, at two or more, with two or more
/// members. The two are disjoint twice over and are meant to stay that way — the
/// guard is a negative result about a **rejected** proposal, and relaxing its
/// `frameless` conjunct to make it count coding rows would silently turn it into
/// a different instrument carrying the guard's name and its published zero.
///
/// # The conjuncts
///
/// - **Coding shape.** The `c.` axis.
/// - **`separation >= 2`.** See above. A separation of zero is adjacency, ruled
///   on separately (`delins-adjacent-members-when-both-consume-reference`),
///   where merging is required rather than interesting.
/// - **Two or more members**, combined as allele members — a composite payload
///   or a repeat count is one member however it is spelled.
/// - **[`Mechanism::Cis`] exactly**, not the wider `combines_members()` set. Both
///   are true of every row the generator builds today (probe:
///   `by_mechanism = {cis: 997}`), so this is future-proofing rather than a
///   filter that currently removes anything — but `combines_members()` also
///   admits `Trans` and `UnknownPhase`, and a merged *trans* allele has its
///   members on different chromosomes. That is an unambiguous defect, not a
///   population worth counting under prose calling the adjudication unsettled,
///   so it must not arrive silently through this predicate.
/// - **Every member consumes reference.** A pure insertion has no footprint of
///   its own, so "the unchanged bases between the members" is not well defined
///   for it; the same conjunct, for the same reason, scopes the sibling guard.
///
/// Irreducibility is the sixth conjunct and is checked in [`build_family`],
/// which is the only place the served sequence is available.
fn is_coding_axis_separation_two_or_more_shape(
    shape: RefShape,
    members: &[Member],
    separation: usize,
    mechanism: Mechanism,
) -> bool {
    let coding = matches!(
        shape,
        RefShape::CodingSingleExon | RefShape::CodingMultiExon(_)
    );
    let all_consume_reference = members.iter().all(|member| member.kind != Kind::Ins);
    coding
        && separation >= 2
        && members.len() >= 2
        && matches!(mechanism, Mechanism::Cis)
        && all_consume_reference
}

/// Stratum 2: transcript geometry (#1478) — the placements a single-exon
/// `CDS_START = 1` transcript makes structurally impossible.
fn enumerate_regions(bounds: &CorpusBounds, out: &mut Vec<Attempt>) {
    const REGIONS: &[Region] = &[
        Region::Utr5,
        Region::CdsStart,
        Region::MidCds,
        Region::ExonJunction1,
        Region::ExonJunction2,
        Region::CdsEnd,
        Region::Utr3,
    ];
    const PAIRS: &[[Kind; 2]] = &[
        [Kind::Del, Kind::Del],
        [Kind::Del, Kind::Ins],
        [Kind::Dup, Kind::Dup],
        [Kind::Sub, Kind::Sub],
        [Kind::Delins, Kind::Del],
    ];
    for (core_index, core) in corpus_cores(bounds.seeds, DENSE_CORE_LEN)
        .into_iter()
        .enumerate()
    {
        for shape in RefShape::structured() {
            let frame = Frame::build(shape, &core);
            for &region in REGIONS {
                for kinds in PAIRS {
                    for &payload in &[1usize, 2] {
                        for &separation in &[0usize, 1, 2] {
                            let geometry = if separation == 0 {
                                Geometry::FlushAdjacent
                            } else {
                                Geometry::Disjoint
                            };
                            let id = format!(
                                "s{core_index:02}-{}-{}-{}-{}-p{payload}-sep{separation}",
                                shape.label(),
                                region.label(),
                                kinds[0].label(),
                                kinds[1].label()
                            );
                            push_design(
                                out, &frame, &core, id, "regions", kinds, payload, separation,
                                geometry, region,
                            );
                        }
                    }
                }
            }
        }
    }
}

/// Stratum 3: scale (#1460) — block lengths and separations that straddle every
/// threshold the canonicalizer keys on.
///
/// Enumerated one ladder at a time against a fixed spine rather than as a cross
/// product: the two ladders are 16 and 15 values, and the 4096-base cells are
/// measured at ~35-77 ms per normalization, so a cross product would make the
/// corpus's runtime a property of a few hundred cells.
fn enumerate_scale(bounds: &CorpusBounds, out: &mut Vec<Attempt>) {
    const PATTERNS: &[[Kind; 2]] = &[
        [Kind::Del, Kind::Del],
        [Kind::Inv, Kind::Del],
        [Kind::Delins, Kind::Del],
    ];
    let mut blocks: Vec<usize> = BLOCK_LADDER.to_vec();
    if bounds.extended_scale {
        blocks.extend_from_slice(EXTENDED_BLOCK_LADDER);
    }

    for shape in [RefShape::Genomic, RefShape::CodingMultiExon(Strand::Plus)] {
        // Block ladder at a fixed separation of 1 — the value `general.md:34`
        // and `general.md:35` disagree about, so every cell is also a
        // separation-rule cell.
        for &payload in &blocks {
            let core_len = payload * 3 + 128;
            let core = corpus_cores(1, core_len).into_iter().next_back();
            let Some(core) = core else { continue };
            let frame = Frame::build(shape, &core);
            for kinds in PATTERNS {
                let id = format!(
                    "scale-{}-block{payload}-{}-{}",
                    shape.label(),
                    kinds[0].label(),
                    kinds[1].label()
                );
                push_design(
                    out,
                    &frame,
                    &core,
                    id,
                    "scale-block",
                    kinds,
                    payload,
                    1,
                    Geometry::Disjoint,
                    Region::MidCds,
                );
            }
        }
        // Separation ladder at a fixed payload of 2 — separation drives the
        // canonicalizer's *window*, which is bounded separately from the block.
        for &separation in SEPARATION_LADDER {
            let core_len = separation * 2 + 256;
            let core = corpus_cores(1, core_len).into_iter().next_back();
            let Some(core) = core else { continue };
            let frame = Frame::build(shape, &core);
            for kinds in PATTERNS {
                let id = format!(
                    "scale-{}-sep{separation}-{}-{}",
                    shape.label(),
                    kinds[0].label(),
                    kinds[1].label()
                );
                push_design(
                    out,
                    &frame,
                    &core,
                    id,
                    "scale-separation",
                    kinds,
                    2,
                    separation,
                    Geometry::Disjoint,
                    Region::MidCds,
                );
            }
        }
    }
}

/// Stratum 4: tandem repeats, over cores engineered to hold a real array.
///
/// Separate from the dense strata because `hgvs_to_spdi` refuses a repeat whose
/// unit is not spelled out, and refuses a spelled unit that does not match the
/// span — so a repeat member drawn against arbitrary sequence is dropped rather
/// than measured, and a stratum that mixed the two would report a repeat
/// coverage it does not have.
fn enumerate_repeats(bounds: &CorpusBounds, out: &mut Vec<Attempt>) {
    for seed in 0..bounds.seeds.max(1) {
        for unit_len in [1usize, 2, 3, 4] {
            for copies in [3usize, 5, 8] {
                let Some((core, unit, array_start)) = repeat_core(unit_len, copies, seed) else {
                    continue;
                };
                for shape in [RefShape::Genomic, RefShape::CodingMultiExon(Strand::Plus)] {
                    let frame = Frame::build(shape, &core);
                    let offset = frame.core_offset() + array_start;
                    for new_copies in [copies + 1, copies.saturating_sub(1)] {
                        if new_copies < 2 || new_copies == copies {
                            continue;
                        }
                        let id = format!(
                            "repeat-{}-u{unit_len}-c{copies}-to{new_copies}-s{seed}",
                            shape.label()
                        );
                        let member = Member {
                            kind: Kind::Repeat,
                            start: offset,
                            span: unit_len * copies,
                            payload: String::new(),
                            repeat: Some((unit.clone(), new_copies)),
                        };
                        // A second, disjoint member 3' of the array, so the row
                        // is multi-member: the repeat/sibling interaction is
                        // where the tract logic swallowed a sibling.
                        let sibling_start = offset + unit_len * copies + 2;
                        if sibling_start + 1 >= frame.served().len() {
                            out.push(Err((id, DropReason::OutOfRange)));
                            continue;
                        }
                        let sibling = Member {
                            kind: Kind::Del,
                            start: sibling_start,
                            span: 1,
                            payload: String::new(),
                            repeat: None,
                        };
                        let rules = rules_for(
                            &[Kind::Repeat, Kind::Del],
                            Geometry::Disjoint,
                            2,
                            Region::MidCds,
                            shape,
                            2,
                        );
                        out.push(build_family(Design {
                            id,
                            stratum: "repeats",
                            frame: &frame,
                            core: &core,
                            members: vec![member, sibling],
                            separation: 2,
                            geometry: Geometry::Disjoint,
                            region: Region::MidCds,
                            mechanism: Mechanism::Cis,
                            negative_guard_candidate: false,
                            rules,
                        }));
                    }
                }
            }
        }
    }
}

/// Stratum 5: conflicting alleles (#1456) — descriptions that denote no single
/// sequence, whose property is that they are **refused**.
///
/// Before #1456 the designed corpus could not build one of these at all, so
/// three separate changes reported `0 of 18,432` as though it were evidence of
/// neutrality.
fn enumerate_conflicts(bounds: &CorpusBounds, out: &mut Vec<Attempt>) {
    const GEOMETRIES: &[Geometry] = &[
        Geometry::Nested,
        Geometry::Overlapping,
        Geometry::CoincidentInsertions,
        Geometry::SelfReplacement,
    ];
    for (core_index, core) in corpus_cores(bounds.seeds, DENSE_CORE_LEN)
        .into_iter()
        .enumerate()
    {
        for shape in RefShape::all() {
            let frame = Frame::build(shape, &core);
            for &geometry in GEOMETRIES {
                for &payload in &[2usize, 4] {
                    let id = format!(
                        "conflict-s{core_index:02}-{}-{}-p{payload}",
                        shape.label(),
                        geometry.label()
                    );
                    let width = payload * 3 + 4;
                    let Some(start) = frame.region_start(Region::MidCds, width) else {
                        out.push(Err((id, DropReason::UnavailableOnThisAxis)));
                        continue;
                    };
                    let members = match geometry {
                        // A wide member with a narrower one strictly inside it.
                        Geometry::Nested => vec![
                            simple_member(Kind::Del, start, payload * 2),
                            simple_member(Kind::Del, start + 1, payload.max(1)),
                        ],
                        // Footprints that partially intersect.
                        Geometry::Overlapping => vec![
                            simple_member(Kind::Del, start, payload * 2),
                            simple_member(Kind::Del, start + payload, payload * 2),
                        ],
                        // Two pure insertions at one interbase have no order.
                        Geometry::CoincidentInsertions => vec![
                            Member {
                                kind: Kind::Ins,
                                start,
                                span: 0,
                                payload: payload_bases(frame.served(), start, payload),
                                repeat: None,
                            },
                            Member {
                                kind: Kind::Ins,
                                start,
                                span: 0,
                                payload: payload_bases(frame.served(), start + 1, payload),
                                repeat: None,
                            },
                        ],
                        // `general.md:58`: a description that removes part of the
                        // reference and replaces it with part of the same
                        // sequence. The spec's own example is
                        // `NM_004006.2:c.[762_768del;767_774dup]`.
                        Geometry::SelfReplacement => vec![
                            simple_member(Kind::Del, start, payload * 2),
                            simple_member(Kind::Dup, start + payload, payload * 2),
                        ],
                        // Named rather than left to a `_` arm, so this match is
                        // EXHAUSTIVE over `Geometry`. Two failure modes close
                        // together: adding a fifth entry to `GEOMETRIES` now
                        // records a drop instead of producing nothing silently,
                        // and adding a variant to `Geometry` itself stops
                        // compiling here instead of being absorbed by a
                        // catch-all. The three below do not conflict — they are
                        // the disjoint/adjacent/shared-endpoint geometries the
                        // other strata enumerate — so reaching them from the
                        // conflict stratum is a mistake worth surfacing.
                        Geometry::Disjoint
                        | Geometry::FlushAdjacent
                        | Geometry::CoincidentEndpoint => {
                            out.push(Err((id, DropReason::NotAConflictingGeometry)));
                            continue;
                        }
                    };
                    let last = members
                        .iter()
                        .map(|m| m.start + m.span.max(1))
                        .max()
                        .unwrap_or(0);
                    if last >= frame.served().len() {
                        out.push(Err((id, DropReason::OutOfRange)));
                        continue;
                    }
                    let rendered: Option<Vec<String>> = members
                        .iter()
                        .map(|member| render_member(&frame, member))
                        .collect();
                    let Some(rendered) = rendered else {
                        out.push(Err((id, DropReason::NoDenotedSequence)));
                        continue;
                    };
                    let spelling = render_allele(&frame, &rendered);
                    // The row is only a conflict if it really denotes nothing.
                    // A design the applier accepts would be a *family*, and
                    // counting it here would make the refusal census a claim
                    // about the generator rather than about the implementation.
                    if denoted_by(frame.provider(), frame.served(), &spelling).is_some() {
                        out.push(Err((id, DropReason::DenotesTheReference)));
                        continue;
                    }
                    let rules = rules_for(
                        &[Kind::Del],
                        geometry,
                        0,
                        Region::MidCds,
                        shape,
                        members.len(),
                    );
                    out.push(Ok(Row {
                        id,
                        kind: RowKind::Conflict,
                        stratum: "conflicts",
                        shape,
                        core: core.clone(),
                        denoted: None,
                        spellings: vec![spelling],
                        members: members.len(),
                        separation: 0,
                        block_len: payload * 3,
                        mechanism: Mechanism::Cis,
                        prohibition: Some((
                            "general.md:57-no-self-replacement",
                            Strength::Absolute,
                        )),
                        negative_guards: Vec::new(),
                        // Set by `build_family` alone; this row is not a family.
                        coding_axis_separation_two_or_more: false,
                        geometry,
                        region: Region::MidCds,
                        scale_bands: Vec::new(),
                        rules,
                    }));
                }
            }
        }
    }
}

/// A member with no payload and no repeat — `del`, `dup` and `inv`.
fn simple_member(kind: Kind, start: usize, span: usize) -> Member {
    Member {
        kind,
        start,
        span,
        payload: String::new(),
        repeat: None,
    }
}

/// Stratum 6: intronic offsets — validity and idempotency only.
///
/// `hgvs_to_spdi` declines an intronic `c.` position ("SPDI is positional and has
/// no offset notation"), so the corpus has **no sequence oracle** for these rows
/// and cannot state what they denote. Rather than drop them — the shape is a
/// documented source of defects, and a single-exon `CDS_START = 1` transcript
/// cannot express one at all (#1478) — they are carried as [`RowKind::Single`]
/// rows and the two properties that need no oracle are measured. The axis test
/// reports the other two as `VACUOUS` for this stratum rather than counting them
/// as passes.
fn enumerate_intronic(bounds: &CorpusBounds, out: &mut Vec<Attempt>) {
    for (core_index, core) in corpus_cores(bounds.seeds, DENSE_CORE_LEN)
        .into_iter()
        .enumerate()
    {
        for shape in RefShape::structured() {
            if !shape.is_multi_exon() {
                continue;
            }
            let frame = Frame::build(shape, &core);
            let boundaries: Vec<(usize, isize)> = frame
                .exons()
                .iter()
                .enumerate()
                .flat_map(|(index, &(start, end))| {
                    let mut sites = Vec::new();
                    if index + 1 < frame.exons().len() {
                        sites.push((end - 1, 1isize));
                        sites.push((end - 1, 2));
                        sites.push((end - 1, 5));
                    }
                    if index > 0 {
                        sites.push((start - 1, -1));
                        sites.push((start - 1, -2));
                    }
                    sites
                })
                .collect();
            for (index, delta) in boundaries {
                for kind in [Kind::Del, Kind::Dup, Kind::Sub, Kind::Ins] {
                    for members in [1usize, 2] {
                        let id = format!(
                            "intronic-s{core_index:02}-{}-i{index}{delta:+}-{}-m{members}",
                            shape.label(),
                            kind.label()
                        );
                        let Some(label) = frame.intronic_label(index, delta) else {
                            out.push(Err((id, DropReason::UnavailableOnThisAxis)));
                            continue;
                        };
                        let member = match kind {
                            Kind::Del => format!("{label}del"),
                            Kind::Dup => format!("{label}dup"),
                            Kind::Sub => {
                                // The intronic base is unknown to the corpus (it
                                // lives on the contig, not the transcript), so a
                                // substitution states an unverifiable reference
                                // base. Spell it as a `delins` instead, which
                                // states none.
                                format!("{label}delinsTT")
                            }
                            _ => format!("{label}_{label}insTT"),
                        };
                        // An insertion needs two flanking positions; spelling
                        // both as the same intronic position is not legal HGVS,
                        // so an intronic insertion is written against the
                        // adjacent offset instead.
                        let member = if kind == Kind::Ins {
                            let Some(next) = frame.intronic_label(
                                index,
                                if delta > 0 { delta + 1 } else { delta - 1 },
                            ) else {
                                out.push(Err((id, DropReason::UnavailableOnThisAxis)));
                                continue;
                            };
                            if delta > 0 {
                                format!("{label}_{next}insTT")
                            } else {
                                format!("{next}_{label}insTT")
                            }
                        } else {
                            member
                        };
                        let rendered = if members == 1 {
                            vec![member]
                        } else {
                            // A second, exonic member, so the row exercises the
                            // interaction rather than the offset alone.
                            let Some(exonic) = frame
                                .region_start(Region::MidCds, 2)
                                .map(|start| format!("{}del", frame.label(start)))
                            else {
                                out.push(Err((id, DropReason::UnavailableOnThisAxis)));
                                continue;
                            };
                            if delta > 0 {
                                vec![exonic, member]
                            } else {
                                vec![member, exonic]
                            }
                        };
                        // Written against the genomic wrapper, not the bare
                        // transcript accession: `checklist.md:20` makes the
                        // wrapper mandatory for an intronic position, so a bare
                        // `NM_…:c.20+2del` is an *invalid input* rather than a
                        // test case. The bare form is generated separately, as a
                        // `RowKind::Prohibited` row whose property is refusal.
                        let Some(accession) = frame.wrapped_accession() else {
                            out.push(Err((id, DropReason::UnavailableOnThisAxis)));
                            continue;
                        };
                        let spelling =
                            render_allele_as(&accession, shape.prefix(), Mechanism::Cis, &rendered);
                        if parse_hgvs(&spelling).is_err() {
                            out.push(Err((id, DropReason::UnavailableOnThisAxis)));
                            continue;
                        }
                        let rules = rules_for(
                            &[kind],
                            Geometry::Disjoint,
                            2,
                            Region::Intronic,
                            shape,
                            members,
                        );
                        out.push(Ok(Row {
                            id,
                            kind: RowKind::Single,
                            stratum: "intronic",
                            shape,
                            core: core.clone(),
                            denoted: None,
                            spellings: vec![spelling],
                            members,
                            separation: 0,
                            block_len: 1,
                            mechanism: if members > 1 {
                                Mechanism::Cis
                            } else {
                                Mechanism::Lone
                            },
                            prohibition: None,
                            negative_guards: Vec::new(),
                            // Set by `build_family` alone; this row is not a family.
                            coding_axis_separation_two_or_more: false,
                            geometry: Geometry::Disjoint,
                            region: Region::Intronic,
                            scale_bands: Vec::new(),
                            rules,
                        }));
                    }
                }
            }
        }
    }
}

/// Stratum 7: the combining mechanisms, enumerated by mechanism rather than by
/// bracket (see [`Mechanism`]).
///
/// Each mechanism gets its own rows so the coverage table can say which are
/// exercised. Two of the six are deliberately **single-member** shapes that look
/// multi-member, and they are here so the census shows them being counted
/// correctly rather than leaving that claim to a reader's trust.
fn enumerate_mechanisms(bounds: &CorpusBounds, out: &mut Vec<Attempt>) {
    const MECHANISMS: &[Mechanism] = &[
        Mechanism::Cis,
        Mechanism::UnknownPhase,
        Mechanism::Trans,
        Mechanism::CompositePayload,
        Mechanism::RepeatCount,
    ];
    for (core_index, core) in corpus_cores(bounds.seeds, DENSE_CORE_LEN)
        .into_iter()
        .enumerate()
    {
        for shape in RefShape::all() {
            let frame = Frame::build(shape, &core);
            for &mechanism in MECHANISMS {
                for &separation in &[1usize, 3] {
                    let id = format!(
                        "mech-s{core_index:02}-{}-{}-sep{separation}",
                        shape.label(),
                        mechanism.label()
                    );
                    let Some(start) = frame.region_start(Region::MidCds, separation + 12) else {
                        out.push(Err((id, DropReason::UnavailableOnThisAxis)));
                        continue;
                    };
                    let served = frame.served();
                    let members = match mechanism {
                        Mechanism::Cis | Mechanism::UnknownPhase | Mechanism::Trans => vec![
                            format!("{}del", frame.label(start)),
                            format!("{}del", frame.label(start + 1 + separation)),
                        ],
                        // `ins[a;b]`: one member whose payload has two fragments.
                        Mechanism::CompositePayload => vec![format!(
                            "{}_{}ins[{};{}]",
                            frame.label(start),
                            frame.label(start + 1),
                            payload_bases(served, start, 2),
                            payload_bases(served, start + 1, 2)
                        )],
                        // `<span><unit>[n]`: one member with a repeat count. The
                        // unit is read out of the reference so the span matches.
                        Mechanism::RepeatCount => {
                            let unit = &served[start..start + 1];
                            vec![format!("{}{unit}[3]", frame.label(start))]
                        }
                        Mechanism::Lone => continue,
                    };
                    let spelling =
                        render_allele_as(frame.accession(), shape.prefix(), mechanism, &members);
                    if parse_hgvs(&spelling).is_err() {
                        // A mechanism the parser declines on this axis is a
                        // *finding*, not a silent absence: it is emitted as a
                        // prohibited row so the census reports it.
                        out.push(Ok(Row {
                            id,
                            kind: RowKind::Prohibited,
                            stratum: "mechanisms",
                            shape,
                            core: core.clone(),
                            denoted: None,
                            spellings: vec![spelling],
                            members: members.len(),
                            separation,
                            block_len: 1,
                            mechanism,
                            prohibition: Some((
                                "DNA/alleles.md:20-unknown-phase-without-brackets",
                                Strength::Conditional,
                            )),
                            negative_guards: Vec::new(),
                            // Set by `build_family` alone; this row is not a family.
                            coding_axis_separation_two_or_more: false,
                            geometry: Geometry::Disjoint,
                            region: Region::MidCds,
                            scale_bands: Vec::new(),
                            rules: vec!["DNA/alleles.md:20-unknown-phase-without-brackets"],
                        }));
                        continue;
                    }
                    // A trans or unknown-phase allele does not denote one
                    // sequence — its two members are on different molecules, or
                    // it is not known whether they are — so there is no
                    // sequence oracle and no confluence family. Validity and
                    // idempotency are what remain measurable.
                    let denotes_one_sequence = mechanism == Mechanism::Cis
                        || mechanism == Mechanism::CompositePayload
                        || mechanism == Mechanism::RepeatCount;
                    let denoted = denotes_one_sequence
                        .then(|| denoted_by(frame.provider(), served, &spelling))
                        .flatten();
                    let rules = vec![match mechanism {
                        Mechanism::Cis => "DNA/alleles.md:16-cis-semicolon",
                        Mechanism::UnknownPhase => {
                            "DNA/alleles.md:20-unknown-phase-without-brackets"
                        }
                        Mechanism::Trans => "DNA/alleles.md:17-trans-bracket-pairs",
                        Mechanism::CompositePayload => "general.md:78-brackets-composite-insertion",
                        Mechanism::RepeatCount => "DNA/repeated.md:5-repeat-format",
                        Mechanism::Lone => continue,
                    }];
                    out.push(Ok(Row {
                        id,
                        kind: RowKind::Single,
                        stratum: "mechanisms",
                        shape,
                        core: core.clone(),
                        denoted,
                        spellings: vec![spelling],
                        members: members.len(),
                        separation,
                        block_len: 1,
                        mechanism,
                        prohibition: None,
                        negative_guards: Vec::new(),
                        // Set by `build_family` alone; this row is not a family.
                        coding_axis_separation_two_or_more: false,
                        geometry: Geometry::Disjoint,
                        region: Region::MidCds,
                        scale_bands: Vec::new(),
                        rules,
                    }));
                }
            }
        }
    }
}

/// One prohibited shape: how to spell it, the clause, and how strongly the
/// clause is stated.
struct Prohibition {
    slug: &'static str,
    rule: &'static str,
    strength: Strength,
    /// Renders the offending **member** — no accession and no coordinate prefix —
    /// so the same prohibition can be emitted alone and inside a cis allele. A
    /// prohibited member next to a legal sibling is where a hygiene check that
    /// runs per description rather than per member stops firing.
    ///
    /// `None` when the shape is not expressible on that axis, which is itself the
    /// point for some rows: a genomic frame has no intron to hang an offset off.
    render: fn(&Frame) -> Option<String>,
    /// Whether the shape is single-member by nature, so no cis-paired row is
    /// emitted for it.
    lone_only: bool,
}

/// Stratum 8: shapes the recommendations prohibit outright.
///
/// The property is refusal. Every row carries its clause and its [`Strength`],
/// and the axis test pins the two acceptance counts separately: an
/// [`Strength::Absolute`] acceptance is a conformance defect, a
/// [`Strength::Conditional`] one is a finding to adjudicate.
fn enumerate_prohibited(bounds: &CorpusBounds, out: &mut Vec<Attempt>) {
    const PROHIBITIONS: &[Prohibition] = &[
        // `checklist.md:16`: "genomic (`g.`) reference sequences start with
        // nucleotide 1 and can not have nucleotides with additions like a `+`,
        // `-`, or `*`."
        Prohibition {
            slug: "genomic-plus-offset",
            rule: "checklist.md:16-genomic-has-no-offsets",
            strength: Strength::Absolute,
            render: |frame| {
                (frame.shape == RefShape::Genomic).then(|| format!("{}+2del", PAD_OFFSET + 10))
            },
            lone_only: false,
        },
        Prohibition {
            slug: "genomic-star-offset",
            rule: "checklist.md:16-genomic-has-no-offsets",
            strength: Strength::Absolute,
            render: |frame| (frame.shape == RefShape::Genomic).then(|| "*10del".to_string()),
            lone_only: false,
        },
        // `checklist.md:45`: "Not correct is `c.12-14del`, this describes a
        // deletion of nucleotide -14 in the intron directly 5' of nucleotide
        // `c.12`." On a genomic axis a hyphen cannot be an intronic offset
        // either, so the shape has no legal reading at all.
        Prohibition {
            slug: "hyphen-range",
            rule: "checklist.md:45-range-is-underscore",
            strength: Strength::Absolute,
            render: |frame| {
                (frame.shape == RefShape::Genomic)
                    .then(|| format!("{}-{}del", PAD_OFFSET + 10, PAD_OFFSET + 12))
            },
            lone_only: false,
        },
        // `checklist.md:49`: "Descriptions like `g.123del3` are not allowed".
        Prohibition {
            slug: "sized-deletion-suffix",
            rule: "checklist.md:49-deletion-names-both-endpoints",
            strength: Strength::Absolute,
            render: |frame| Some(format!("{}del3", frame.label(9))),
            lone_only: false,
        },
        // `checklist.md:31`: "The format `c.52insT` is **ambiguous**, and not
        // allowed."
        Prohibition {
            slug: "single-anchor-insertion",
            rule: "checklist.md:30-insertion-needs-two-anchors",
            strength: Strength::Absolute,
            render: |frame| Some(format!("{}insT", frame.label(9))),
            lone_only: false,
        },
        // `checklist.md:33`: "Describing a variant as `c.5439_5430ins6` is not
        // allowed, the inserted sequence … should be specified."
        Prohibition {
            slug: "sized-insertion-payload",
            rule: "checklist.md:32-insertion-states-its-sequence",
            strength: Strength::Absolute,
            render: |frame| Some(format!("{}_{}ins6", frame.label(9), frame.label(10))),
            lone_only: false,
        },
        // `background/standards.md:39` footnotes `X` and `-` as "used in
        // alignment only", so neither is a base a description may state.
        Prohibition {
            slug: "alignment-only-base-x",
            rule: "standards.md:39-alignment-only-symbols",
            strength: Strength::Conditional,
            render: |frame| Some(format!("{}delinsX", frame.label(9))),
            lone_only: false,
        },
        // `general.md:96`: "spaces are *not* permitted in any HGVS description".
        Prohibition {
            slug: "internal-space",
            rule: "general.md:95-no-spaces",
            strength: Strength::Absolute,
            render: |frame| Some(format!("{}_{} del", frame.label(9), frame.label(11))),
            lone_only: false,
        },
        // `checklist.md:20` NOTE: an NM_ "can only be used to describe variants
        // in introns using a `c.` prefix when a genomic reference sequence is
        // given on which the coding DNA reference sequence is annotated".
        // Conditional, not absolute: the clause states a condition rather than
        // using prohibitive words.
        Prohibition {
            slug: "bare-transcript-intronic",
            rule: "checklist.md:20-intron-needs-a-genomic-wrapper",
            strength: Strength::Conditional,
            render: |frame| {
                let exon = frame.exons().first().copied()?;
                (frame.exons().len() > 1).then(|| format!("{}+2del", frame.label(exon.1 - 1)))
            },
            lone_only: false,
        },
        // `checklist.md:26`: "the format `c.123-65_-50` is not, it is
        // **incomplete**."
        Prohibition {
            slug: "incomplete-intronic-range",
            rule: "checklist.md:26-intronic-range-is-complete",
            strength: Strength::Absolute,
            render: |frame| {
                let exon = frame.exons().first().copied()?;
                (frame.exons().len() > 1).then(|| format!("{}+2_+5del", frame.label(exon.1 - 1)))
            },
            lone_only: false,
        },
    ];

    for (core_index, core) in corpus_cores(bounds.seeds, DENSE_CORE_LEN)
        .into_iter()
        .enumerate()
    {
        for shape in RefShape::all() {
            let frame = Frame::build(shape, &core);
            for prohibition in PROHIBITIONS {
                let pairings: &[Mechanism] = if prohibition.lone_only {
                    &[Mechanism::Lone]
                } else {
                    &[Mechanism::Lone, Mechanism::Cis]
                };
                for &mechanism in pairings {
                    let id = format!(
                        "prohibited-s{core_index:02}-{}-{}-{}",
                        shape.label(),
                        prohibition.slug,
                        mechanism.label()
                    );
                    let Some(offender) = (prohibition.render)(&frame) else {
                        out.push(Err((id, DropReason::UnavailableOnThisAxis)));
                        continue;
                    };
                    // A legal sibling three bases 3' of the offender, so the row
                    // is a cis allele whose *other* member is fine. A hygiene
                    // check that runs once per description rather than once per
                    // member stops firing exactly here.
                    let members = match mechanism {
                        Mechanism::Cis => {
                            let Some(start) = frame.region_start(Region::MidCds, 4) else {
                                out.push(Err((id, DropReason::UnavailableOnThisAxis)));
                                continue;
                            };
                            vec![offender, format!("{}del", frame.label(start))]
                        }
                        _ => vec![offender],
                    };
                    let spelling =
                        render_allele_as(frame.accession(), shape.prefix(), mechanism, &members);
                    out.push(Ok(Row {
                        id,
                        kind: RowKind::Prohibited,
                        stratum: "prohibited",
                        shape,
                        core: core.clone(),
                        denoted: None,
                        spellings: vec![spelling],
                        members: members.len(),
                        separation: 0,
                        block_len: 1,
                        mechanism,
                        prohibition: Some((prohibition.rule, prohibition.strength)),
                        negative_guards: Vec::new(),
                        // Set by `build_family` alone; this row is not a family.
                        coding_axis_separation_two_or_more: false,
                        geometry: Geometry::Disjoint,
                        region: Region::Anywhere,
                        scale_bands: Vec::new(),
                        rules: vec![prohibition.rule],
                    }));
                }
            }
        }
    }
}

/// The 15 nucleotide symbols the recommendations admit, per
/// `background/standards.md`.
///
/// `X` and `-` appear in that table and are footnoted at `:39` as "used in
/// alignment only", so they are **excluded** here and generated instead as
/// prohibited shapes. Getting that boundary wrong in the other direction —
/// emitting `X` as content — would make every row carrying it an invalid input
/// whose result means nothing.
pub const DNA_SYMBOLS: &[char] = &[
    'A', 'C', 'G', 'T', 'B', 'D', 'H', 'K', 'M', 'N', 'R', 'S', 'V', 'W', 'Y',
];

/// Stratum 9: IUPAC ambiguity codes in **inserted** payloads.
///
/// Only on the inserted side. An ambiguous *reference* base is not something a
/// synthetic reference can hold and still be applied against, so the corpus does
/// not claim to cover it — see the rule inventory's not-generatable list.
fn enumerate_ambiguity(bounds: &CorpusBounds, out: &mut Vec<Attempt>) {
    for (core_index, core) in corpus_cores(bounds.seeds, DENSE_CORE_LEN)
        .into_iter()
        .enumerate()
    {
        for shape in [RefShape::Genomic, RefShape::CodingMultiExon(Strand::Plus)] {
            let frame = Frame::build(shape, &core);
            // Skip the four unambiguous symbols: they are what every other
            // stratum already draws from.
            for &symbol in &DNA_SYMBOLS[4..] {
                let id = format!("ambiguity-s{core_index:02}-{}-{symbol}", shape.label());
                let Some(start) = frame.region_start(Region::MidCds, 8) else {
                    out.push(Err((id, DropReason::UnavailableOnThisAxis)));
                    continue;
                };
                let members = vec![
                    format!("{}delins{symbol}{symbol}", frame.label(start)),
                    format!(
                        "{}_{}ins{symbol}",
                        frame.label(start + 2),
                        frame.label(start + 3)
                    ),
                ];
                let spelling = render_allele(&frame, &members);
                let Some(denoted) = denoted_by(frame.provider(), frame.served(), &spelling) else {
                    out.push(Err((id, DropReason::NoDenotedSequence)));
                    continue;
                };
                out.push(Ok(Row {
                    id,
                    kind: RowKind::Single,
                    stratum: "ambiguity",
                    shape,
                    core: core.clone(),
                    denoted: Some(denoted),
                    spellings: vec![spelling],
                    members: 2,
                    separation: 1,
                    block_len: 4,
                    mechanism: Mechanism::Cis,
                    prohibition: None,
                    negative_guards: Vec::new(),
                    // Set by `build_family` alone; this row is not a family.
                    coding_axis_separation_two_or_more: false,
                    geometry: Geometry::Disjoint,
                    region: Region::MidCds,
                    scale_bands: Vec::new(),
                    rules: vec!["standards.md:15-iupac-nucleotide-symbols"],
                }));
            }
        }
    }
}

/// Rules that are about one member's own spelling, so no multi-member row can
/// exercise them any more thoroughly than a lone one.
///
/// Named rather than derived, because "this rule cannot be multi-member" is a
/// judgement and the list is short enough to review. Everything *not* here must
/// reach a multi-member row — see
/// [`tests::every_rule_tag_is_reachable_and_mostly_multi_member`].
pub const SINGLE_MEMBER_BY_NATURE: &[&str] = &[
    // A composite insertion payload is one member by definition; that is the
    // whole reason it is enumerated as its own mechanism.
    "general.md:78-brackets-composite-insertion",
];

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

    /// The corpus must be reproducible from its bounds alone, and a smaller run
    /// must be a strict prefix of a larger one on both axes — seed count and
    /// draw length. Prefix stability is what makes a reduced run a strict subset
    /// of the full run's cases, so a zero at a prefix cannot be non-zero at the
    /// full corpus.
    #[test]
    fn cores_are_deterministic_and_prefix_stable() {
        assert_eq!(corpus_cores(2, 64), corpus_cores(2, 64));
        let few = corpus_cores(2, 64);
        let many = corpus_cores(6, 64);
        assert_eq!(few[..], many[..few.len()]);
        for (short, long) in corpus_cores(2, 20).iter().zip(corpus_cores(2, 64)) {
            assert_eq!(short.as_str(), &long[..20]);
        }
        // The same stream `sweep_sequences` draws, which is what "shares the
        // generator" has to mean to be worth claiming.
        assert_eq!(corpus_cores(1, 20)[0], "TTTTTTTTTAATATATTTTA");
        assert_eq!(corpus_cores(1, 20)[1], "CCCCCCCCTGACGTATCCTA");
    }

    /// `hgvs_to_spdi` reports positions 0-based on the sequence the axis serves —
    /// the padded contig for `g.`, the transcript for `c.`/`n.`. Everything the
    /// applier does rests on this, so it is pinned rather than assumed.
    #[test]
    fn spdi_positions_are_zero_based_on_the_served_sequence() {
        let core = corpus_cores(1, DENSE_CORE_LEN).remove(1);
        let genomic = Frame::build(RefShape::Genomic, &core);
        let at = PAD_OFFSET + 9;
        let spelling = format!("{GENOMIC_CONTIG}:g.{}del", at + 1);
        let triples = triples_of(genomic.provider(), &spelling).expect("a genomic triple");
        assert_eq!(triples[0].0, at);
        assert_eq!(triples[0].1, core[9..10]);

        let coding = Frame::build(RefShape::CodingMultiExon(Strand::Plus), &core);
        let (cds_start, _) = coding.cds().expect("a coding frame has a CDS");
        let spelling = format!("{CODING_ACCESSION}:c.1del");
        let triples = triples_of(coding.provider(), &spelling).expect("a coding triple");
        assert_eq!(triples[0].0, cds_start - 1);
    }

    /// A coding frame must reach `-n`, `n` and `*n` labels, because a
    /// single-exon `CDS_START = 1` transcript reaches only the middle one — that
    /// is #1478 exactly, and a regression to it would silently delete a third of
    /// the region stratum.
    #[test]
    fn a_coding_frame_labels_all_three_regions() {
        let core = corpus_cores(1, DENSE_CORE_LEN).remove(1);
        let frame = Frame::build(RefShape::CodingMultiExon(Strand::Plus), &core);
        let (cds_start, cds_end) = frame.cds().expect("a CDS");
        assert!(cds_start > 1, "the 5'UTR must be non-empty");
        assert!(cds_end < core.len(), "the 3'UTR must be non-empty");
        assert_eq!(frame.label(0), format!("-{}", cds_start - 1));
        assert_eq!(frame.label(cds_start - 1), "1");
        assert_eq!(frame.label(cds_end), "*1");
        assert_eq!(frame.exons().len(), 3, "three exons, so two junctions");

        // The control shape is deliberately the blind one.
        let control = Frame::build(RefShape::CodingSingleExon, &core);
        assert_eq!(control.exons().len(), 1);
        assert_eq!(control.cds().map(|c| c.0), Some(1));
        assert!(
            control.region_start(Region::Utr5, 2).is_none(),
            "the #1478 control shape must have no 5'UTR to place a row in"
        );
    }

    /// A minus-strand transcript's exon 1 must occupy the highest genomic
    /// coordinates, and its transcript sequence must still read 5'->3' in
    /// transcript order. Otherwise the frame is a plus-strand transcript wearing
    /// a label, and every minus-strand row measures the same thing twice.
    #[test]
    fn a_minus_strand_frame_reverses_the_genomic_layout() {
        let core = corpus_cores(1, DENSE_CORE_LEN).remove(1);
        let frame = Frame::build(RefShape::CodingMultiExon(Strand::Minus), &core);
        assert_eq!(frame.served(), core.as_str());
        // The projection has to agree with the transcript sequence: a `c.` row
        // in exon 2 must read the base the transcript holds, not its complement.
        let (cds_start, _) = frame.cds().expect("a CDS");
        let spelling = format!("{CODING_ACCESSION}:c.1del");
        let triples = triples_of(frame.provider(), &spelling).expect("a triple");
        assert_eq!(triples[0].1, core[cds_start - 1..cds_start]);
    }

    /// The applier declines exactly what denotes no sequence, and nothing else.
    /// It is the whole ground truth, so its two non-obvious rules get their own
    /// assertions: a zero-width member flush against a deletion is not an
    /// overlap, and two pure insertions at one interbase are declined.
    #[test]
    fn the_applier_declines_only_what_denotes_no_sequence() {
        let reference = "AAAACCCCGGGG";
        assert_eq!(
            apply_triples(
                reference,
                &[
                    (4, "CCCC".to_string(), String::new()),
                    (4, String::new(), "TT".to_string()),
                ],
            )
            .as_deref(),
            Some("AAAATTGGGG")
        );
        assert_eq!(
            apply_triples(
                reference,
                &[
                    (4, "CCCC".to_string(), String::new()),
                    (6, "CC".to_string(), String::new()),
                ],
            ),
            None
        );
        assert_eq!(
            apply_triples(
                reference,
                &[
                    (4, String::new(), "TT".to_string()),
                    (4, String::new(), "GG".to_string()),
                ],
            ),
            None
        );
        assert_eq!(
            apply_triples(reference, &[(4, "GGGG".to_string(), String::new())]),
            None
        );
    }

    /// Every row the coding-axis merge instrument counts over really is in the
    /// population it claims, and the population is not empty.
    ///
    /// Without this the counter's denominator is a number nobody checked: a
    /// predicate that silently admitted a `g.` row, or a separation of one,
    /// would make the census's figure mean something other than what its docs
    /// say — and `spec_conformance_axis` asserts only that the denominator is
    /// non-zero, never what is in it.
    ///
    /// It also pins the disjointness the instrument is built on: no row may
    /// carry both this flag and the SVD-WG010 negative guard. That is what makes
    /// "the guard cannot count these merges" a property of the corpus rather
    /// than a claim in a doc comment.
    ///
    /// # What it does NOT check, stated because a mutation showed it
    ///
    /// **Irreducibility.** [`is_coding_axis_separation_two_or_more_shape`] names
    /// it as a conjunct and [`build_family`] computes it, but a `Row` does not
    /// carry the triples the check needs, so this test cannot re-derive it.
    /// Dropping that conjunct leaves this test **green** while moving the
    /// denominator 997 -> 2,527 and the census numerator 0 -> 74 (measured on an
    /// `origin/main` whose shipped numerator was still 0, i.e. before #1835 took
    /// it to 3; the mutation has not been re-run since, so read the direction and
    /// not the second digit) — so the property is real and load-bearing, and it
    /// is defended by the two census pins rather than here. Do not read this test
    /// as covering it.
    #[test]
    fn the_coding_axis_merge_population_is_what_it_says_it_is() {
        let built = corpus(&CorpusBounds::default());
        let mut checked = 0usize;
        for row in &built.rows {
            if !row.coding_axis_separation_two_or_more {
                continue;
            }
            assert_eq!(
                row.kind,
                RowKind::Family,
                "{}: only family rows carry the flag",
                row.id
            );
            assert!(
                matches!(
                    row.shape,
                    RefShape::CodingSingleExon | RefShape::CodingMultiExon(_)
                ),
                "{}: {:?} is not a coding axis",
                row.id,
                row.shape
            );
            assert!(
                row.separation >= 2,
                "{}: separation {} is below the floor the instrument documents",
                row.id,
                row.separation
            );
            assert!(row.is_multi_member(), "{}: not multi-member", row.id);
            assert!(
                matches!(row.mechanism, Mechanism::Cis),
                "{}: mechanism {:?} — a merged trans or unknown-phase allele is a defect, not a \
                 population this instrument may count",
                row.id,
                row.mechanism
            );
            // Named, not `is_empty()`. The property is disjointness from THIS
            // guard; a second, unrelated guard label added to a coding row later
            // would otherwise fail here with a message about SVD-WG010.
            assert!(
                !row.negative_guards.contains(&SVD_WG010_GUARD),
                "{}: carries the SVD-WG010 guard as well, so the two domains overlap",
                row.id
            );
            checked += 1;
        }
        assert!(
            checked > 0,
            "VACUOUS: the corpus builds no coding-axis row separated by two or more unchanged \
             nucleotides, so the merge counter measures nothing"
        );
        assert_eq!(
            checked,
            built.coding_axis_separation_two_or_more_rows(),
            "the accessor and a direct scan disagree"
        );
    }

    /// A deletion inside a run has an ambiguous placement and both ends must be
    /// found; one outside a run has none.
    #[test]
    fn equivalent_placements_find_both_ends_of_a_run() {
        //          0123456789
        let core = "GTAAAAATCG";
        let placements = equivalent_placements(core, 4, "A", "");
        let offsets: Vec<usize> = placements.iter().map(|p| p.0).collect();
        assert_eq!(offsets, vec![2, 6], "the run spans core[2..7]");
        assert!(equivalent_placements(core, 0, "G", "").is_empty());
    }

    /// Every emitted family satisfies the contract the axis test relies on: at
    /// least two distinct spellings, each of which really does denote the row's
    /// sequence when applied independently of the normalizer.
    #[test]
    fn every_family_is_a_real_confluence_family() {
        let built = corpus(&CorpusBounds::default());
        assert!(
            built.rows.len() > 2_000,
            "the corpus collapsed to {} rows",
            built.rows.len()
        );
        let mut checked = 0usize;
        for row in &built.rows {
            if row.kind != RowKind::Family {
                continue;
            }
            let frame = row.frame();
            let expected = row.denoted.as_deref().expect("a family denotes a sequence");
            assert!(row.spellings.len() >= 2, "{} is a singleton", row.id);
            for spelling in &row.spellings {
                let applied = denoted_by(frame.provider(), frame.served(), spelling)
                    .unwrap_or_else(|| panic!("{spelling} does not apply"));
                assert_eq!(applied, expected, "{spelling} denotes a different sequence");
            }
            checked += 1;
            if checked >= 400 {
                break;
            }
        }
        assert!(checked > 0, "no families to check — the corpus is vacuous");
    }

    /// A conflict row must really denote nothing, or the refusal census would be
    /// a claim about the generator rather than about the implementation.
    #[test]
    fn every_conflict_row_denotes_no_sequence() {
        let built = corpus(&CorpusBounds::default());
        let conflicts: Vec<&Row> = built
            .rows
            .iter()
            .filter(|row| row.kind == RowKind::Conflict)
            .collect();
        assert!(
            conflicts.len() >= 20,
            "only {} conflict rows — #1456 is rebuilt",
            conflicts.len()
        );
        for row in conflicts {
            let frame = row.frame();
            assert_eq!(
                denoted_by(frame.provider(), frame.served(), &row.spellings[0]),
                None,
                "{} denotes a sequence, so it is not a conflict",
                row.id
            );
        }
    }

    /// Each of the three recorded blindnesses must be varied, and the assertion
    /// is on the corpus rather than on the generator's intent: #1456, #1460 and
    /// #1478 were each invisible to the one before it precisely because the
    /// generator believed it covered them.
    #[test]
    fn the_three_recorded_blindnesses_are_varied() {
        let built = corpus(&CorpusBounds::default());

        // #1456 — member geometry, including geometries that denote nothing.
        let geometries = built.by_geometry();
        for geometry in [
            Geometry::Disjoint,
            Geometry::FlushAdjacent,
            Geometry::CoincidentEndpoint,
            Geometry::Nested,
            Geometry::Overlapping,
            Geometry::CoincidentInsertions,
            Geometry::SelfReplacement,
        ] {
            assert!(
                geometries.get(geometry.label()).copied().unwrap_or(0) > 0,
                "no rows with geometry {} — #1456 is rebuilt",
                geometry.label()
            );
        }

        // #1460 — scale. A row must actually reach each band, not merely be
        // enumerated at a length that would.
        let bands = built.by_scale_band();
        for band in [
            "canonical-pad-128",
            "tie-break-sweep-256",
            "split-block-1024",
            "canonical-window-4096",
            "window-past-canonical-4096",
        ] {
            assert!(
                bands.get(band).copied().unwrap_or(0) > 0,
                "no rows reach {band} — #1460 is rebuilt"
            );
        }

        // #1478 — transcript geometry.
        let regions = built.by_region();
        for region in [
            Region::Utr5,
            Region::CdsStart,
            Region::MidCds,
            Region::ExonJunction1,
            Region::ExonJunction2,
            Region::CdsEnd,
            Region::Utr3,
            Region::Intronic,
        ] {
            assert!(
                regions.get(region.label()).copied().unwrap_or(0) > 0,
                "no rows in region {} — #1478 is rebuilt",
                region.label()
            );
        }
        let shapes = built.by_shape();
        for shape in RefShape::all() {
            assert!(
                shapes.get(shape.label()).copied().unwrap_or(0) > 0,
                "no rows on reference shape {}",
                shape.label()
            );
        }
    }

    /// Multi-member is the priority axis, so its share is asserted rather than
    /// hoped for. Real corpora are 0.006% multi-member; this must be
    /// overwhelmingly the opposite.
    #[test]
    fn multi_member_rows_dominate_the_corpus() {
        let built = corpus(&CorpusBounds::default());
        let share = built.multi_member_rows() as f64 / built.rows.len() as f64;
        assert!(
            share > 0.9,
            "multi-member share is {share:.4}; real corpora are 0.00006 and this corpus \
             exists to invert that"
        );
    }

    /// Every rule tag a design can carry must be reachable, and the census must
    /// say whether it is reached in a multi-member context — a rule only ever
    /// exercised single-member is a gap even when it reads as covered.
    #[test]
    fn every_rule_tag_is_reachable_and_mostly_multi_member() {
        let built = corpus(&CorpusBounds::default());
        let coverage = built.by_rule();
        assert!(!coverage.is_empty(), "no rule tags — coverage is vacuous");
        for (rule, seen) in &coverage {
            assert!(seen.rows > 0, "{rule} is tagged but reached by no row");
        }
        // A rule only ever exercised on a single-member row is a gap even when
        // it reads as covered, because partitioning, separation, ordering,
        // overlap detection, coalescing and typing interact only in a
        // multi-member allele. So the exceptions are named rather than tolerated:
        // this list is what "single-member by nature" means, and anything else
        // showing up here is a coverage gap to close.
        let single_member_only: Vec<&str> = coverage
            .iter()
            .filter(|(_, seen)| seen.multi_member_rows == 0)
            .map(|(rule, _)| *rule)
            .filter(|rule| !SINGLE_MEMBER_BY_NATURE.contains(rule))
            .collect();
        assert!(
            single_member_only.is_empty(),
            "these rules are never exercised in a multi-member row, and are not in \
             SINGLE_MEMBER_BY_NATURE: {single_member_only:?}"
        );
    }
}