vela-verify 0.950.1

Vela Verify: frozen, independent exact verifiers for combinatorial and coding-theory witnesses (Sidon, Golomb, cap sets, B_h, covering designs, constant-weight, Costas, linear codes). An untrusted proposer's construction is re-checked deterministically here before any claim is recorded; corrupting a witness must fail the verifier. The reference verifier registry the gate (vela-protocol::verifier_attachment) and `vela reproduce` build on.
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
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
//! Frozen, independent exact verifiers for combinatorial and
//! coding-theory witnesses.
//!
//! The discovery loop's proposers are **untrusted**: an agent returns an
//! explicit construction (a set of points, a ruler, a generator matrix),
//! and this crate re-checks it deterministically before any claim is
//! recorded. A witness that does not pass here is discarded no matter
//! what the proposer reported. Corrupting a witness must fail the
//! verifier — that is the property the self-tests pin.
//!
//! This is the reference verifier registry the trust gate
//! ([`vela_protocol::verifier_attachment`]) and `vela reproduce` build
//! on: a passing verify here is the *evidence* an `exact_construction`
//! verifier attachment attests to. The verifiers are intentionally
//! dependency-light (serde only) and pure — no I/O, no randomness — so a
//! third party can re-run them and get byte-identical verdicts.
//!
//! Ported from the campaign's `scripts/verify_construction.py`; the
//! Python reference and this Rust port must agree on every witness.

use std::collections::HashSet;

use serde::{Deserialize, Serialize};

/// A stable, reproducible identity for the frozen verifier build, recorded in
/// the `policy.auto_admitted` audit record (`verifier_env_hash`) so an auditor
/// can pin which frozen `vela-verify` produced a machine admission. Same source
/// + same release => same string.
pub const ENV_ID: &str = concat!("vela-verify@", env!("CARGO_PKG_VERSION"));

/// The outcome of verifying one witness.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct VerifyResult {
    /// Whether the witness passed its exact verifier.
    pub ok: bool,
    /// Human-readable detail (what was checked, or why it failed).
    pub message: String,
    /// A recomputed numeric quantity for "value-to-beat" problems
    /// (currently unused by the boolean verifiers; reserved).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub value: Option<f64>,
}

impl VerifyResult {
    pub fn ok(message: impl Into<String>) -> Self {
        Self {
            ok: true,
            message: message.into(),
            value: None,
        }
    }
    pub fn fail(message: impl Into<String>) -> Self {
        Self {
            ok: false,
            message: message.into(),
            value: None,
        }
    }
}

/// A witness to verify. Tagged by `kind` on the wire, so a witness file
/// is `{"kind": "sidon", "n": 8, "points": [[...], ...], ...}`.
///
/// `claimed_size` (where present) lets a record assert "this construction
/// has N elements" — `verify_witness` confirms the verifier passes *and*
/// the construction has exactly that size, so a record can't claim a
/// bigger set than the witness it ships.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum Witness {
    /// A Sidon set in `{0,1}^n` under componentwise integer addition:
    /// all pairwise sums distinct.
    Sidon {
        n: usize,
        points: Vec<Vec<i64>>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        claimed_size: Option<usize>,
    },
    /// A Golomb ruler: integer marks with all pairwise differences
    /// distinct.
    Golomb { marks: Vec<i64> },
    /// A cap set in `F_3^n`: no three distinct points collinear.
    Cap {
        n: usize,
        points: Vec<Vec<i64>>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        claimed_size: Option<usize>,
    },
    /// A `B_h` set in `{0,1}^n`: all `h`-fold sums distinct (`h = 2` is
    /// Sidon).
    Bh {
        n: usize,
        h: usize,
        points: Vec<Vec<i64>>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        claimed_size: Option<usize>,
    },
    /// A covering design `C(v, k, t)`: every `t`-subset of `[0, v)` lies
    /// in at least one `k`-block.
    Covering {
        v: usize,
        k: usize,
        t: usize,
        blocks: Vec<Vec<usize>>,
    },
    /// A constant-weight binary code `A(n, d, w)`: codewords of weight
    /// exactly `w`, pairwise Hamming distance `>= d`.
    ConstantWeight {
        n: usize,
        d: usize,
        w: usize,
        words: Vec<Vec<i64>>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        claimed_size: Option<usize>,
    },
    /// A Costas array: a permutation whose displacement vectors are all
    /// distinct.
    Costas { perm: Vec<i64> },
    /// A Sidon set in `GF(2)^n` (OEIS A394031): `elements` are integer
    /// bitmasks; the set is Sidon iff all pairwise XORs are distinct (no
    /// four distinct elements XOR to zero). Pure integer arithmetic.
    Gf2Sidon {
        elements: Vec<u64>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        claimed_size: Option<usize>,
    },
    /// A union-free family (OEIS A347025): nonempty subsets of `{1..n}` such
    /// that no member equals the union of a sub-collection of the others.
    /// `sets` lists the members (1-based elements). The witness certifies the
    /// LOWER bound a(n) >= |sets|; optimality (no larger family) is a separate
    /// exhaustive search, not a witness-checkable property.
    UnionFree {
        n: usize,
        sets: Vec<Vec<u32>>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        claimed_size: Option<usize>,
    },
    /// A non-attacking rook placement (OEIS A321531): `perm` is 1-based columns
    /// (rook i sits in row i, column `perm[i]`). The verifier counts distinct
    /// direction classes `sorted(|Δcol|,|Δrow|)/gcd` over all rook pairs. The
    /// witness certifies the LOWER bound a(n) >= count; optimality is a
    /// separate exhaustive search, not a witness-checkable property.
    RookDirections {
        n: usize,
        perm: Vec<i64>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        claimed_directions: Option<usize>,
    },
    /// A linear `[n, k, d]_q` code given by a `k x n` generator matrix
    /// over a prime field `GF(q)`.
    LinearCode {
        q: u64,
        claimed_d: usize,
        generator: Vec<Vec<i64>>,
    },
    /// An Erdős #1056 cut-equality certificate: a prime `p` and strictly
    /// increasing cuts `c_0 < ... < c_k` such that every consecutive
    /// interval `(c_{i-1}, c_i]` has integer product `== 1 (mod p)`.
    IntervalProduct { p: u64, cuts: Vec<u64> },
    /// A balanced r-coloring of K_n (Erdős #617 shape): every
    /// (r+1)-vertex subset must see all r colors among its internal
    /// edges. `edge_colors` keys are "i,j" with i<j, 0-indexed; colors
    /// are 1..=r. For K_26 r=5 this is C(26,6)=230,230 subset checks —
    /// instant.
    BalancedColoring {
        n: usize,
        r: usize,
        edge_colors: std::collections::BTreeMap<String, u32>,
    },
    /// An Erdős #203 partial CRT covering certificate: a modulus `m`
    /// (decimal string, coprime to 6) and prime rows, each pinning the
    /// multiplicative orders of 2 and 3 mod `p` and an affine line
    /// `(alpha, beta, gamma, h)` such that `p | 2^k 3^l m + 1` iff
    /// `alpha*k + beta*l == gamma (mod h)`, checked exhaustively over
    /// `(k, l) in [0, h)^2`.
    CrtPartialCover { m: String, rows: Vec<CrtCoverRow> },
    /// An Erdős #684 effective lower-bound certificate: for each entry
    /// `(k, m)`, `m = prod_{p<=k} p^(floor(log_p k)+1)` is recomputed and
    /// adding `j + (m-1-j)` in base `p` produces zero Kummer carries for
    /// all `2 <= j <= k`, `p <= j` — hence `f(m-1) > k`.
    KummerNoCarry { entries: Vec<KummerEntry> },
    /// An Erdős #700 value certificate: for each `(n, f)`,
    /// `f = min_{1<k<=n/2} gcd(n, C(n,k))`, recomputed via Kummer
    /// (`gcd(n, C(n,k)) = prod_{p|n} p^min(v_p(n), carries_p(k, n-k))`)
    /// so no big integers ever materialize.
    MinBinomGcd { cases: Vec<MinGcdCase> },
    /// An Erdős #1093 (ELS93) deficiency certificate: for each entry,
    /// `C(N,k)` is Kummer-defined (no prime `p <= k` divides it) and the
    /// deficiency `delta(N,k) = #{1<=i<=k : (N-k+i) | i*C(k,i)}` equals
    /// the claimed value (and slot positions, when given). Divisibility
    /// is decided by smooth factorization + Legendre — `i*C(k,i)` is
    /// never materialized.
    BinomDeficiency { entries: Vec<DeficiencyEntry> },
    /// An Erdős #1094 exception-enumeration certificate: every
    /// counterexample with `N >= 2k`, `k <= k_max` arises as
    /// `N = x + k - r` with `x | gcd(lcm(1..k), r*C(k,r))`, `k | x`.
    /// The verifier re-enumerates all candidates and confirms the found
    /// exception set equals the claimed `(N, k)` list exactly.
    /// Fail-closed: an unresolved candidate aborts rather than claims.
    BinomExceptionEnum {
        k_max: u64,
        exceptions: Vec<(u64, u64)>,
    },
    /// An UNSAT certificate: a CNF formula plus an LRAT-style clausal
    /// proof. Each proof step adds a clause justified by reverse unit
    /// propagation (RUP) over named antecedent clauses; the proof is
    /// accepted only if it derives the empty clause. A propositional
    /// claim (e.g. an Erdős finite case reduced to SAT) is verified by
    /// replaying this proof — the solver is untrusted, the certificate
    /// is checked. RUP only: a proof whose hints carry RAT structure is
    /// refused, never guessed.
    UnsatCert {
        cnf: Vec<Vec<i64>>,
        proof: Vec<LratStep>,
    },
    /// A difference triangle set (HorizonMath / coding theory): `rows` of
    /// strictly increasing non-negative integers each starting at 0, such that
    /// every positive within-row pairwise difference is GLOBALLY distinct (no
    /// difference repeats anywhere in the set). A `(I, J)`-DTS has `I` rows of
    /// `J + 1` marks; the objective is to MINIMIZE the scope (the largest mark).
    /// `claimed_scope`, when present, must equal the recomputed scope, so a
    /// record claim ("scope < 112") cannot ship a witness of a different scope.
    DiffTriangle {
        rows: Vec<Vec<i64>>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        claimed_scope: Option<usize>,
    },
    /// An Erdős #242 (Erdős–Straus, distinct variant) certificate: for every
    /// `n` in `[3, n_max]`, distinct integers `1 <= x < y < z` with
    /// `4/n = 1/x + 1/y + 1/z`. The verifier confirms the table is COMPLETE
    /// over `[3, n_max]` (no gaps) and every case is exact (`4 x y z = n (yz +
    /// xz + xy)`) with `x < y < z`. This certifies the conjecture for all
    /// `3 <= n <= n_max` — a FINITE confirmation, not the uniform proof (which
    /// is the open problem). Pure integer arithmetic; `cases` may be in any
    /// order (the verifier sorts/checks coverage).
    UnitFractionDecomp {
        n_max: u64,
        cases: Vec<UnitFractionCase>,
    },
    /// An Erdős #475 (Graham distinct-partial-sums) certificate for a fixed
    /// prime `p`: for EVERY nonempty `A ⊆ F_p\{0}`, an ordering of `A` whose
    /// partial sums are all distinct mod `p`. `orderings` lists one sequence per
    /// subset; the verifier confirms `p` is prime, every ordering is a valid
    /// rearrangement of a nonempty subset of `{1..p-1}` with distinct partial
    /// sums mod `p`, and COVERAGE is complete (all `2^(p-1) - 1` nonempty
    /// subsets appear exactly once). Certifies #475 for this `p` — a finite
    /// confirmation (the question over all primes is the open problem). Pure
    /// integer arithmetic.
    DistinctPartialSums { p: u64, orderings: Vec<Vec<u64>> },
    /// An Erdős #364 certificate: there are no three CONSECUTIVE powerful
    /// integers `n, n+1, n+2` in `[1, n_max]` (a number is powerful iff every
    /// prime in its factorisation appears to exponent `>= 2`). The verifier
    /// re-scans `[2, n_max]` from scratch via a smallest-prime-factor sieve and
    /// confirms no such triple exists. A finite confirmation (the question over
    /// all integers is the open problem). `pairs_seen` is an optional sanity
    /// echo of how many consecutive powerful PAIRS were found (e.g. (8,9)); it
    /// does not gate the verdict.
    PowerfulTriplesNone {
        n_max: u64,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pairs_claimed: Option<u64>,
    },
    /// An Erdős #366 certificate: the complete set, over `[1, n_max]`, of `n`
    /// that are 2-full (powerful: every prime exponent `>= 2`) with `n+1`
    /// 3-full (every prime exponent `>= 3`). The verifier re-scans `[1, n_max]`
    /// via an SPF sieve and confirms `examples` is EXACTLY the set found. An
    /// empty `examples` is a finite confirmation that no such `n` exists in the
    /// range (the question over all integers is open); a nonempty `examples`
    /// exhibits genuine witnesses.
    TwoFullThreeFull { n_max: u64, examples: Vec<u64> },
    /// An Erdős #398 (Brocard / Brocard–Ramanujan) finite-confirmation
    /// certificate: over `[n_min, n_max]`, `n! + 1` is a perfect square for
    /// exactly the known `n ∈ {4,5,7}` and for no other `n`. Each non-exception
    /// `n` carries a witnessing prime `p > n` such that `n! + 1` is a quadratic
    /// non-residue mod `p` (recomputed from scratch with pure modular integer
    /// arithmetic — no bignum, `n!` is never materialised). A finite confirmation
    /// (the conjecture over all `n` is the open problem).
    BrocardNoSquare {
        n_min: u64,
        n_max: u64,
        cases: Vec<BrocardCase>,
    },
    /// An Erdős #306 certificate: each listed reduced `a/b` (with `b`
    /// squarefree) is exhibited as an Egyptian expansion whose denominators are
    /// all products of two distinct primes (squarefree semiprimes), strictly
    /// increasing. The verifier re-checks every expansion with exact integer
    /// arithmetic and confirms the cases are distinct rationals. A per-instance
    /// finite confirmation (the question over all positive rationals is open);
    /// it EXHIBITS genuine decompositions rather than claiming completeness.
    SemiprimeEgyptian { cases: Vec<SemiprimeEgyptianCase> },
}

/// One addition step of an LRAT proof: clause `id` is the listed
/// `literals` (empty = the empty clause = the proof goal), justified by
/// reverse unit propagation over the antecedent clause `hints` in order.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct LratStep {
    pub id: u64,
    pub literals: Vec<i64>,
    pub hints: Vec<u64>,
    /// RAT justification, used only when the direct RUP check fails:
    /// for EVERY db clause containing the negated pivot (the step's
    /// FIRST literal), a `(clause_id, resolvent_hints)` pair whose
    /// resolvent must itself be RUP. Tautological resolvents are
    /// vacuously fine. Deletion lines remain unsupported.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub rat_hints: Vec<(u64, Vec<u64>)>,
}

/// One prime row of an Erdős #203 partial-cover certificate.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CrtCoverRow {
    pub p: u64,
    pub ord2: u64,
    pub ord3: u64,
    pub h: u64,
    pub t_p: u64,
    pub m_mod_p: u64,
    /// `(alpha, beta, gamma, modulus)` with `modulus == h`.
    pub line: [u64; 4],
}

/// One `(k, m)` entry of an Erdős #684 certificate.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct KummerEntry {
    pub k: u64,
    pub m: u64,
}

/// One `(n, f)` case of an Erdős #700 certificate.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MinGcdCase {
    pub n: u64,
    pub f: u64,
}

/// One `(n, x, y, z)` case of an Erdős #242 (Erdős–Straus) certificate:
/// `4/n = 1/x + 1/y + 1/z` with `1 <= x < y < z`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct UnitFractionCase {
    pub n: u64,
    pub x: u64,
    pub y: u64,
    pub z: u64,
}

/// One `(n, p)` case of an Erdős #398 (Brocard) finite-confirmation certificate.
/// For `n ∉ {4,5,7}`, `p` is a prime `> n` that WITNESSES that `n! + 1` is not a
/// perfect square: the verifier recomputes `r = (n! + 1) mod p` and confirms `r`
/// is a quadratic NON-residue mod `p` (Euler's criterion), which forces `n! + 1`
/// to be a non-square (a perfect square is a residue, or `0`, mod every prime).
/// For the three known solutions `n ∈ {4,5,7}`, `p` is ignored and the verifier
/// confirms `n! + 1` IS the recorded perfect square (`25, 121, 5041`).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct BrocardCase {
    pub n: u64,
    #[serde(default)]
    pub p: u64,
}

/// One `(a, b, denominators)` case of an Erdős #306 certificate: an Egyptian
/// expansion `a/b = 1/n_1 + ... + 1/n_k` in which every `n_i` is a product of two
/// DISTINCT primes (a squarefree semiprime), with `b` squarefree and the `n_i`
/// strictly increasing. Verified with exact integer arithmetic.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SemiprimeEgyptianCase {
    pub a: u64,
    pub b: u64,
    pub denominators: Vec<u64>,
}

/// One `(k, N, delta, slots)` entry of an Erdős #1093 deficiency
/// certificate. `n` is a decimal string (up to 38 digits / u128);
/// `slots` is optional — when absent only the count is checked.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DeficiencyEntry {
    pub k: u64,
    pub n: String,
    pub delta: u64,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub slots: Option<Vec<u64>>,
}

impl Witness {
    /// The verifier name (matches the `kind` tag).
    pub fn kind(&self) -> &'static str {
        match self {
            Witness::Sidon { .. } => "sidon",
            Witness::Golomb { .. } => "golomb",
            Witness::Cap { .. } => "cap",
            Witness::Bh { .. } => "bh",
            Witness::Covering { .. } => "covering",
            Witness::ConstantWeight { .. } => "constant_weight",
            Witness::Costas { .. } => "costas",
            Witness::Gf2Sidon { .. } => "gf2_sidon",
            Witness::UnionFree { .. } => "union_free",
            Witness::RookDirections { .. } => "rook_directions",
            Witness::LinearCode { .. } => "linear_code",
            Witness::IntervalProduct { .. } => "interval_product",
            Witness::BalancedColoring { .. } => "balanced_coloring",
            Witness::CrtPartialCover { .. } => "crt_partial_cover",
            Witness::KummerNoCarry { .. } => "kummer_no_carry",
            Witness::MinBinomGcd { .. } => "min_binom_gcd",
            Witness::BinomDeficiency { .. } => "binom_deficiency",
            Witness::BinomExceptionEnum { .. } => "binom_exception_enum",
            Witness::UnsatCert { .. } => "unsat_cert",
            Witness::DiffTriangle { .. } => "diff_triangle",
            Witness::UnitFractionDecomp { .. } => "unit_fraction_decomp",
            Witness::DistinctPartialSums { .. } => "distinct_partial_sums",
            Witness::PowerfulTriplesNone { .. } => "powerful_triples_none",
            Witness::TwoFullThreeFull { .. } => "two_full_three_full",
            Witness::BrocardNoSquare { .. } => "brocard_no_square",
            Witness::SemiprimeEgyptian { .. } => "semiprime_egyptian",
        }
    }
}

/// Verify a difference triangle set: `rows` of strictly increasing
/// non-negative integers, each starting at 0, with every positive within-row
/// pairwise difference GLOBALLY distinct (no difference repeats across the
/// whole set). Reports the scope (the largest mark). `claimed_scope`, when
/// present, must equal the recomputed scope.
pub fn verify_diff_triangle(rows: &[Vec<i64>], claimed_scope: Option<usize>) -> VerifyResult {
    if rows.is_empty() {
        return VerifyResult::fail("empty difference triangle set");
    }
    let mut diffs: HashSet<i64> = HashSet::new();
    let mut diff_count = 0usize;
    let mut scope: i64 = 0;
    for (r, row) in rows.iter().enumerate() {
        if row.len() < 2 {
            return VerifyResult::fail(format!("row {r} has fewer than 2 marks"));
        }
        if row[0] != 0 {
            return VerifyResult::fail(format!("row {r} does not start at 0"));
        }
        // strictly increasing, non-negative
        for w in row.windows(2) {
            if w[1] <= w[0] {
                return VerifyResult::fail(format!("row {r} is not strictly increasing"));
            }
        }
        scope = scope.max(*row.last().unwrap());
        // every within-row positive difference must be globally distinct
        for i in 0..row.len() {
            for j in (i + 1)..row.len() {
                let d = row[j] - row[i];
                if !diffs.insert(d) {
                    return VerifyResult::fail(format!(
                        "difference {d} repeats (row {r}) — not a difference triangle set"
                    ));
                }
                diff_count += 1;
            }
        }
    }
    let scope_usize = scope as usize;
    if let Some(c) = claimed_scope
        && c != scope_usize
    {
        return VerifyResult::fail(format!(
            "verifier passed but scope {scope_usize} != claimed_scope {c}"
        ));
    }
    VerifyResult::ok(format!(
        "difference triangle set: {} rows, scope {scope_usize}, all {diff_count} within-row differences globally distinct",
        rows.len()
    ))
}

/// Verify a witness against its exact verifier, plus the optional
/// `claimed_size` cross-check.
/// Machine-checked novelty: does `new` strictly dominate `prior` for
/// kinds with a natural order? Conservative: kinds without an obvious
/// dominance order return Err (the caller reports "not comparable") —
/// never a silent pass. This is the anti-AI-novelty-judge: dominance is
/// arithmetic, not opinion.
pub fn dominates(new: &Witness, prior: &Witness) -> Result<bool, String> {
    use Witness::*;
    match (new, prior) {
        (
            Sidon {
                n: n1, points: p1, ..
            },
            Sidon {
                n: n2, points: p2, ..
            },
        ) => {
            if n1 != n2 {
                return Err(format!("different n ({n1} vs {n2}); not comparable"));
            }
            Ok(p1.len() > p2.len())
        }
        (Golomb { marks: m1, .. }, Golomb { marks: m2, .. }) => Ok(m1.len() > m2.len()),
        (BalancedColoring { n: n1, r: r1, .. }, BalancedColoring { n: n2, r: r2, .. }) => {
            if r1 != r2 {
                return Err(format!("different r ({r1} vs {r2}); not comparable"));
            }
            Ok(n1 > n2)
        }
        (IntervalProduct { p: p1, cuts: c1 }, IntervalProduct { p: p2, cuts: c2 }) => {
            if p1 == p2 {
                Ok(c1.len() > c2.len())
            } else {
                // a longer chain at ANY prime is a new k-record
                Ok(c1.len() > c2.len())
            }
        }
        _ => Err(format!(
            "no dominance order defined between {} and {}",
            new.kind(),
            prior.kind()
        )),
    }
}

pub fn verify_witness(witness: &Witness) -> VerifyResult {
    match witness {
        Witness::Sidon {
            n,
            points,
            claimed_size,
        } => with_size(verify_sidon(points, *n), points.len(), *claimed_size),
        Witness::Golomb { marks } => verify_golomb(marks),
        Witness::Cap {
            n,
            points,
            claimed_size,
        } => with_size(verify_cap(points, *n), points.len(), *claimed_size),
        Witness::Bh {
            n,
            h,
            points,
            claimed_size,
        } => with_size(verify_bh(points, *n, *h), points.len(), *claimed_size),
        Witness::Covering { v, k, t, blocks } => verify_covering(blocks, *v, *k, *t),
        Witness::IntervalProduct { p, cuts } => verify_interval_product(*p, cuts),
        Witness::BalancedColoring { n, r, edge_colors } => {
            verify_balanced_coloring(*n, *r, edge_colors)
        }
        Witness::CrtPartialCover { m, rows } => verify_crt_partial_cover(m, rows),
        Witness::KummerNoCarry { entries } => verify_kummer_no_carry(entries),
        Witness::MinBinomGcd { cases } => verify_min_binom_gcd(cases),
        Witness::BinomDeficiency { entries } => verify_binom_deficiency(entries),
        Witness::BinomExceptionEnum { k_max, exceptions } => {
            verify_binom_exception_enum(*k_max, exceptions)
        }
        Witness::UnsatCert { cnf, proof } => verify_unsat_cert(cnf, proof),
        Witness::ConstantWeight {
            n,
            d,
            w,
            words,
            claimed_size,
        } => with_size(
            verify_constant_weight(words, *n, *d, *w),
            words.len(),
            *claimed_size,
        ),
        Witness::Costas { perm } => verify_costas(perm),
        Witness::Gf2Sidon {
            elements,
            claimed_size,
        } => with_size(verify_gf2_sidon(elements), elements.len(), *claimed_size),
        Witness::UnionFree {
            n,
            sets,
            claimed_size,
        } => with_size(verify_union_free(*n, sets), sets.len(), *claimed_size),
        Witness::RookDirections {
            n,
            perm,
            claimed_directions,
        } => verify_rook_directions(*n, perm, *claimed_directions),
        Witness::LinearCode {
            q,
            claimed_d,
            generator,
        } => verify_linear_code(generator, *q, *claimed_d),
        Witness::DiffTriangle {
            rows,
            claimed_scope,
        } => verify_diff_triangle(rows, *claimed_scope),
        Witness::UnitFractionDecomp { n_max, cases } => verify_unit_fraction_decomp(*n_max, cases),
        Witness::DistinctPartialSums { p, orderings } => {
            verify_distinct_partial_sums(*p, orderings)
        }
        Witness::PowerfulTriplesNone {
            n_max,
            pairs_claimed,
        } => verify_powerful_triples_none(*n_max, *pairs_claimed),
        Witness::TwoFullThreeFull { n_max, examples } => {
            verify_two_full_three_full(*n_max, examples)
        }
        Witness::BrocardNoSquare {
            n_min,
            n_max,
            cases,
        } => verify_brocard_no_square(*n_min, *n_max, cases),
        Witness::SemiprimeEgyptian { cases } => verify_semiprime_egyptian(cases),
    }
}

/// Erdős #366: verify `examples` is EXACTLY the set of `n` in `[1, n_max]` that
/// are 2-full (powerful: every prime exponent `>= 2`) with `n+1` 3-full (every
/// prime exponent `>= 3`). Re-scans `[1, n_max]` via an SPF sieve (the minimum
/// prime exponent is computed exactly). An empty `examples` is a finite
/// confirmation that no such `n` exists up to `n_max`; a nonempty `examples`
/// exhibits genuine witnesses. Fail-closed: a claimed example that is not such
/// an `n`, or a missing one, aborts.
pub fn verify_two_full_three_full(n_max: u64, examples: &[u64]) -> VerifyResult {
    if n_max < 1 {
        return VerifyResult::fail("n_max must be >= 1");
    }
    if n_max > 200_000_000 {
        return VerifyResult::fail("n_max too large for the in-gate sieve (cap 2e8)");
    }
    let n = (n_max + 1) as usize; // need n+1 too
    let mut spf = vec![0u32; n + 1];
    for i in 2..=n {
        if spf[i] == 0 {
            let mut j = i;
            while j <= n {
                if spf[j] == 0 {
                    spf[j] = i as u32;
                }
                j += i;
            }
        }
    }
    // Minimum prime exponent in the factorisation of m (u64::MAX sentinel for m=1).
    let min_exp = |mut m: usize| -> u64 {
        if m <= 1 {
            return u64::MAX;
        }
        let mut lo = u64::MAX;
        while m > 1 {
            let p = spf[m] as usize;
            let mut e = 0;
            while m.is_multiple_of(p) {
                m /= p;
                e += 1;
            }
            lo = lo.min(e);
        }
        lo
    };
    let mut found: Vec<u64> = Vec::new();
    for m in 1..=(n_max as usize) {
        if min_exp(m) >= 2 && min_exp(m + 1) >= 3 {
            found.push(m as u64);
        }
    }
    let mut claimed = examples.to_vec();
    claimed.sort_unstable();
    if claimed != found {
        return VerifyResult::fail(format!(
            "claimed examples {claimed:?} != the {} actually found in [1, {n_max}]: {found:?}",
            found.len()
        ));
    }
    if found.is_empty() {
        VerifyResult::ok(format!(
            "Erdős #366 finite confirmation: NO 2-full n with n+1 3-full in [1, {n_max}]. \
             The question over all integers is the open problem."
        ))
    } else {
        VerifyResult::ok(format!(
            "Erdős #366: {} genuine witness(es) in [1, {n_max}] — 2-full n with n+1 3-full: {found:?}. \
             Exhibits existence (the set is complete over the range).",
            found.len()
        ))
    }
}

/// Erdős #364: verify there are NO three consecutive powerful integers in
/// `[1, n_max]`. A smallest-prime-factor sieve over `[2, n_max]` makes the
/// powerful test O(log n); the scan is fail-closed (any triple aborts). Finite
/// confirmation (the question over all integers is open). `pairs_claimed`, if
/// present, must equal the count of consecutive powerful pairs found.
pub fn verify_powerful_triples_none(n_max: u64, pairs_claimed: Option<u64>) -> VerifyResult {
    if n_max < 3 {
        return VerifyResult::fail("n_max must be >= 3");
    }
    if n_max > 200_000_000 {
        // Bound the sieve memory/time so the gate stays fast and safe.
        return VerifyResult::fail("n_max too large for the in-gate sieve (cap 2e8)");
    }
    let n = n_max as usize;
    // Smallest-prime-factor sieve.
    let mut spf = vec![0u32; n + 1];
    for i in 2..=n {
        if spf[i] == 0 {
            let mut j = i;
            while j <= n {
                if spf[j] == 0 {
                    spf[j] = i as u32;
                }
                j += i;
            }
        }
    }
    // m is powerful iff every prime in its factorisation has exponent >= 2.
    let is_powerful = |mut m: usize| -> bool {
        if m == 1 {
            return true;
        }
        while m > 1 {
            let p = spf[m] as usize;
            let mut e = 0;
            while m.is_multiple_of(p) {
                m /= p;
                e += 1;
            }
            if e < 2 {
                return false;
            }
        }
        true
    };
    let mut pairs = 0u64;
    let mut prev = is_powerful(1);
    let mut prev2 = false;
    for m in 2..=n {
        let cur = is_powerful(m);
        if cur && prev {
            pairs += 1;
        }
        if cur && prev && prev2 {
            return VerifyResult::fail(format!(
                "found three consecutive powerful integers ending at {m} (#364 would be FALSIFIED)"
            ));
        }
        prev2 = prev;
        prev = cur;
    }
    if let Some(claimed) = pairs_claimed
        && claimed != pairs
    {
        return VerifyResult::fail(format!(
            "pairs_claimed {claimed} != {pairs} consecutive powerful pairs actually found"
        ));
    }
    VerifyResult::ok(format!(
        "Erdős #364 verified for [1, {n_max}]: no three consecutive powerful integers \
         ({pairs} consecutive powerful pairs exist, e.g. 8,9). Finite confirmation; the \
         question over all integers is the open problem."
    ))
}

/// Erdős #475 (Graham distinct-partial-sums): for a fixed prime `p`, verify that
/// `orderings` give, for EVERY nonempty `A ⊆ F_p\{0}`, a rearrangement of `A`
/// whose partial sums are all distinct mod `p`. Fail-closed: a non-prime `p`, an
/// out-of-range element, a non-distinct partial-sum sequence, or incomplete
/// coverage of the `2^(p-1) - 1` nonempty subsets aborts. Certifies #475 for
/// this `p` (a finite confirmation; the question over all primes is open).
pub fn verify_distinct_partial_sums(p: u64, orderings: &[Vec<u64>]) -> VerifyResult {
    let is_prime = |n: u64| -> bool {
        if n < 2 {
            return false;
        }
        let mut d = 2;
        while d * d <= n {
            if n.is_multiple_of(d) {
                return false;
            }
            d += 1;
        }
        true
    };
    if !is_prime(p) {
        return VerifyResult::fail(format!("p = {p} is not prime"));
    }
    // Coverage set: the sorted-subset key of each ordering must enumerate every
    // nonempty subset of {1, .., p-1} exactly once.
    let mut covered: HashSet<Vec<u64>> = HashSet::new();
    for ord in orderings {
        if ord.is_empty() {
            return VerifyResult::fail("empty ordering (A must be nonempty)");
        }
        // Elements in F_p\{0} and distinct (a genuine subset rearrangement).
        let set: HashSet<&u64> = ord.iter().collect();
        if set.len() != ord.len() {
            return VerifyResult::fail("ordering has a repeated element");
        }
        for &a in ord {
            if a == 0 || a >= p {
                return VerifyResult::fail(format!("element {a} not in F_{p}\\{{0}}"));
            }
        }
        // Distinct partial sums mod p.
        let mut seen: HashSet<u64> = HashSet::new();
        let mut acc = 0u64;
        for &a in ord {
            acc = (acc + a) % p;
            if !seen.insert(acc) {
                let mut key: Vec<u64> = ord.clone();
                key.sort_unstable();
                return VerifyResult::fail(format!(
                    "subset {key:?}: ordering {ord:?} has a repeated partial sum mod {p}"
                ));
            }
        }
        let mut key: Vec<u64> = ord.clone();
        key.sort_unstable();
        if !covered.insert(key.clone()) {
            return VerifyResult::fail(format!("subset {key:?} covered more than once"));
        }
    }
    let expected = (1u64 << (p - 1)) - 1; // 2^(p-1) - 1 nonempty subsets of {1..p-1}
    if covered.len() as u64 != expected {
        return VerifyResult::fail(format!(
            "incomplete coverage: {} of {expected} nonempty subsets of F_{p}\\{{0}}",
            covered.len()
        ));
    }
    VerifyResult::ok(format!(
        "Erdős #475 (distinct partial sums) verified for ALL nonempty A ⊆ F_{p}\\{{0}}: \
         {expected} subsets, each orderable with distinct partial sums mod {p}. \
         Finite confirmation; the question over all primes is the open problem."
    ))
}

/// Erdős #242 (Erdős–Straus, distinct variant): verify that `cases` give, for
/// EVERY `n` in `[3, n_max]`, distinct `1 <= x < y < z` with
/// `4/n = 1/x + 1/y + 1/z`. Fail-closed: a gap in `[3, n_max]`, a non-ordered
/// triple, or an inexact equation aborts. Certifies the conjecture for all
/// `3 <= n <= n_max` (a FINITE confirmation; the uniform proof over all `n` is
/// the open problem). Exact `u128` integer arithmetic, no floating point.
pub fn verify_unit_fraction_decomp(n_max: u64, cases: &[UnitFractionCase]) -> VerifyResult {
    if n_max < 3 {
        return VerifyResult::fail("n_max must be >= 3 (the conjecture is stated for n > 2)");
    }
    // Coverage: exactly one case per n in [3, n_max], no gaps, no duplicates.
    let mut seen: HashSet<u64> = HashSet::new();
    for c in cases {
        if c.n < 3 || c.n > n_max {
            return VerifyResult::fail(format!("case n={} is outside [3, {n_max}]", c.n));
        }
        if !seen.insert(c.n) {
            return VerifyResult::fail(format!("duplicate case for n={}", c.n));
        }
        // Distinct, ordered, positive: 1 <= x < y < z.
        if !(1 <= c.x && c.x < c.y && c.y < c.z) {
            return VerifyResult::fail(format!(
                "n={}: triple ({},{},{}) is not 1 <= x < y < z",
                c.n, c.x, c.y, c.z
            ));
        }
        // Exact: 4/n = 1/x + 1/y + 1/z  <=>  4*x*y*z = n*(y*z + x*z + x*y).
        let (n, x, y, z) = (c.n as u128, c.x as u128, c.y as u128, c.z as u128);
        let lhs = 4u128 * x * y * z;
        let rhs = n * (y * z + x * z + x * y);
        if lhs != rhs {
            return VerifyResult::fail(format!(
                "n={}: 4/{} != 1/{}+1/{}+1/{} (exact check failed)",
                c.n, c.n, c.x, c.y, c.z
            ));
        }
    }
    let expected = (n_max - 3 + 1) as usize;
    if seen.len() != expected {
        return VerifyResult::fail(format!(
            "incomplete: covered {} of {expected} values in [3, {n_max}]",
            seen.len()
        ));
    }
    VerifyResult::ok(format!(
        "Erdős–Straus (#242, distinct variant) verified for all 3 <= n <= {n_max}: \
         {expected} exact decompositions 4/n = 1/x+1/y+1/z with x < y < z. \
         Finite confirmation; the uniform proof over all n is the open problem."
    ))
}

/// Erdős #398 (Brocard's problem, `n! + 1 = m^2`): over `[n_min, n_max]`, confirm
/// `n! + 1` is a perfect square for exactly the known `n ∈ {4,5,7}` and for no
/// other `n`. Each non-exception `n` carries a witnessing prime `p > n` and the
/// verifier recomputes `r = (n! + 1) mod p` (iterated modular product — `n!` is
/// never materialised, so no bignum) and confirms via Euler's criterion that `r`
/// is a quadratic NON-residue mod `p`, which forces `n! + 1` to be a non-square.
/// Fail-closed: a non-prime / too-small `p`, a residue `r`, `r = 0`, a wrong
/// known-solution, or incomplete coverage of `[n_min, n_max]` aborts. A finite
/// confirmation (the conjecture over all `n` is the open problem).
pub fn verify_brocard_no_square(n_min: u64, n_max: u64, cases: &[BrocardCase]) -> VerifyResult {
    if n_min < 1 || n_max < n_min {
        return VerifyResult::fail("require 1 <= n_min <= n_max");
    }
    if n_max > 5_000_000 {
        return VerifyResult::fail("n_max too large for the in-gate certificate (cap 5e6)");
    }
    let is_prime = |n: u64| -> bool {
        if n < 2 {
            return false;
        }
        if n.is_multiple_of(2) {
            return n == 2;
        }
        let mut d = 3u64;
        while d * d <= n {
            if n.is_multiple_of(d) {
                return false;
            }
            d += 2;
        }
        true
    };
    // Modular exponentiation in u128 (base, exp already reduced sensibly).
    let mod_pow = |mut base: u128, mut exp: u128, modulus: u128| -> u128 {
        if modulus == 1 {
            return 0;
        }
        let mut result = 1u128;
        base %= modulus;
        while exp > 0 {
            if exp & 1 == 1 {
                result = result * base % modulus;
            }
            exp >>= 1;
            base = base * base % modulus;
        }
        result
    };
    // The three known Brocard solutions: 4!+1=25, 5!+1=121, 7!+1=5041.
    let known: [u64; 3] = [4, 5, 7];
    let mut seen: HashSet<u64> = HashSet::new();
    for c in cases {
        if c.n < n_min || c.n > n_max {
            return VerifyResult::fail(format!("case n={} outside [{n_min}, {n_max}]", c.n));
        }
        if !seen.insert(c.n) {
            return VerifyResult::fail(format!("duplicate case for n={}", c.n));
        }
        if known.contains(&c.n) {
            // Confirm n!+1 IS a perfect square (n <= 7, so n! fits easily).
            let mut fact: u128 = 1;
            for k in 1..=c.n as u128 {
                fact *= k;
            }
            let val = fact + 1;
            let root = (val as f64).sqrt() as u128;
            let mut is_sq = false;
            for m in root.saturating_sub(2)..=root + 2 {
                if m * m == val {
                    is_sq = true;
                    break;
                }
            }
            if !is_sq {
                return VerifyResult::fail(format!(
                    "n={}: {}!+1 = {val} is not a perfect square (expected a known solution)",
                    c.n, c.n
                ));
            }
        } else {
            // Non-exception: a witnessing prime p > n with n!+1 a non-residue mod p.
            let p = c.p;
            if p <= c.n {
                return VerifyResult::fail(format!(
                    "n={}: witnessing prime p={p} must exceed n",
                    c.n
                ));
            }
            if !is_prime(p) {
                return VerifyResult::fail(format!("n={}: p={p} is not prime", c.n));
            }
            let pm = p as u128;
            let mut fact = 1u128;
            for k in 1..=c.n {
                fact = fact * (k as u128) % pm;
            }
            let r = (fact + 1) % pm;
            if r == 0 {
                return VerifyResult::fail(format!(
                    "n={}: n!+1 ≡ 0 (mod {p}); that does not prove a non-square",
                    c.n
                ));
            }
            // Euler's criterion: r is a non-residue iff r^((p-1)/2) ≡ -1 (mod p).
            let legendre = mod_pow(r, (pm - 1) / 2, pm);
            if legendre != pm - 1 {
                return VerifyResult::fail(format!(
                    "n={}: r={r} is a quadratic residue mod {p} \
                     (r^((p-1)/2) mod p = {legendre}, need {}); n!+1 not shown non-square",
                    c.n,
                    pm - 1
                ));
            }
        }
    }
    let expected = (n_max - n_min + 1) as usize;
    if seen.len() != expected {
        return VerifyResult::fail(format!(
            "incomplete: covered {} of {expected} values in [{n_min}, {n_max}]",
            seen.len()
        ));
    }
    let exceptions: Vec<u64> = known
        .iter()
        .copied()
        .filter(|&n| n >= n_min && n <= n_max)
        .collect();
    VerifyResult::ok(format!(
        "Erdős #398 (Brocard) verified for all {n_min} <= n <= {n_max}: n!+1 is a perfect \
         square exactly for n in {exceptions:?}, and a non-square (quadratic-non-residue \
         certificate mod a witnessing prime) for every other n. Finite confirmation; the \
         conjecture over all n is the open problem."
    ))
}

/// Erdős #306: verify each listed reduced `a/b` (with `b` squarefree) is exhibited
/// as an Egyptian expansion `a/b = sum 1/n_i` whose denominators `n_i` are all
/// products of two DISTINCT primes (squarefree semiprimes), strictly increasing.
/// Exact integer arithmetic (reduced-fraction accumulation, no floats). Fail-closed:
/// a non-squarefree `b`, a denominator that is not a distinct-prime product, a
/// non-increasing list, a mismatched sum, or a duplicated rational aborts. A
/// per-instance finite confirmation (the question over all positive rationals is open).
pub fn verify_semiprime_egyptian(cases: &[SemiprimeEgyptianCase]) -> VerifyResult {
    if cases.is_empty() {
        return VerifyResult::fail("no cases supplied");
    }
    let gcd = |mut a: u64, mut b: u64| -> u64 {
        while b != 0 {
            let t = a % b;
            a = b;
            b = t;
        }
        a
    };
    let gcd128 = |mut a: u128, mut b: u128| -> u128 {
        while b != 0 {
            let t = a % b;
            a = b;
            b = t;
        }
        a
    };
    // n is a squarefree semiprime iff it factors as p*q with p<q both prime
    // (exactly two distinct prime factors, each to exponent 1).
    let is_squarefree_semiprime = |n: u64| -> bool {
        if n < 6 {
            return false;
        }
        let mut m = n;
        let mut factors = 0u32;
        let mut d = 2u64;
        while d * d <= m {
            if m.is_multiple_of(d) {
                let mut e = 0u32;
                while m.is_multiple_of(d) {
                    m /= d;
                    e += 1;
                }
                if e != 1 {
                    return false; // a repeated prime => not squarefree
                }
                factors += 1;
            }
            d += 1;
        }
        if m > 1 {
            factors += 1;
        }
        factors == 2
    };
    let is_squarefree = |mut n: u64| -> bool {
        let mut d = 2u64;
        while d * d <= n {
            if n.is_multiple_of(d) {
                n /= d;
                if n.is_multiple_of(d) {
                    return false;
                }
            } else {
                d += 1;
            }
        }
        true
    };
    let mut seen: HashSet<(u64, u64)> = HashSet::new();
    for c in cases {
        if c.a == 0 || c.b == 0 {
            return VerifyResult::fail("a and b must be positive");
        }
        let g = gcd(c.a, c.b);
        let (ar, br) = (c.a / g, c.b / g);
        if !is_squarefree(br) {
            return VerifyResult::fail(format!(
                "{}/{}: reduced denominator {br} is not squarefree",
                c.a, c.b
            ));
        }
        if !seen.insert((ar, br)) {
            return VerifyResult::fail(format!("duplicate rational {ar}/{br}"));
        }
        let d = &c.denominators;
        if d.is_empty() {
            return VerifyResult::fail(format!("{ar}/{br}: empty denominator list"));
        }
        for w in d.windows(2) {
            if w[0] >= w[1] {
                return VerifyResult::fail(format!(
                    "{ar}/{br}: denominators must be strictly increasing"
                ));
            }
        }
        for &ni in d {
            if !is_squarefree_semiprime(ni) {
                return VerifyResult::fail(format!(
                    "{ar}/{br}: denominator {ni} is not a product of two distinct primes"
                ));
            }
        }
        // Exact sum 1/n_i via reduced-fraction accumulation (u128, gcd each step).
        let mut sn: u128 = 0;
        let mut sd: u128 = 1;
        for &ni in d {
            let ni = ni as u128;
            let nn = sn.checked_mul(ni).and_then(|v| v.checked_add(sd));
            let nd = sd.checked_mul(ni);
            match (nn, nd) {
                (Some(nn), Some(nd)) => {
                    let g = gcd128(nn, nd).max(1);
                    sn = nn / g;
                    sd = nd / g;
                }
                _ => {
                    return VerifyResult::fail(format!(
                        "{ar}/{br}: denominator product overflow (expansion too long/large)"
                    ));
                }
            }
        }
        // Compare sn/sd to ar/br exactly via cross-multiplication (checked).
        let lhs = sn.checked_mul(br as u128);
        let rhs = (ar as u128).checked_mul(sd);
        match (lhs, rhs) {
            (Some(l), Some(r)) if l == r => {}
            (Some(_), Some(_)) => {
                return VerifyResult::fail(format!(
                    "{ar}/{br}: sum of 1/n_i = {sn}/{sd} != {ar}/{br}"
                ));
            }
            _ => {
                return VerifyResult::fail(format!("{ar}/{br}: overflow comparing the exact sum"));
            }
        }
    }
    VerifyResult::ok(format!(
        "Erdős #306 verified: {} reduced a/b (b squarefree) each exhibited as an Egyptian \
         expansion into distinct squarefree-semiprime unit fractions. Per-instance finite \
         confirmation; the question over all positive rationals is the open problem.",
        cases.len()
    ))
}

/// A claim parsed from a finding's free-text assertion into the structured,
/// frozen-verifiable shape needed to BIND it to a witness. Deliberately
/// conservative: `parse_claim` returns `None` for anything it cannot read
/// unambiguously, so an unrecognized assertion is never faithful (fail-closed).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ParsedClaim {
    /// The witness kind keyword found in the assertion (e.g. "sidon").
    pub kind: String,
    /// The ambient dimension / order `n`, reconciled from the OEIS order
    /// `a(N)` and/or an ambient literal (`{0,1}^N` / `GF(2)^N` / `F_3^N`).
    /// `None` only when the assertion states neither.
    pub ambient_n: Option<usize>,
    /// The claimed size / order bound `k`.
    pub bound: usize,
    /// `true` when the claim is an equality (`= k` / `exactly k`), `false`
    /// for a lower bound (`>= k` / `at least k`). Only lower bounds and
    /// matched equalities are admissible.
    pub exact: bool,
    /// The B_h order `h` (from `B_<h>` / `<h>-fold`), when stated. Bound to the
    /// witness `h` for `bh` claims; required for B_h floor-admission.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub h: Option<usize>,
    /// The constant-weight code distance `d` and weight `w` (from the
    /// `A(n,d,w)` signature), when stated. Both bound to the witness for
    /// `constant_weight` floor-admission.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub d: Option<usize>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub w: Option<usize>,
}

/// The frozen faithfulness verdict: does `witness` ESTABLISH the claim in
/// `assertion_text`? This is the load-bearing, un-forgeable check the
/// exact-lane auto-admission rests on. `verify_witness` only confirms a
/// witness is INTERNALLY valid (a genuine Sidon set of size `points.len()`);
/// it never reads the assertion, so an INFLATED assertion ("a(20) >= 2500")
/// over a valid-but-weaker witness (a real Sidon set of 1989 points) would
/// pass `verify_witness`. `claim_witness_faithful` closes that: it re-derives
/// faithfulness from frozen inputs (the parsed assertion + the witness
/// structure), never from the drafter-set `match_to_claim.matches` flag an
/// agent can author. `faithful` is true only when the witness both verifies
/// AND its parameters meet/exceed the parsed claim.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Faithfulness {
    pub faithful: bool,
    pub reasons: Vec<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub parsed: Option<ParsedClaim>,
}

/// Leading `usize` from a string slice after skipping ASCII whitespace.
fn leading_usize(s: &str) -> Option<usize> {
    let s = s.trim_start();
    let digits: String = s.chars().take_while(|c| c.is_ascii_digit()).collect();
    if digits.is_empty() {
        None
    } else {
        digits.parse().ok()
    }
}

/// The `usize` immediately following the EARLIEST occurrence of any `needle`
/// (the headline bound, so a trailing "(was N)" aside cannot override it).
fn usize_after_any(hay: &str, needles: &[&str]) -> Option<usize> {
    let mut best: Option<(usize, usize)> = None; // (value, position)
    for needle in needles {
        if let Some(idx) = hay.find(needle)
            && let Some(v) = leading_usize(&hay[idx + needle.len()..])
            && best.map(|(_, p)| idx < p).unwrap_or(true)
        {
            best = Some((v, idx));
        }
    }
    best.map(|(v, _)| v)
}

/// The `usize` inside the first `a(N)` group (the OEIS order/index form),
/// e.g. `a(20)` -> `20`. The match requires a literal `a(` so a sequence id
/// like `a309370` (no paren) is not mistaken for an order.
fn order_in_a_paren(text: &str) -> Option<usize> {
    text.find("a(").and_then(|i| leading_usize(&text[i + 2..]))
}

/// The `usize` of an EQUALITY / optimality marker: `exactly N`, or a standalone
/// `= N` whose `=` is NOT part of a `>=` / `<=` / `!=` / `==` operator. A
/// witness establishes a lower bound, never an equality, so any such marker is
/// a fail-closed signal (and a `= N` headline beside an `at least k` clause is
/// the dual-bound inflation the exact lane must reject).
fn equality_bound(text: &str) -> Option<usize> {
    if let Some(v) = usize_after_any(text, &["exactly "]) {
        return Some(v);
    }
    let mut from = 0;
    while let Some(rel) = text[from..].find('=') {
        let idx = from + rel;
        let prev = text[..idx].chars().last();
        let compound = matches!(
            prev,
            Some('>') | Some('<') | Some('!') | Some('=') | Some('\u{2265}') | Some('\u{2264}')
        );
        if !compound && let Some(v) = leading_usize(&text[idx + 1..]) {
            return Some(v);
        }
        from = idx + 1;
    }
    None
}

/// The B_h order `h` from the standard subscript form `b_<h>` and/or the
/// `<h>-fold` form. Disagreeing signals -> `None` (fail closed via the
/// mandatory bind). `b_h` with a literal `h` (no digit) yields `None`.
fn bh_order(text: &str) -> Option<usize> {
    let subscript = text.find("b_").and_then(|i| leading_usize(&text[i + 2..]));
    let fold = text.find("-fold").and_then(|i| {
        let pre: String = text[..i]
            .chars()
            .rev()
            .take_while(|c| c.is_ascii_digit())
            .collect();
        pre.chars().rev().collect::<String>().parse().ok()
    });
    match (subscript, fold) {
        (Some(a), Some(b)) if a != b => None,
        (Some(a), _) => Some(a),
        (None, Some(b)) => Some(b),
        (None, None) => None,
    }
}

/// The constant-weight `A(n, d, w)` triple from the first `a(...)` group that
/// holds exactly three comma-separated integers. `None` when the signature is
/// absent or malformed (so `(d, w)` go unbound and the claim routes to review).
fn cw_params(text: &str) -> Option<(usize, usize, usize)> {
    let i = text.find("a(")?;
    let rest = &text[i + 2..];
    let close = rest.find(')')?;
    let parts: Vec<&str> = rest[..close].split(',').collect();
    if parts.len() != 3 {
        return None;
    }
    Some((
        parts[0].trim().parse().ok()?,
        parts[1].trim().parse().ok()?,
        parts[2].trim().parse().ok()?,
    ))
}

/// Parse a finding assertion into a [`ParsedClaim`]. Conservative and
/// fail-closed: recognizes only the lower-bound forms the exact lane admits,
/// and returns `None` on any ambiguity (no kind keyword, no parseable bound,
/// an equality/optimality marker, two disagreeing dimension signals, or a
/// lower bound co-occurring with an equality marker).
pub fn parse_claim(assertion_text: &str) -> Option<ParsedClaim> {
    let text = assertion_text.to_lowercase();

    // Witness-kind keyword. Order matters: check the more specific ones first.
    let kind = if text.contains("gf(2)") && text.contains("sidon") {
        "gf2_sidon"
    } else if text.contains("sidon") {
        "sidon"
    } else if text.contains("golomb") {
        "golomb"
    } else if text.contains("cap set") || text.contains("cap-set") {
        "cap"
    } else if text.contains("b_h") || text.contains("bh set") || bh_order(&text).is_some() {
        "bh"
    } else if text.contains("constant weight") || text.contains("constant-weight") {
        "constant_weight"
    } else if text.contains("union-free") || text.contains("union free") {
        "union_free"
    } else {
        return None;
    };

    // Dimension / order. Two independent signals: the OEIS order `a(N)` and an
    // ambient-space literal (`{0,1}^N`, `gf(2)^N`, `f_3^N`). Reading the `a(N)`
    // order (not only the literal) is what binds an OEIS "a(20)" claim to the
    // witness even when the prose omits a `{0,1}^20` literal. If BOTH signals
    // are present and DISAGREE the claim is ambiguous -> fail closed.
    let order = order_in_a_paren(&text);
    let literal = ["{0,1}^", "gf(2)^", "f_3^"].iter().find_map(|m| {
        text.find(m)
            .and_then(|i| leading_usize(&text[i + m.len()..]))
    });
    let ambient_n = match (order, literal) {
        (Some(a), Some(b)) if a != b => return None,
        (Some(a), _) => Some(a),
        (None, Some(b)) => Some(b),
        (None, None) => None,
    };

    // Bound: exactly one unambiguous lower bound (`>=`, `≥`, `at least`). An
    // equality / optimality marker (`exactly N`, or a standalone `= N`) is not
    // witness-establishable, and a lower bound co-occurring with one is
    // ambiguous (a `= 2500` headline beside an `at least 5` clause): both fail
    // closed.
    let lower = usize_after_any(&text, &[">=", "\u{2265}", "at least "]);
    let equality = equality_bound(&text);
    let (bound, is_exact) = match (lower, equality) {
        (Some(l), None) => (l, false),
        (None, Some(e)) => (e, true),
        // both present, or neither: ambiguous / unparseable -> fail closed.
        _ => return None,
    };

    // Extra hardness parameters, bound per-kind in claim_witness_faithful.
    let h = bh_order(&text);
    let (d, w) = match cw_params(&text) {
        Some((_, d, w)) => (Some(d), Some(w)),
        None => (None, None),
    };

    Some(ParsedClaim {
        kind: kind.to_string(),
        ambient_n,
        bound,
        exact: is_exact,
        h,
        d,
        w,
    })
}

/// Frozen check that `witness` establishes the claim in `assertion_text`.
/// See [`Faithfulness`] for why this is the un-forgeable core of the exact
/// lane. Fail-closed throughout: any parse miss, kind/dimension mismatch,
/// size shortfall, or internal-validity failure yields `faithful: false`.
pub fn claim_witness_faithful(assertion_text: &str, witness: &Witness) -> Faithfulness {
    verify_witness_with_claim(assertion_text, witness).1
}

/// Verify the witness and bind an exact claim with one mechanical pass.
///
/// Callers that need both results should use this function instead of invoking
/// [`verify_witness`] and [`claim_witness_faithful`] separately. Large exact
/// constructions can make verification expensive; the claim check consumes
/// the result produced here and never reruns the verifier.
pub fn verify_witness_with_claim(
    assertion_text: &str,
    witness: &Witness,
) -> (VerifyResult, Faithfulness) {
    let verification = verify_witness(witness);
    let faithfulness =
        claim_witness_faithful_from_verification(assertion_text, witness, &verification);
    (verification, faithfulness)
}

fn claim_witness_faithful_from_verification(
    assertion_text: &str,
    witness: &Witness,
    verification: &VerifyResult,
) -> Faithfulness {
    let mut reasons = Vec::new();

    let Some(parsed) = parse_claim(assertion_text) else {
        reasons.push(
            "assertion does not parse to a recognized exact-lane claim (kind keyword + a single \
             unambiguous >=/exactly bound); routes to review"
                .to_string(),
        );
        return Faithfulness {
            faithful: false,
            reasons,
            parsed: None,
        };
    };

    // The witness must be internally valid first (a genuine Sidon set, etc.).
    if !verification.ok {
        reasons.push(format!("witness does not verify: {}", verification.message));
        return Faithfulness {
            faithful: false,
            reasons,
            parsed: Some(parsed),
        };
    }

    // Kind must match the witness variant.
    if parsed.kind != witness.kind() {
        reasons.push(format!(
            "claim kind '{}' does not match witness kind '{}'",
            parsed.kind,
            witness.kind()
        ));
        return Faithfulness {
            faithful: false,
            reasons,
            parsed: Some(parsed),
        };
    }

    // A construction witness establishes a LOWER bound (a(n) >= size). An
    // equality / optimality claim (`=` / `exactly`) additionally asserts that
    // no larger object exists, which a single witness cannot prove; route it to
    // review rather than admit it on the witness alone.
    if parsed.exact {
        reasons.push(
            "equality/optimality claim (= / exactly) is not establishable by a construction \
             witness (which proves only a lower bound); routes to review"
                .to_string(),
        );
        return Faithfulness {
            faithful: false,
            reasons,
            parsed: Some(parsed),
        };
    }

    // The witness's size/order must meet the claimed bound AND the claimed
    // dimension must bind to the witness. Every size/order-bearing kind MUST
    // carry a parsed dimension (the `a(N)` order or an ambient literal); a
    // dimensioned claim that omits it is the omit-dimension bypass (a small
    // witness backing an `a(20)` headline) and routes to review.
    let dim_n_witness = |n: usize| -> Option<String> {
        match parsed.ambient_n {
            None => Some(
                "dimensioned claim states no ambient dimension (a(N) / {0,1}^N / gf(2)^N); \
                 routes to review"
                    .to_string(),
            ),
            Some(c) if c != n => Some(format!(
                "claim ambient dimension n={c} does not match witness n={n}"
            )),
            Some(_) => None,
        }
    };

    // The floor admits a kind only when EVERY witness-defining parameter that
    // changes a record's hardness is parsed from the assertion and bound to the
    // witness — not just the ambient dimension `n`. A third adversarial review
    // showed binding `n` alone is insufficient: verify_witness checks a witness
    // against its OWN author-set h/d/w, so an EASY witness (B_2, or A(n,2,1))
    // could back a HARD headline (B_3, or A(n,10,8)). B_h now binds the order
    // `h`, constant-weight binds `(d, w)`; both route to review when the
    // parameter is unstated. Golomb (a min-length problem) still has no sound
    // witness->lower-bound binding and routes to review.
    let size: usize = match witness {
        Witness::Sidon { n, points, .. } | Witness::Cap { n, points, .. } => {
            if let Some(r) = dim_n_witness(*n) {
                reasons.push(r);
                return Faithfulness {
                    faithful: false,
                    reasons,
                    parsed: Some(parsed),
                };
            }
            points.len()
        }
        Witness::UnionFree { n, sets, .. } => {
            if let Some(r) = dim_n_witness(*n) {
                reasons.push(r);
                return Faithfulness {
                    faithful: false,
                    reasons,
                    parsed: Some(parsed),
                };
            }
            sets.len()
        }
        Witness::Gf2Sidon { elements, .. } => {
            // The claimed dimension N is mandatory, and every element must live
            // in GF(2)^N (no set bit at index >= N). A witness in GF(2)^12 must
            // NOT establish an a(5) claim; the element-fit check binds it.
            let Some(claim_n) = parsed.ambient_n else {
                reasons.push(
                    "GF(2)-Sidon claim states no dimension N (a(N) / gf(2)^N); routes to review"
                        .to_string(),
                );
                return Faithfulness {
                    faithful: false,
                    reasons,
                    parsed: Some(parsed),
                };
            };
            if claim_n >= 64 || elements.iter().any(|e| (*e >> claim_n) != 0) {
                reasons.push(format!(
                    "witness has an element outside GF(2)^{claim_n}; it does not establish a(N) \
                     at that dimension"
                ));
                return Faithfulness {
                    faithful: false,
                    reasons,
                    parsed: Some(parsed),
                };
            }
            elements.len()
        }
        Witness::Bh { n, h, points, .. } => {
            // B_h binds the ambient n AND the order h (a B_3 set admits strictly
            // fewer points than B_2). h is mandatory and must match the witness;
            // an unstated or mismatched h routes to review.
            if let Some(r) = dim_n_witness(*n) {
                reasons.push(r);
                return Faithfulness {
                    faithful: false,
                    reasons,
                    parsed: Some(parsed),
                };
            }
            match parsed.h {
                Some(ch) if ch == *h => {}
                Some(ch) => {
                    reasons.push(format!(
                        "claim B_{ch} does not match witness B_{h} (the order h binds the record)"
                    ));
                    return Faithfulness {
                        faithful: false,
                        reasons,
                        parsed: Some(parsed),
                    };
                }
                None => {
                    reasons.push(
                        "B_h claim does not state the order h (B_<h> / <h>-fold); routes to review"
                            .to_string(),
                    );
                    return Faithfulness {
                        faithful: false,
                        reasons,
                        parsed: Some(parsed),
                    };
                }
            }
            points.len()
        }
        Witness::ConstantWeight { n, d, w, words, .. } => {
            // A constant-weight record A(n,d,w) binds the ambient n AND the
            // minimum distance d and weight w; a trivial A(n,2,1) witness must
            // not back a hard A(n,10,8) claim. Both d and w are mandatory (from
            // the `A(n,d,w)` signature) and must match the witness.
            if let Some(r) = dim_n_witness(*n) {
                reasons.push(r);
                return Faithfulness {
                    faithful: false,
                    reasons,
                    parsed: Some(parsed),
                };
            }
            match (parsed.d, parsed.w) {
                (Some(cd), Some(cw)) if cd == *d && cw == *w => {}
                (Some(cd), Some(cw)) => {
                    reasons.push(format!(
                        "claim A(n,{cd},{cw}) does not match witness A(n,{d},{w}) (d,w bind the record)"
                    ));
                    return Faithfulness {
                        faithful: false,
                        reasons,
                        parsed: Some(parsed),
                    };
                }
                _ => {
                    reasons.push(
                        "constant-weight claim does not state (d,w) as A(n,d,w); routes to review"
                            .to_string(),
                    );
                    return Faithfulness {
                        faithful: false,
                        reasons,
                        parsed: Some(parsed),
                    };
                }
            }
            words.len()
        }
        Witness::Golomb { .. } => {
            // A Golomb claim is a MIN-length problem (a(n) <= length); a ruler
            // witness does not establish a >= lower bound the same way, and no
            // sound witness->claim binding is defined here. Route to review.
            reasons.push(
                "golomb claims are not floor-admissible (no sound witness->bound binding \
                 defined); routes to review"
                    .to_string(),
            );
            return Faithfulness {
                faithful: false,
                reasons,
                parsed: Some(parsed),
            };
        }
        // Any other variant is outside the size/order-bearing exact lane.
        _ => {
            reasons.push(format!(
                "witness kind '{}' is not an exact-lane size/order claim",
                witness.kind()
            ));
            return Faithfulness {
                faithful: false,
                reasons,
                parsed: Some(parsed),
            };
        }
    };

    if size < parsed.bound {
        reasons.push(format!(
            "witness size/order {size} does not establish the claimed >= {}",
            parsed.bound
        ));
        return Faithfulness {
            faithful: false,
            reasons,
            parsed: Some(parsed),
        };
    }

    Faithfulness {
        faithful: true,
        reasons,
        parsed: Some(parsed),
    }
}

/// The canonical, WITNESS-DERIVED verified claim for a floor-admissible witness:
/// exactly the lower bound the witness structurally establishes, independent of
/// the author's assertion prose. Surfaces should DISPLAY this as the verified
/// `machine_verified` claim (with the prose shown only as an unverified
/// description), so author prose cannot puff a true bound into a false headline.
/// `None` for kinds that are not floor-admissible. Mirrors the binding in
/// `claim_witness_faithful` (kind, n, the bound-defining parameters, size).
pub fn canonical_claim(witness: &Witness) -> Option<String> {
    match witness {
        Witness::Sidon { n, points, .. } => Some(format!(
            "Sidon set: a({n}) >= {} (a Sidon set of {} points in {{0,1}}^{n})",
            points.len(),
            points.len()
        )),
        Witness::Cap { n, points, .. } => Some(format!(
            "cap set: a({n}) >= {} (a cap set of {} points in F_3^{n})",
            points.len(),
            points.len()
        )),
        Witness::Gf2Sidon { elements, .. } => {
            // The witness lives in GF(2)^n for n = the widest element's bit
            // width; that is the strongest (smallest-n) true statement.
            let n = elements
                .iter()
                .map(|e| (64 - e.leading_zeros()) as usize)
                .max()
                .unwrap_or(0);
            Some(format!(
                "GF(2)-Sidon set: a({n}) >= {} (a Sidon set of {} elements in GF(2)^{n})",
                elements.len(),
                elements.len()
            ))
        }
        Witness::UnionFree { n, sets, .. } => Some(format!(
            "union-free family: a({n}) >= {} (a union-free family of {} subsets of {{1..{n}}})",
            sets.len(),
            sets.len()
        )),
        Witness::Bh { n, h, points, .. } => Some(format!(
            "B_{h} set: a({n}) >= {} (a B_{h} set of {} points in {{0,1}}^{n})",
            points.len(),
            points.len()
        )),
        Witness::ConstantWeight { n, d, w, words, .. } => Some(format!(
            "constant-weight code: A({n},{d},{w}) >= {} ({} codewords of length {n}, weight {w}, min distance {d})",
            words.len(),
            words.len()
        )),
        // Not floor-admissible (golomb, covering, costas, rook, linear_code, ...).
        _ => None,
    }
}

/// Fold a `claimed_size` cross-check into a verifier result: the witness
/// must pass AND have exactly the claimed number of elements.
fn with_size(mut r: VerifyResult, actual: usize, claimed: Option<usize>) -> VerifyResult {
    if r.ok
        && let Some(c) = claimed
    {
        if actual != c {
            return VerifyResult::fail(format!(
                "verifier passed but construction size {actual} != claimed_size {c}"
            ));
        }
        r.message = format!("{} (size {actual} = claimed)", r.message);
    }
    r
}

// --- combinatorial verifiers ---------------------------------------------

fn binary_points_ok(points: &[Vec<i64>], n: usize) -> Option<VerifyResult> {
    let set: HashSet<&Vec<i64>> = points.iter().collect();
    if set.len() != points.len() {
        return Some(VerifyResult::fail("duplicate points"));
    }
    if !points
        .iter()
        .all(|p| p.len() == n && p.iter().all(|&x| x == 0 || x == 1))
    {
        return Some(VerifyResult::fail(format!("points not binary length-{n}")));
    }
    None
}

/// A Sidon subset of `{0,1}^n` under componentwise integer addition: all
/// pairwise sums `a+b` (`a <= b`) distinct.
pub fn verify_sidon(points: &[Vec<i64>], n: usize) -> VerifyResult {
    if let Some(bad) = binary_points_ok(points, n) {
        return bad;
    }
    let m = points.len();
    if n <= 32 {
        let Some(pair_count) = m
            .checked_add(1)
            .and_then(|next| m.checked_mul(next))
            .map(|value| value / 2)
        else {
            return VerifyResult::fail("pairwise-sum count overflows this platform");
        };
        let expanded = points
            .iter()
            .map(|point| {
                point
                    .iter()
                    .enumerate()
                    .fold(0_u64, |packed, (index, value)| {
                        packed | ((*value as u64) << (2 * index))
                    })
            })
            .collect::<Vec<_>>();
        let mut sums = Vec::new();
        if sums.try_reserve_exact(pair_count).is_err() {
            return VerifyResult::fail("insufficient memory for pairwise-sum check");
        }
        for i in 0..m {
            for j in i..m {
                // Each coordinate occupies two bits and sums to at most two,
                // so ordinary integer addition cannot carry between lanes.
                sums.push(expanded[i] + expanded[j]);
            }
        }
        sums.sort_unstable();
        if sums.windows(2).any(|pair| pair[0] == pair[1]) {
            return VerifyResult::fail("pairwise-sum collision (not Sidon)");
        }
        return VerifyResult::ok(format!(
            "Sidon verified: {m} points, {pair_count} pairwise sums all distinct"
        ));
    }
    let mut sums: HashSet<Vec<i64>> = HashSet::new();
    let mut count = 0usize;
    for i in 0..m {
        for j in i..m {
            let s: Vec<i64> = (0..n).map(|k| points[i][k] + points[j][k]).collect();
            if !sums.insert(s) {
                return VerifyResult::fail("pairwise-sum collision (not Sidon)");
            }
            count += 1;
        }
    }
    VerifyResult::ok(format!(
        "Sidon verified: {m} points, {count} pairwise sums all distinct"
    ))
}

/// Verify a Sidon set in `GF(2)^n` (OEIS A394031): `elements` are integer
/// bitmasks; the set is Sidon iff the elements are distinct and all pairwise
/// XORs are distinct and nonzero (equivalently, no four distinct elements XOR
/// to zero). Mirrors the reference `is_gf2_sidon`; pure integer arithmetic.
#[must_use]
pub fn verify_gf2_sidon(elements: &[u64]) -> VerifyResult {
    let m = elements.len();
    let distinct: HashSet<u64> = elements.iter().copied().collect();
    if distinct.len() != m {
        return VerifyResult::fail("duplicate element (not a set)");
    }
    let mut xors: HashSet<u64> = HashSet::new();
    let mut count = 0usize;
    for i in 0..m {
        for j in (i + 1)..m {
            let x = elements[i] ^ elements[j];
            if x == 0 {
                return VerifyResult::fail("zero XOR (equal elements)");
            }
            if !xors.insert(x) {
                return VerifyResult::fail("pairwise-XOR collision (not a GF(2) Sidon set)");
            }
            count += 1;
        }
    }
    VerifyResult::ok(format!(
        "GF(2)-Sidon verified: {m} elements, {count} pairwise XORs all distinct"
    ))
}

/// Greatest common divisor of two non-negative integers (0 maps to 1 so a
/// normalized direction class is always well-defined).
fn gcd_pos(a: i64, b: i64) -> i64 {
    let (mut a, mut b) = (a.abs(), b.abs());
    while b != 0 {
        let t = b;
        b = a % b;
        a = t;
    }
    if a == 0 { 1 } else { a }
}

/// Verify a union-free family (OEIS A347025): `sets` are nonempty subsets of
/// `{1..n}` and no member is the union of a sub-collection of the others.
/// Polynomial check: a member C is expressible iff the union of every OTHER
/// member that is a subset of C equals C (any super-C member would overshoot).
/// Certifies the lower bound a(n) >= |sets| only.
#[must_use]
pub fn verify_union_free(n: usize, sets: &[Vec<u32>]) -> VerifyResult {
    if n == 0 || n > 63 {
        return VerifyResult::fail("n out of range (1..=63)");
    }
    let mut masks: Vec<u64> = Vec::with_capacity(sets.len());
    for s in sets {
        if s.is_empty() {
            return VerifyResult::fail("empty set (members must be nonempty)");
        }
        let mut m = 0u64;
        for &e in s {
            if e < 1 || (e as usize) > n {
                return VerifyResult::fail(format!("element {e} out of {{1..{n}}}"));
            }
            m |= 1u64 << (e - 1);
        }
        masks.push(m);
    }
    let distinct: HashSet<u64> = masks.iter().copied().collect();
    if distinct.len() != masks.len() {
        return VerifyResult::fail("duplicate set (members must be distinct)");
    }
    for (i, &c) in masks.iter().enumerate() {
        let mut u = 0u64;
        for (j, &s) in masks.iter().enumerate() {
            if i != j && (s & c) == s {
                u |= s;
            }
        }
        if u == c {
            return VerifyResult::fail(
                "a member is the union of a sub-collection of the others (not union-free)",
            );
        }
    }
    VerifyResult::ok(format!(
        "union-free verified: {} sets over {{1..{n}}}, no member is a union of others",
        masks.len()
    ))
}

/// Verify a non-attacking rook placement (OEIS A321531): `perm` is a
/// permutation of `1..=n` (one rook per row, distinct columns), and the count
/// of distinct direction classes `sorted(|Δcol|,|Δrow|)/gcd` over all rook
/// pairs equals `claimed` (when given). Certifies the lower bound a(n) >=
/// count only.
#[must_use]
pub fn verify_rook_directions(n: usize, perm: &[i64], claimed: Option<usize>) -> VerifyResult {
    if perm.len() != n {
        return VerifyResult::fail("perm length != n");
    }
    let mut seen = vec![false; n + 1];
    for &c in perm {
        if c < 1 || (c as usize) > n {
            return VerifyResult::fail("column out of 1..=n");
        }
        if seen[c as usize] {
            return VerifyResult::fail("repeated column (attacking rooks)");
        }
        seen[c as usize] = true;
    }
    let mut classes: HashSet<(i64, i64)> = HashSet::new();
    for i in 0..n {
        for j in (i + 1)..n {
            let drow = (j as i64) - (i as i64);
            let dcol = perm[j] - perm[i];
            let g = gcd_pos(dcol, drow);
            let (a, b) = (dcol.abs() / g, drow.abs() / g);
            classes.insert(if a <= b { (a, b) } else { (b, a) });
        }
    }
    let count = classes.len();
    if let Some(cl) = claimed
        && count != cl
    {
        return VerifyResult::fail(format!("direction count {count} != claimed {cl}"));
    }
    VerifyResult::ok(format!(
        "rook-directions verified: {n} non-attacking rooks realize {count} distinct direction classes"
    ))
}

/// A Golomb ruler: integer marks with all `C(m,2)` pairwise differences
/// distinct.
/// Verify an Erdős #1056 cut-equality certificate: a prime `p` and
/// strictly increasing cuts `c_0 < ... < c_k` such that every consecutive
/// interval `(c_{i-1}, c_i]` has integer product `== 1 (mod p)`. Pure
/// modular arithmetic — deterministic and total, no search.
/// Erdős #617 witness shape: a balanced r-coloring of K_n. Checks that
/// every edge {i,j} (i<j, 0-indexed) is colored in 1..=r and that every
/// (r+1)-subset of vertices sees ALL r colors among its internal edges.
pub fn verify_balanced_coloring(
    n: usize,
    r: usize,
    edge_colors: &std::collections::BTreeMap<String, u32>,
) -> VerifyResult {
    if r < 2 || n < r + 1 {
        return VerifyResult::fail(format!("need r >= 2 and n >= r+1 (got n={n}, r={r})"));
    }
    // Dense lookup table from the string-keyed map.
    let mut color = vec![vec![0u32; n]; n];
    for (key, &c) in edge_colors {
        let Some((a, b)) = key.split_once(',') else {
            return VerifyResult::fail(format!("bad edge key '{key}' (want \"i,j\")"));
        };
        let (Ok(i), Ok(j)) = (a.trim().parse::<usize>(), b.trim().parse::<usize>()) else {
            return VerifyResult::fail(format!("bad edge key '{key}'"));
        };
        if i >= n || j >= n || i >= j {
            return VerifyResult::fail(format!("edge '{key}' out of range or not i<j for n={n}"));
        }
        if c == 0 || c as usize > r {
            return VerifyResult::fail(format!("edge '{key}' color {c} outside 1..={r}"));
        }
        color[i][j] = c;
    }
    for (i, row) in color.iter().enumerate() {
        for (j, &c) in row.iter().enumerate().skip(i + 1) {
            if c == 0 {
                return VerifyResult::fail(format!("edge {i},{j} is uncolored"));
            }
        }
    }
    // Every (r+1)-subset must see all r colors. Iterate subsets via a
    // simple combinations walker (k = r+1).
    let k = r + 1;
    let mut idx: Vec<usize> = (0..k).collect();
    let mut checked = 0u64;
    loop {
        let mut seen = vec![false; r + 1];
        for x in 0..k {
            for y in (x + 1)..k {
                seen[color[idx[x]][idx[y]] as usize] = true;
            }
        }
        if let Some(missing) = (1..=r).find(|&c| !seen[c]) {
            return VerifyResult::fail(format!("subset {:?} sees no edge of color {missing}", idx));
        }
        checked += 1;
        // next combination
        let mut pos = k;
        while pos > 0 {
            pos -= 1;
            if idx[pos] != pos + n - k {
                idx[pos] += 1;
                for q in (pos + 1)..k {
                    idx[q] = idx[q - 1] + 1;
                }
                break;
            }
            if pos == 0 {
                return VerifyResult::ok(format!(
                    "balanced {r}-coloring of K_{n} verified: {checked} {k}-subsets each see all {r} colors"
                ));
            }
        }
    }
}

pub fn verify_interval_product(p: u64, cuts: &[u64]) -> VerifyResult {
    if !is_prime(p) {
        return VerifyResult::fail(format!("modulus p={p} must be prime"));
    }
    if cuts.len() < 2 {
        return VerifyResult::fail("need at least two cuts (one interval)");
    }
    for w in cuts.windows(2) {
        if w[0] >= w[1] {
            return VerifyResult::fail("cuts must be strictly increasing");
        }
    }
    for w in cuts.windows(2) {
        let mut prod: u64 = 1;
        for m in (w[0] + 1)..=w[1] {
            prod = ((prod as u128 * (m % p) as u128) % p as u128) as u64;
        }
        if prod != 1 {
            return VerifyResult::fail(format!(
                "interval ({}, {}] has product {prod} mod {p} != 1",
                w[0], w[1]
            ));
        }
    }
    VerifyResult::ok(format!(
        "Erdos #1056 certificate: prime p={p}, {} consecutive interval(s) each with product 1 mod p",
        cuts.len() - 1
    ))
}

// --- shared exact number theory -------------------------------------------

/// Number of carries when adding `a + b` in base `p` (Kummer's theorem:
/// this equals `v_p(C(a+b, a))`).
fn carries_base_p(mut a: u128, mut b: u128, p: u128) -> u64 {
    let mut carry: u128 = 0;
    let mut count: u64 = 0;
    while a > 0 || b > 0 || carry > 0 {
        let s = a % p + b % p + carry;
        carry = u128::from(s >= p);
        count += carry as u64;
        a /= p;
        b /= p;
    }
    count
}

/// Legendre: `v_p(n!)`.
fn vp_factorial(n: u64, p: u64) -> u64 {
    let mut s = 0u64;
    let mut pk = p;
    while pk <= n {
        s += n / pk;
        pk = pk.saturating_mul(p);
    }
    s
}

/// `v_p(C(n, k))` via Legendre.
fn vp_binom(n: u64, k: u64, p: u64) -> u64 {
    vp_factorial(n, p) - vp_factorial(k, p) - vp_factorial(n - k, p)
}

/// `v_p(n)` for `n >= 1`.
fn vp_of(mut n: u64, p: u64) -> u64 {
    let mut v = 0u64;
    while n.is_multiple_of(p) {
        n /= p;
        v += 1;
    }
    v
}

fn gcd_u64(mut a: u64, mut b: u64) -> u64 {
    while b != 0 {
        let t = a % b;
        a = b;
        b = t;
    }
    a
}

/// Primes up to `n` inclusive (trial division; `n` is small here).
fn primes_upto(n: u64) -> Vec<u64> {
    (2..=n).filter(|&q| is_prime(q)).collect()
}

/// Parse a decimal string into u128 (guard: 1..=38 digits, all ASCII).
fn parse_decimal_u128(s: &str) -> Result<u128, String> {
    if s.is_empty() || s.len() > 38 || !s.bytes().all(|b| b.is_ascii_digit()) {
        return Err(format!("`{s}` is not a 1..=38 digit decimal string"));
    }
    s.parse::<u128>().map_err(|e| format!("parse `{s}`: {e}"))
}

/// A decimal string mod a small modulus, by digit streaming — handles
/// integers far beyond u128 without big-int arithmetic.
fn decimal_mod(s: &str, m: u64) -> Result<u64, String> {
    if s.is_empty() || !s.bytes().all(|b| b.is_ascii_digit()) {
        return Err(format!("`{s}` is not a decimal string"));
    }
    let mut acc: u64 = 0;
    for b in s.bytes() {
        acc = (acc * 10 + u64::from(b - b'0')) % m;
    }
    Ok(acc)
}

/// Multiplicative order of `base` mod prime `p` (`base` not divisible
/// by `p`); iterates at most `p - 1` steps.
fn multiplicative_order(base: u64, p: u64) -> Result<u64, String> {
    if base.is_multiple_of(p) {
        return Err(format!("{base} is 0 mod {p}; order undefined"));
    }
    let mut acc = base % p;
    let mut ord = 1u64;
    while acc != 1 {
        acc = acc * base % p;
        ord += 1;
        if ord >= p {
            return Err(format!("order of {base} mod {p} did not divide p-1"));
        }
    }
    Ok(ord)
}

// --- Erdős #203: partial CRT cover ----------------------------------------

/// Verify an Erdős #203 partial CRT covering certificate. `m` is a
/// decimal string coprime to 6; each row pins a prime `p`, the orders of
/// 2 and 3 mod `p`, `h = lcm(ord2, ord3)`, `t_p = (-m^-1) mod p`,
/// `m mod p`, and an affine line such that `p | 2^k 3^l m + 1` iff
/// `alpha*k + beta*l == gamma (mod h)` — checked exhaustively over
/// `(k, l) in [0, h)^2`. Deterministic and total.
pub fn verify_crt_partial_cover(m: &str, rows: &[CrtCoverRow]) -> VerifyResult {
    if rows.is_empty() {
        return VerifyResult::fail("need at least one prime row");
    }
    match (decimal_mod(m, 2), decimal_mod(m, 3)) {
        (Ok(r2), Ok(r3)) => {
            if r2 == 0 || r3 == 0 {
                return VerifyResult::fail("m must be coprime to 6");
            }
        }
        (Err(e), _) | (_, Err(e)) => return VerifyResult::fail(e),
    }
    for row in rows {
        let p = row.p;
        if !(5..=1_000_000).contains(&p) || !is_prime(p) {
            return VerifyResult::fail(format!("row p={p} must be a prime in [5, 10^6]"));
        }
        let ord2 = match multiplicative_order(2, p) {
            Ok(v) => v,
            Err(e) => return VerifyResult::fail(e),
        };
        let ord3 = match multiplicative_order(3, p) {
            Ok(v) => v,
            Err(e) => return VerifyResult::fail(e),
        };
        if ord2 != row.ord2 || ord3 != row.ord3 {
            return VerifyResult::fail(format!(
                "row p={p}: ord(2)={ord2}, ord(3)={ord3} != claimed ({}, {})",
                row.ord2, row.ord3
            ));
        }
        let h = ord2 / gcd_u64(ord2, ord3) * ord3;
        if h != row.h || row.line[3] != h {
            return VerifyResult::fail(format!(
                "row p={p}: lcm(ord2, ord3)={h} != claimed h={} / line modulus {}",
                row.h, row.line[3]
            ));
        }
        if h > 5_000 {
            return VerifyResult::fail(format!("row p={p}: h={h} exceeds the 5000 guard"));
        }
        let mm = match decimal_mod(m, p) {
            Ok(v) => v,
            Err(e) => return VerifyResult::fail(e),
        };
        if mm != row.m_mod_p || mm == 0 {
            return VerifyResult::fail(format!(
                "row p={p}: m mod p = {mm} != claimed {} (and must be nonzero)",
                row.m_mod_p
            ));
        }
        let t = (p - mod_pow(mm, p - 2, p)) % p;
        if t != row.t_p {
            return VerifyResult::fail(format!(
                "row p={p}: (-m^-1) mod p = {t} != claimed t_p={}",
                row.t_p
            ));
        }
        let (al, be, ga) = (row.line[0], row.line[1], row.line[2]);
        for k in 0..h {
            for l in 0..h {
                let lhs = (mod_pow(2, k, p) * mod_pow(3, l, p) % p * mm % p + 1).is_multiple_of(p);
                let rhs = (al * k + be * l) % h == ga % h; // affine line mod h
                if lhs != rhs {
                    return VerifyResult::fail(format!(
                        "row p={p}: congruence line fails at (k, l) = ({k}, {l})"
                    ));
                }
            }
        }
    }
    VerifyResult::ok(format!(
        "Erdos #203 partial CRT cover: m coprime to 6, {} prime row(s) verified (p | 2^k 3^l m + 1 <=> affine line mod h)",
        rows.len()
    ))
}

// --- Erdős #684: Kummer no-carry lower bound -------------------------------

/// Verify an Erdős #684 certificate: for each `(k, m)`, recompute
/// `m = prod_{p<=k} p^(floor(log_p k)+1)` and confirm zero Kummer carries
/// adding `j + (m-1-j)` in base `p` for all `2 <= j <= k`, `p <= j` —
/// hence no prime `p <= j` divides `C(m-1, j)` and `f(m-1) > k`.
pub fn verify_kummer_no_carry(entries: &[KummerEntry]) -> VerifyResult {
    if entries.is_empty() {
        return VerifyResult::fail("need at least one (k, m) entry");
    }
    for e in entries {
        let k = e.k;
        if !(3..=20).contains(&k) {
            return VerifyResult::fail(format!("k={k} outside the [3, 20] guard"));
        }
        let mut m: u64 = 1;
        for p in primes_upto(k) {
            let mut pe = 1u64;
            let mut exp = 0u64;
            while pe * p <= k {
                pe *= p;
                exp += 1;
            }
            for _ in 0..=exp {
                m = match m.checked_mul(p) {
                    Some(v) => v,
                    None => return VerifyResult::fail(format!("M_{k} overflows u64")),
                };
            }
        }
        if m != e.m {
            return VerifyResult::fail(format!("k={k}: recomputed M_k={m} != claimed {}", e.m));
        }
        let n = m - 1;
        for j in 2..=k {
            for p in primes_upto(j) {
                if carries_base_p(u128::from(j), u128::from(n - j), u128::from(p)) != 0 {
                    return VerifyResult::fail(format!(
                        "k={k}: carry adding {j} + (M-1-{j}) base {p} — C(M-1, {j}) not p-free"
                    ));
                }
            }
        }
    }
    VerifyResult::ok(format!(
        "Erdos #684 certificate: f(M_k - 1) > k verified for {} value(s) of k (zero Kummer carries)",
        entries.len()
    ))
}

// --- Erdős #700: min gcd(n, C(n,k)) ----------------------------------------

/// Verify an Erdős #700 value certificate: for each `(n, f)`, recompute
/// `f(n) = min_{1<k<=n/2} gcd(n, C(n,k))` via the Kummer identity
/// `gcd(n, C(n,k)) = prod_{p|n} p^min(v_p(n), carries_p(k, n-k))`.
pub fn verify_min_binom_gcd(cases: &[MinGcdCase]) -> VerifyResult {
    if cases.is_empty() {
        return VerifyResult::fail("need at least one (n, f) case");
    }
    for c in cases {
        let n = c.n;
        if !(4..=10_000).contains(&n) {
            return VerifyResult::fail(format!("n={n} outside the [4, 10000] guard"));
        }
        let mut factors: Vec<(u64, u64)> = Vec::new();
        let mut rem = n;
        let mut p = 2u64;
        while p * p <= rem {
            if rem.is_multiple_of(p) {
                factors.push((p, vp_of(rem, p)));
                while rem.is_multiple_of(p) {
                    rem /= p;
                }
            }
            p += 1;
        }
        if rem > 1 {
            factors.push((rem, 1));
        }
        let mut best = u64::MAX;
        for k in 2..=n / 2 {
            let mut g = 1u64;
            for &(p, vn) in &factors {
                let carries = carries_base_p(u128::from(k), u128::from(n - k), u128::from(p));
                g *= p.pow(vn.min(carries) as u32);
            }
            best = best.min(g);
        }
        if best != c.f {
            return VerifyResult::fail(format!("n={n}: recomputed f(n)={best} != claimed {}", c.f));
        }
    }
    VerifyResult::ok(format!(
        "Erdos #700 certificate: f(n) = min gcd(n, C(n,k)) verified for {} case(s)",
        cases.len()
    ))
}

// --- Erdős #1093: ELS93 deficiency -----------------------------------------

/// Does `x | i * C(k, i)`? Every prime factor of `i * C(k, i)` is `<= k`,
/// so trial-divide `x` by primes `<= k`; a residual `> 1` means no.
/// Otherwise check `v_p(i) + v_p(C(k,i)) >= e` for each `p^e || x` —
/// `i * C(k, i)` itself is never materialized.
fn divides_smooth(mut x: u128, i: u64, k: u64) -> bool {
    for p in primes_upto(k) {
        if x == 1 {
            break;
        }
        let pp = u128::from(p);
        let mut e = 0u64;
        while x.is_multiple_of(pp) {
            x /= pp;
            e += 1;
        }
        if e > 0 && vp_of(i, p) + vp_binom(k, i, p) < e {
            return false;
        }
    }
    x == 1
}

/// Verify an Erdős #1093 (ELS93) deficiency certificate: each entry's
/// `C(N,k)` is Kummer-defined and `delta(N,k)` (and slot positions, when
/// given) recompute exactly. `N` may be up to 38 decimal digits.
pub fn verify_binom_deficiency(entries: &[DeficiencyEntry]) -> VerifyResult {
    if entries.is_empty() {
        return VerifyResult::fail("need at least one entry");
    }
    for e in entries {
        let k = e.k;
        if !(2..=150).contains(&k) {
            return VerifyResult::fail(format!("k={k} outside the [2, 150] guard"));
        }
        let n = match parse_decimal_u128(&e.n) {
            Ok(v) => v,
            Err(err) => return VerifyResult::fail(err),
        };
        if n < 2 * u128::from(k) {
            return VerifyResult::fail(format!("entry k={k}: need N >= 2k"));
        }
        for p in primes_upto(k) {
            if carries_base_p(u128::from(k), n - u128::from(k), u128::from(p)) != 0 {
                return VerifyResult::fail(format!(
                    "entry k={k}: prime {p} divides C(N,k) — not Kummer-defined"
                ));
            }
        }
        let mut slots: Vec<u64> = Vec::new();
        for i in 1..=k {
            let x = n - u128::from(k) + u128::from(i);
            if divides_smooth(x, i, k) {
                slots.push(i);
            }
        }
        if slots.len() as u64 != e.delta {
            return VerifyResult::fail(format!(
                "entry k={k}: recomputed delta={} != claimed {}",
                slots.len(),
                e.delta
            ));
        }
        if let Some(claimed) = &e.slots
            && &slots != claimed
        {
            return VerifyResult::fail(format!(
                "entry k={k}: smooth slots {slots:?} != claimed {claimed:?}"
            ));
        }
    }
    VerifyResult::ok(format!(
        "Erdos #1093 deficiency certificate: {} entr(ies) Kummer-defined with delta and slots recomputed exactly",
        entries.len()
    ))
}

// --- Erdős #1094: exception enumeration ------------------------------------

/// `C(k, r)` for `k <= 40` — exact in u64.
fn binom_u64(k: u64, r: u64) -> u64 {
    let r = r.min(k - r);
    let mut res = 1u64;
    for i in 1..=r {
        res = res * (k - r + i) / i;
    }
    res
}

/// All divisors of `g`, where `g | lcm(1..k)` so every prime factor is
/// `<= k`. Returns None if `g` does not fully factor over primes `<= k`
/// or the divisor count exceeds the guard.
fn divisors_smooth(g: u64, k: u64) -> Option<Vec<u64>> {
    let mut rem = g;
    let mut pf: Vec<(u64, u64)> = Vec::new();
    for p in primes_upto(k) {
        if rem.is_multiple_of(p) {
            pf.push((p, vp_of(rem, p)));
            while rem.is_multiple_of(p) {
                rem /= p;
            }
        }
    }
    if rem != 1 {
        return None;
    }
    let mut divs: Vec<u64> = vec![1];
    for (p, e) in pf {
        let prev = divs.clone();
        let mut pe = 1u64;
        for _ in 0..e {
            pe *= p;
            for d in &prev {
                divs.push(d * pe);
            }
        }
        if divs.len() > 200_000 {
            return None;
        }
    }
    Some(divs)
}

/// Is `(N, k)` a #1094 exception — no prime `p <= max(N/k, k)` divides
/// `C(N, k)`? Early-exits on the first dividing prime. Returns None
/// (fail-closed) if a candidate survives past the 10^7 prime guard
/// without a verdict — that can only happen for a would-be NEW
/// exception, where refusing to claim is the correct behavior.
fn is_exception_guarded(n: u64, k: u64) -> Option<bool> {
    let mut p = 2u64;
    // Condition `p <= max(N/k, k)` without floats: p <= k || p*k <= N.
    while p <= k || p.saturating_mul(k) <= n {
        if is_prime(p) && vp_binom(n, k, p) > 0 {
            return Some(false);
        }
        if p > 10_000_000 {
            return None;
        }
        p += 1;
    }
    Some(true)
}

/// Verify an Erdős #1094 exception-enumeration certificate: re-enumerate
/// every candidate `N = x + k - r` (`x | gcd(lcm(1..k), r*C(k,r))`,
/// `k | x`, `N >= 2k`) for `k <= k_max` and confirm the exception set
/// equals the claimed `(N, k)` list exactly.
pub fn verify_binom_exception_enum(k_max: u64, exceptions: &[(u64, u64)]) -> VerifyResult {
    if !(3..=40).contains(&k_max) {
        return VerifyResult::fail(format!("k_max={k_max} outside the [3, 40] guard"));
    }
    let claimed: std::collections::BTreeSet<(u64, u64)> = exceptions.iter().copied().collect();
    for &(n, k) in &claimed {
        if k > k_max || n < 2 * k {
            return VerifyResult::fail(format!(
                "claimed exception (N={n}, k={k}) outside k <= k_max / N >= 2k"
            ));
        }
    }
    let mut found: std::collections::BTreeSet<(u64, u64)> = std::collections::BTreeSet::new();
    let mut lambda: u64 = 1;
    let mut candidates: u64 = 0;
    for k in 2..=k_max {
        lambda = lambda / gcd_u64(lambda, k) * k;
        for r in 1..=k {
            let g = gcd_u64(lambda, r * binom_u64(k, r));
            let divs = match divisors_smooth(g, k) {
                Some(d) => d,
                None => {
                    return VerifyResult::fail(format!(
                        "divisor enumeration guard exceeded at k={k}, r={r}"
                    ));
                }
            };
            for x in divs {
                if !x.is_multiple_of(k) {
                    continue;
                }
                let n = x + k - r;
                if n < 2 * k {
                    continue;
                }
                candidates += 1;
                match is_exception_guarded(n, k) {
                    Some(true) => {
                        found.insert((n, k));
                    }
                    Some(false) => {}
                    None => {
                        return VerifyResult::fail(format!(
                            "exception test guard exceeded at (N={n}, k={k}) — refusing to claim"
                        ));
                    }
                }
            }
        }
    }
    if found != claimed {
        let extra: Vec<_> = found.difference(&claimed).collect();
        let missing: Vec<_> = claimed.difference(&found).collect();
        return VerifyResult::fail(format!(
            "exception set mismatch: extra {extra:?}, missing {missing:?}"
        ));
    }
    VerifyResult::ok(format!(
        "Erdos #1094 enumeration: {candidates} candidate(s) checked for k <= {k_max}; exception set of {} matches exactly",
        claimed.len()
    ))
}

// --- UNSAT certificate (LRAT / RUP) ----------------------------------------

/// Check that adding clause `c` is justified by reverse unit propagation
/// over the antecedent `hints` (in order) against `db`. Returns true iff
/// propagating `¬c` through the hinted clauses reaches a conflict — i.e.
/// `c` is RUP-implied by the current clause set. Hints that are satisfied,
/// non-unit, or unknown are rejected (a malformed proof never passes).
/// RAT check on the step's FIRST literal (the LRAT convention): the
/// step is a Resolution Asymmetric Tautology iff for every db clause D
/// containing the negated pivot, the resolvent (step ∪ D minus the
/// pivot pair) is RUP using the hints the step supplies for D's id.
/// Tautological resolvents pass vacuously. A clause with -pivot that
/// has no supplied hints fails the whole step — nothing is guessed.
fn rat_check(step: &LratStep, db: &std::collections::HashMap<u64, Vec<i64>>) -> bool {
    let Some(&pivot) = step.literals.first() else {
        return false; // the empty clause can never be RAT
    };
    let supplied: std::collections::HashMap<u64, &Vec<u64>> =
        step.rat_hints.iter().map(|(id, h)| (*id, h)).collect();
    for (&cid, clause) in db {
        if !clause.contains(&-pivot) {
            continue;
        }
        let mut resolvent: Vec<i64> = step.literals.clone();
        for &l in clause {
            if l != -pivot && l != 0 && !resolvent.contains(&l) {
                resolvent.push(l);
            }
        }
        if resolvent.iter().any(|&l| resolvent.contains(&-l) && l > 0) {
            continue; // tautological resolvent: vacuously implied
        }
        let Some(hints) = supplied.get(&cid) else {
            return false;
        };
        if !rup_checks(&resolvent, hints, db) {
            return false;
        }
    }
    true
}

fn rup_checks(c: &[i64], hints: &[u64], db: &std::collections::HashMap<u64, Vec<i64>>) -> bool {
    // Falsify every literal of c: var |l| takes the value that makes l false.
    let mut assign: std::collections::HashMap<i64, bool> = std::collections::HashMap::new();
    for &l in c {
        if l == 0 {
            return false;
        }
        let v = l.abs();
        let want = l < 0; // l<0 ⇒ var true makes l false
        if let Some(&prev) = assign.get(&v)
            && prev != want
        {
            return false; // c is a tautology (l and ¬l) — not a real clause
        }
        assign.insert(v, want);
    }
    for &h in hints {
        let Some(cl) = db.get(&h) else {
            return false; // unknown antecedent
        };
        let mut unassigned: Vec<i64> = Vec::new();
        let mut satisfied = false;
        for &l in cl {
            if l == 0 {
                continue;
            }
            match assign.get(&l.abs()) {
                None => unassigned.push(l),
                Some(&val) => {
                    // l true under assign? l>0 wants var true; l<0 wants var false.
                    if (l > 0) == val {
                        satisfied = true;
                    }
                }
            }
        }
        if satisfied {
            return false; // a satisfied antecedent can neither propagate nor conflict
        }
        match unassigned.len() {
            0 => return true, // all literals falsified ⇒ conflict ⇒ c is RUP
            1 => {
                let l = unassigned[0];
                assign.insert(l.abs(), l > 0); // propagate the forced literal
            }
            _ => return false, // not unit ⇒ this hint cannot fire
        }
    }
    false // ran out of hints without a conflict
}

/// Verify an UNSAT certificate: replay the LRAT proof over the CNF and
/// confirm it derives the empty clause. Each step's added clause must be
/// RUP-implied by the clauses available so far (original + previously
/// added). Deterministic and total; bounded by explicit guards.
pub fn verify_unsat_cert(cnf: &[Vec<i64>], proof: &[LratStep]) -> VerifyResult {
    if cnf.is_empty() {
        return VerifyResult::fail("empty CNF: nothing to refute");
    }
    if cnf.len() > 5_000_000 || proof.len() > 20_000_000 {
        return VerifyResult::fail("certificate exceeds the size guard");
    }
    let mut db: std::collections::HashMap<u64, Vec<i64>> = std::collections::HashMap::new();
    for (i, clause) in cnf.iter().enumerate() {
        let id = (i + 1) as u64; // original clauses are 1-indexed
        if db.insert(id, clause.clone()).is_some() {
            return VerifyResult::fail(format!("duplicate clause id {id}"));
        }
    }
    let mut derived_empty = false;
    for step in proof {
        if step.id == 0 {
            return VerifyResult::fail("proof clause id 0 is reserved");
        }
        if !rup_checks(&step.literals, &step.hints, &db) && !rat_check(step, &db) {
            return VerifyResult::fail(format!(
                "LRAT step {} is neither RUP-implied nor RAT on its first literal",
                step.id
            ));
        }
        let empty = step.literals.is_empty();
        if db.insert(step.id, step.literals.clone()).is_some() {
            return VerifyResult::fail(format!("clause id {} added twice", step.id));
        }
        if empty {
            derived_empty = true;
            break;
        }
    }
    if !derived_empty {
        return VerifyResult::fail("proof never derives the empty clause (UNSAT not established)");
    }
    VerifyResult::ok(format!(
        "UNSAT certificate: {} clause(s), {} LRAT step(s), empty clause derived by RUP",
        cnf.len(),
        proof.len()
    ))
}

pub fn verify_golomb(marks: &[i64]) -> VerifyResult {
    let set: HashSet<&i64> = marks.iter().collect();
    if set.len() != marks.len() {
        return VerifyResult::fail("duplicate marks");
    }
    let mut diffs: HashSet<i64> = HashSet::new();
    let mut count = 0usize;
    for i in 0..marks.len() {
        for j in (i + 1)..marks.len() {
            if !diffs.insert((marks[j] - marks[i]).abs()) {
                return VerifyResult::fail("repeated pairwise difference (not a Golomb ruler)");
            }
            count += 1;
        }
    }
    let (lo, hi) = (marks.iter().min().copied(), marks.iter().max().copied());
    let length = match (lo, hi) {
        (Some(a), Some(b)) => b - a,
        _ => 0,
    };
    VerifyResult::ok(format!(
        "Golomb ruler: {} marks, length {length}, all {count} differences distinct",
        marks.len()
    ))
}

/// A cap in `F_3^n`: no three distinct points sum to 0 mod 3 (no three
/// collinear). For each pair, the unique line-completion must be absent.
pub fn verify_cap(points: &[Vec<i64>], n: usize) -> VerifyResult {
    let set: HashSet<&Vec<i64>> = points.iter().collect();
    if set.len() != points.len() {
        return VerifyResult::fail("duplicate points");
    }
    if !points
        .iter()
        .all(|p| p.len() == n && p.iter().all(|&x| (0..=2).contains(&x)))
    {
        return VerifyResult::fail(format!("points not in (0,1,2)^{n}"));
    }
    let owned: HashSet<Vec<i64>> = points.iter().cloned().collect();
    let m = points.len();
    for i in 0..m {
        let a = &points[i];
        for b in points.iter().take(m).skip(i + 1) {
            let c: Vec<i64> = (0..n).map(|k| (-(a[k] + b[k])).rem_euclid(3)).collect();
            if owned.contains(&c) && &c != a && &c != b {
                return VerifyResult::fail("3 collinear points found (not a cap)");
            }
        }
    }
    VerifyResult::ok(format!(
        "cap verified: {m} points in F_3^{n}, no 3 collinear"
    ))
}

/// A `B_h` set in `{0,1}^n`: all sums of `h` elements (with repetition,
/// non-decreasing index order) distinct. `h = 2` is Sidon.
pub fn verify_bh(points: &[Vec<i64>], n: usize, h: usize) -> VerifyResult {
    if let Some(bad) = binary_points_ok(points, n) {
        return bad;
    }
    let m = points.len();
    if m == 0 || h == 0 {
        return VerifyResult::ok(format!("B_{h} verified: {m} points, 0 sums"));
    }
    let mut sums: HashSet<Vec<i64>> = HashSet::new();
    let mut count = 0usize;
    let mut idx = vec![0usize; h];
    loop {
        let mut s = vec![0i64; n];
        for &i in &idx {
            for k in 0..n {
                s[k] += points[i][k];
            }
        }
        if !sums.insert(s) {
            return VerifyResult::fail(format!("B_{h} violated: a repeated {h}-fold sum"));
        }
        count += 1;
        if !advance_with_replacement(&mut idx, m) {
            break;
        }
    }
    VerifyResult::ok(format!(
        "B_{h} verified: {m} points, {count} h-fold sums all distinct"
    ))
}

/// A covering design `C(v, k, t)`: blocks are `k`-subsets of `[0, v)`
/// such that every `t`-subset of `[0, v)` is contained in at least one.
pub fn verify_covering(blocks: &[Vec<usize>], v: usize, k: usize, t: usize) -> VerifyResult {
    let norm: Vec<Vec<usize>> = blocks
        .iter()
        .map(|b| {
            let s: std::collections::BTreeSet<usize> = b.iter().copied().collect();
            s.into_iter().collect()
        })
        .collect();
    if !norm
        .iter()
        .all(|b| b.len() == k && b.iter().all(|&x| x < v))
    {
        return VerifyResult::fail(format!("blocks not valid {k}-subsets of [0,{v})"));
    }
    let mut covered: HashSet<Vec<usize>> = HashSet::new();
    for b in &norm {
        each_combination(b.len(), t, &mut |sub| {
            covered.insert(sub.iter().map(|&i| b[i]).collect());
        });
    }
    let mut need = 0usize;
    let mut missing = 0usize;
    each_combination(v, t, &mut |sub| {
        need += 1;
        if !covered.contains(sub) {
            missing += 1;
        }
    });
    if missing > 0 {
        return VerifyResult::fail(format!(
            "not a covering: {missing} of {need} t-subsets uncovered"
        ));
    }
    VerifyResult::ok(format!(
        "valid C({v},{k},{t}) covering with {} blocks",
        norm.len()
    ))
}

/// A constant-weight binary code `A(n, d, w)`: codewords of weight
/// exactly `w`, pairwise Hamming distance `>= d`.
pub fn verify_constant_weight(words: &[Vec<i64>], n: usize, d: usize, w: usize) -> VerifyResult {
    let set: HashSet<&Vec<i64>> = words.iter().collect();
    if set.len() != words.len() {
        return VerifyResult::fail("duplicate codewords");
    }
    if !words
        .iter()
        .all(|c| c.len() == n && c.iter().all(|&x| x == 0 || x == 1))
    {
        return VerifyResult::fail(format!("words not binary length-{n}"));
    }
    if let Some(c) = words.iter().find(|c| c.iter().sum::<i64>() as usize != w) {
        return VerifyResult::fail(format!(
            "a codeword has weight {} != {w}",
            c.iter().sum::<i64>()
        ));
    }
    for i in 0..words.len() {
        for j in (i + 1)..words.len() {
            let dist = (0..n).filter(|&k| words[i][k] != words[j][k]).count();
            if dist < d {
                return VerifyResult::fail(format!("a pair has Hamming distance {dist} < {d}"));
            }
        }
    }
    VerifyResult::ok(format!(
        "constant-weight code A({n},{d},{w}): {} words, all weight {w}, min dist >= {d}",
        words.len()
    ))
}

/// A Costas array: a permutation `p` of consecutive integers such that
/// the displacement vectors `(j-i, p[j]-p[i])` for `i < j` are distinct.
pub fn verify_costas(perm: &[i64]) -> VerifyResult {
    let n = perm.len();
    let mut sorted = perm.to_vec();
    sorted.sort_unstable();
    let min = perm.iter().min().copied().unwrap_or(0);
    let expected: Vec<i64> = (0..n as i64).map(|i| min + i).collect();
    if sorted != expected {
        return VerifyResult::fail("not a permutation");
    }
    let mut vecs: HashSet<(i64, i64)> = HashSet::new();
    let mut count = 0usize;
    for i in 0..n {
        for j in (i + 1)..n {
            if !vecs.insert(((j - i) as i64, perm[j] - perm[i])) {
                return VerifyResult::fail("repeated displacement vector (not a Costas array)");
            }
            count += 1;
        }
    }
    VerifyResult::ok(format!(
        "Costas array of order {n} verified ({count} displacement vectors all distinct)"
    ))
}

/// A linear `[n, k, d]_q` code given by a `k x n` generator matrix over a
/// prime field `GF(q)`. Verifies `rank(G) = k` and that the true minimum
/// distance (min nonzero codeword weight, by exhaustive enumeration of
/// the `q^k` codewords, guarded) is `>= claimed_d`. Prime-power `GF(q)`
/// is refused rather than mis-verified.
// Frozen exact verifier: the range loops index multiple parallel arrays
// (codeword/weight); the explicit index is the faithful expression, not a
// refactor target.
#[allow(clippy::needless_range_loop)]
pub fn verify_linear_code(generator: &[Vec<i64>], q: u64, claimed_d: usize) -> VerifyResult {
    const MAX_ENUM: u64 = 1_000_000;
    if !is_prime(q) {
        return VerifyResult::fail(format!(
            "q={q} not prime; prime-power GF(q) not implemented — refusing to claim"
        ));
    }
    let k = generator.len();
    if k == 0 {
        return VerifyResult::fail("empty generator");
    }
    let n = generator[0].len();
    if !generator.iter().all(|row| row.len() == n) {
        return VerifyResult::fail("ragged generator matrix");
    }
    let g: Vec<Vec<u64>> = generator
        .iter()
        .map(|row| row.iter().map(|&x| x.rem_euclid(q as i64) as u64).collect())
        .collect();
    if gf_rank(&g, q) != k {
        return VerifyResult::fail(format!(
            "generator rank < k={k} (rows dependent — not an [n,{k}] code)"
        ));
    }
    let qk = (q).checked_pow(k as u32);
    match qk {
        Some(v) if v <= MAX_ENUM => {}
        _ => {
            return VerifyResult::fail(format!(
                "q^k exceeds enum guard {MAX_ENUM}; distance not exhaustively verifiable — refusing to claim"
            ));
        }
    }
    let qk = qk.unwrap();
    let mut dmin = n + 1;
    // Enumerate all nonzero message vectors msg in GF(q)^k.
    let mut msg = vec![0u64; k];
    for code in 1..qk {
        // decode `code` as a base-q digit vector
        let mut x = code;
        for m in msg.iter_mut() {
            *m = x % q;
            x /= q;
        }
        let mut weight = 0usize;
        for c in 0..n {
            let mut s = 0u64;
            for i in 0..k {
                if msg[i] != 0 {
                    s = (s + msg[i] * g[i][c]) % q;
                }
            }
            if s != 0 {
                weight += 1;
            }
        }
        if weight < dmin {
            dmin = weight;
        }
    }
    let ok = dmin >= claimed_d;
    let rel = if ok { ">=" } else { "<" };
    VerifyResult {
        ok,
        message: format!(
            "[{n},{k},{dmin}]_{q} verified (min weight {dmin} {rel} claimed {claimed_d})"
        ),
        value: Some(dmin as f64),
    }
}

// --- small numeric / combinatorial helpers -------------------------------

/// Advance an index tuple to the next combination-with-replacement over
/// `[0, m)`. Returns false when exhausted.
fn advance_with_replacement(idx: &mut [usize], m: usize) -> bool {
    let h = idx.len();
    let mut i = h;
    loop {
        if i == 0 {
            return false;
        }
        i -= 1;
        if idx[i] != m - 1 {
            let nv = idx[i] + 1;
            for slot in idx.iter_mut().take(h).skip(i) {
                *slot = nv;
            }
            return true;
        }
    }
}

/// Visit every strictly-increasing `t`-combination of indices in
/// `[0, n)`.
fn each_combination(n: usize, t: usize, f: &mut impl FnMut(&[usize])) {
    if t > n {
        return;
    }
    let mut idx: Vec<usize> = (0..t).collect();
    loop {
        f(&idx);
        // advance
        let mut i = t;
        loop {
            if i == 0 {
                return;
            }
            i -= 1;
            if idx[i] != i + n - t {
                idx[i] += 1;
                for j in (i + 1)..t {
                    idx[j] = idx[j - 1] + 1;
                }
                break;
            }
        }
    }
}

fn is_prime(q: u64) -> bool {
    if q < 2 {
        return false;
    }
    let mut p = 2u64;
    while p * p <= q {
        if q.is_multiple_of(p) {
            return false;
        }
        p += 1;
    }
    true
}

/// Rank over `GF(q)` (q prime) of an integer matrix (entries already
/// reduced mod q).
// Gaussian elimination over GF(q): the inner loops index two rows by the same
// column, so a range loop is the honest form (iterator pairs would obscure it).
#[allow(clippy::needless_range_loop)]
fn gf_rank(rows: &[Vec<u64>], q: u64) -> usize {
    let mut m: Vec<Vec<u64>> = rows.to_vec();
    if m.is_empty() {
        return 0;
    }
    let ncols = m[0].len();
    let mut rank = 0usize;
    for col in 0..ncols {
        let piv = (rank..m.len()).find(|&r| !m[r][col].is_multiple_of(q));
        let Some(piv) = piv else { continue };
        m.swap(rank, piv);
        let inv = mod_inv(m[rank][col] % q, q);
        for c in 0..ncols {
            m[rank][c] = (m[rank][c] * inv) % q;
        }
        for r in 0..m.len() {
            if r != rank && !m[r][col].is_multiple_of(q) {
                let f = m[r][col] % q;
                for c in 0..ncols {
                    m[r][c] = (m[r][c] + q - (f * m[rank][c]) % q) % q;
                }
            }
        }
        rank += 1;
        if rank == m.len() {
            break;
        }
    }
    rank
}

/// Modular inverse of `a` mod prime `q` via Fermat's little theorem.
fn mod_inv(a: u64, q: u64) -> u64 {
    mod_pow(a, q - 2, q)
}

fn mod_pow(mut base: u64, mut exp: u64, modulus: u64) -> u64 {
    let mut result = 1u64;
    base %= modulus;
    while exp > 0 {
        if exp & 1 == 1 {
            result = (result * base) % modulus;
        }
        exp >>= 1;
        base = (base * base) % modulus;
    }
    result
}

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

    // A genuine a(8) >= 33 Sidon witness fragment is large; use a small
    // hand-checked Sidon set for the unit test, plus corrupt-it checks.
    fn small_sidon() -> Vec<Vec<i64>> {
        // In {0,1}^3: {000, 100, 010, 001} — pairwise sums all distinct?
        // sums include 000,100,010,001 (i=j) and 110,101,011 (i<j) — all
        // distinct. A valid (small) Sidon set.
        vec![vec![0, 0, 0], vec![1, 0, 0], vec![0, 1, 0], vec![0, 0, 1]]
    }

    // ---- claim<->witness faithfulness (the un-forgeable exact-lane core) ----

    #[test]
    fn faithful_parses_real_a309370_assertion() {
        let text = "OEIS A309370 a(20) >= 1989: a Sidon set of 1989 distinct binary \
                    vectors in {0,1}^20 under componentwise integer addition, with all \
                    pairwise sums distinct. Frozen-verified by vela-verify (sidon kind).";
        let p = parse_claim(text).expect("should parse the canonical A309370 form");
        assert_eq!(p.kind, "sidon");
        assert_eq!(p.ambient_n, Some(20));
        assert_eq!(p.bound, 1989);
        assert!(!p.exact);
    }

    #[test]
    fn faithful_happy_path() {
        let text = "a(3) >= 4: a Sidon set of 4 vectors in {0,1}^3.";
        let w = Witness::Sidon {
            n: 3,
            points: small_sidon(),
            claimed_size: Some(4),
        };
        let f = claim_witness_faithful(text, &w);
        assert!(f.faithful, "{:?}", f.reasons);
    }

    // ATTACK: inflated assertion over a valid-but-weaker witness. verify_witness
    // passes (it IS a genuine size-4 Sidon set), but the claim says >= 5.
    #[test]
    fn faithful_rejects_inflated_lower_bound() {
        let text = "a(3) >= 5: a Sidon set of 5 vectors in {0,1}^3.";
        let w = Witness::Sidon {
            n: 3,
            points: small_sidon(), // only 4 points
            claimed_size: None,
        };
        assert!(verify_witness(&w).ok, "the witness itself is valid");
        let f = claim_witness_faithful(text, &w);
        assert!(!f.faithful);
        assert!(f.reasons.iter().any(|r| r.contains("does not establish")));
    }

    // ATTACK: claim names a different ambient dimension than the witness.
    #[test]
    fn faithful_rejects_dimension_mismatch() {
        let text = "a(8) >= 4: a Sidon set of 4 vectors in {0,1}^8.";
        let w = Witness::Sidon {
            n: 3,
            points: small_sidon(),
            claimed_size: None,
        };
        let f = claim_witness_faithful(text, &w);
        assert!(!f.faithful);
        assert!(f.reasons.iter().any(|r| r.contains("dimension")));
    }

    // ATTACK: a Golomb claim bound to a Sidon witness.
    #[test]
    fn faithful_rejects_kind_mismatch() {
        let text = "an optimal Golomb ruler of order 4 with >= 4 marks.";
        let w = Witness::Sidon {
            n: 3,
            points: small_sidon(),
            claimed_size: None,
        };
        let f = claim_witness_faithful(text, &w);
        assert!(!f.faithful);
        assert!(f.reasons.iter().any(|r| r.contains("kind")));
    }

    // ATTACK: a witness that does not actually verify (collision injected).
    #[test]
    fn faithful_rejects_invalid_witness() {
        let text = "a(3) >= 4: a Sidon set of 4 vectors in {0,1}^3.";
        // {000, 100, 100, 010}: 100 repeated -> not a valid Sidon set.
        let w = Witness::Sidon {
            n: 3,
            points: vec![vec![0, 0, 0], vec![1, 0, 0], vec![1, 0, 0], vec![0, 1, 0]],
            claimed_size: None,
        };
        let f = claim_witness_faithful(text, &w);
        assert!(!f.faithful);
        assert!(f.reasons.iter().any(|r| r.contains("does not verify")));
    }

    // ATTACK: an existence/asymptotic assertion with no exact bound -> the
    // conservative parser refuses, so it can never auto-admit.
    #[test]
    fn faithful_refuses_unparseable_asymptotic_claim() {
        let text = "Singer's perfect-difference-set construction yields Sidon sets in \
                    {1,...,N} of size sqrt(N) + O(N^{1/4}).";
        let w = Witness::Sidon {
            n: 3,
            points: small_sidon(),
            claimed_size: None,
        };
        let f = claim_witness_faithful(text, &w);
        assert!(!f.faithful);
        assert!(f.parsed.is_none());
    }

    // ATTACK: ambiguous claim carrying BOTH a lower bound and an equality.
    #[test]
    fn faithful_refuses_ambiguous_bound() {
        let text = "a Sidon set in {0,1}^3 with >= 4 and exactly 5 elements.";
        assert!(parse_claim(text).is_none());
    }

    #[test]
    fn faithful_routes_equality_optimality_to_review() {
        // An equality / optimality claim (`= N` / `exactly N`) asserts the
        // MAXIMUM is N (no larger object exists), which a single construction
        // witness cannot prove — it establishes only a lower bound. So even a
        // size-matching witness must NOT auto-admit an `exactly` claim; it
        // routes to review. (Closes the inflation-via-equality vector: an agent
        // cannot turn a real `a(n) >= k` witness into an `a(n) = k`/headline
        // claim the floor never verified.)
        let w = Witness::Sidon {
            n: 3,
            points: small_sidon(), // 4 points
            claimed_size: None,
        };
        let f = claim_witness_faithful("a Sidon set in {0,1}^3 with exactly 4 elements.", &w);
        assert!(
            !f.faithful,
            "equality/optimality is not witness-establishable"
        );
        assert!(f.reasons.iter().any(|r| r.contains("equality/optimality")));
        // a standalone `= N` headline is treated the same way.
        let f2 = claim_witness_faithful("Sidon a(3) = 4 in {0,1}^3 (new record).", &w);
        assert!(!f2.faithful, "a `= N` headline also routes to review");
    }

    // ---- second-adversarial-review regressions (floor as the sole gate) ----

    // ATTACK (inflated-claim / witness-substitution): a genuine small witness
    // dressed with an `a(20)` headline. Reading the a(N) order and binding it to
    // the witness n closes both the omit-dimension and the easy-witness-for-
    // hard-claim bypass.
    #[test]
    fn faithful_binds_a_of_n_order_to_witness() {
        let w = Witness::Sidon {
            n: 3,
            points: small_sidon(),
            claimed_size: None,
        }; // a valid 4-point Sidon set in {0,1}^3
        assert!(verify_witness(&w).ok, "the witness itself is valid");
        // a(20) order vs witness n=3 -> mismatch, even though size 4 >= 4.
        let f = claim_witness_faithful("Sidon record a(20): at least 4 points.", &w);
        assert!(
            !f.faithful,
            "an a(20) claim cannot ride an n=3 witness: {:?}",
            f.reasons
        );
        // No ambient/order at all -> mandatory-dimension fail closed.
        let f2 = claim_witness_faithful("A Sidon set, at least 4 points, beats the record.", &w);
        assert!(
            !f2.faithful,
            "a dimensioned claim with no ambient routes to review: {:?}",
            f2.reasons
        );
    }

    // ATTACK (dual-bound headline): a `= 2500` headline beside an `at least 4`
    // clause. The lower bound co-occurring with an equality marker is ambiguous.
    #[test]
    fn faithful_rejects_dual_bound_headline() {
        let w = Witness::Sidon {
            n: 3,
            points: small_sidon(),
            claimed_size: None,
        };
        let f = claim_witness_faithful(
            "Sidon in {0,1}^3: a(3) = 2500 (beats prior 1989). The witness has at least 4 points.",
            &w,
        );
        assert!(
            !f.faithful,
            "a `= headline` beside an `at least` clause is ambiguous: {:?}",
            f.reasons
        );
        assert!(
            f.parsed.is_none(),
            "the dual lower+equality marker fails parse"
        );
    }

    // ATTACK (reproduce-spoof / GF(2) dimension): a GF(2)^5 witness cannot
    // establish an a(4) claim, because element 16 sits outside GF(2)^4.
    #[test]
    fn faithful_gf2_binds_dimension() {
        let good = Witness::Gf2Sidon {
            elements: vec![1, 2, 4],
            claimed_size: None,
        };
        assert!(verify_witness(&good).ok);
        let f = claim_witness_faithful("OEIS A394031 a(3) >= 3: a Sidon set in GF(2)^3.", &good);
        assert!(f.faithful, "genuine GF(2)^3 claim: {:?}", f.reasons);

        let wide = Witness::Gf2Sidon {
            elements: vec![1, 2, 4, 8, 16],
            claimed_size: None,
        };
        assert!(
            verify_witness(&wide).ok,
            "the wider witness is itself valid"
        );
        let f2 = claim_witness_faithful("OEIS A394031 a(4) >= 5: a Sidon set in GF(2)^4.", &wide);
        assert!(
            !f2.faithful,
            "an element outside GF(2)^4 must fail: {:?}",
            f2.reasons
        );
        // dimension omitted -> mandatory fail closed.
        let f3 = claim_witness_faithful("A GF(2) Sidon set, at least 5 elements.", &wide);
        assert!(!f3.faithful, "{:?}", f3.reasons);
    }

    // B_h and constant-weight bind their extra hardness parameter (h; d,w).
    // The round-3 attack (an EASY witness dressed with a HARD headline) now
    // FAILS on the parameter mismatch; a matched claim PASSES; an unstated
    // parameter routes to review.
    #[test]
    fn faithful_binds_bh_order_and_constant_weight_params() {
        // B_h: the witness is a valid B_2 set.
        let bh = Witness::Bh {
            n: 3,
            h: 2,
            points: small_sidon(),
            claimed_size: None,
        };
        assert!(verify_witness(&bh).ok, "the B_2 witness is itself valid");
        // ATTACK: a B_3 headline over a B_2 witness -> h mismatch -> rejected.
        let attack = claim_witness_faithful("a B_3 set in {0,1}^3: a(3) >= 4.", &bh);
        assert!(
            !attack.faithful,
            "B_3 claim cannot ride a B_2 witness: {:?}",
            attack.reasons
        );
        assert!(attack.reasons.iter().any(|r| r.contains("does not match")));
        // GENUINE: a matched B_2 claim is faithful.
        let ok = claim_witness_faithful("a B_2 set in {0,1}^3: a(3) >= 4.", &bh);
        assert!(ok.faithful, "matched B_2 claim: {:?}", ok.reasons);
        // h unstated -> route to review.
        let bare = claim_witness_faithful("a bh set in {0,1}^3: a(3) >= 4.", &bh);
        assert!(
            !bare.faithful,
            "unstated h routes to review: {:?}",
            bare.reasons
        );

        // constant-weight: the witness is a valid A(4,2,1) code (2 weight-1 words).
        let cw = Witness::ConstantWeight {
            n: 4,
            d: 2,
            w: 1,
            words: vec![vec![1, 0, 0, 0], vec![0, 1, 0, 0]],
            claimed_size: None,
        };
        assert!(
            verify_witness(&cw).ok,
            "the A(4,2,1) witness is itself valid"
        );
        // ATTACK: a hard A(4,10,8) headline over the trivial witness -> rejected.
        let attack2 = claim_witness_faithful("constant weight code A(4,10,8) >= 2.", &cw);
        assert!(
            !attack2.faithful,
            "A(4,10,8) claim cannot ride an A(4,2,1) witness: {:?}",
            attack2.reasons
        );
        assert!(attack2.reasons.iter().any(|r| r.contains("does not match")));
        // GENUINE: the matched A(4,2,1) claim is faithful.
        let ok2 = claim_witness_faithful("constant weight code A(4,2,1) >= 2.", &cw);
        assert!(ok2.faithful, "matched A(4,2,1) claim: {:?}", ok2.reasons);
        // (d,w) unstated -> route to review.
        let bare2 = claim_witness_faithful("a constant weight code, a(4) >= 2.", &cw);
        assert!(
            !bare2.faithful,
            "unstated (d,w) routes to review: {:?}",
            bare2.reasons
        );
    }

    // The canonical, witness-derived verified claim (residual #1): the displayed
    // claim is DERIVED from the witness, so prose cannot puff a true bound.
    #[test]
    fn canonical_claim_is_witness_derived() {
        let s = Witness::Sidon {
            n: 3,
            points: small_sidon(),
            claimed_size: None,
        };
        let c = canonical_claim(&s).expect("sidon has a canonical claim");
        assert!(c.contains("a(3) >= 4"), "{c}");
        // GF(2): n is the widest element's bit width (here 4 -> bit index 2).
        let g = Witness::Gf2Sidon {
            elements: vec![1, 2, 4],
            claimed_size: None,
        };
        let cg = canonical_claim(&g).expect("gf2 has a canonical claim");
        assert!(cg.contains("a(3) >= 3"), "{cg}");
        // golomb (not floor-admissible) has no canonical claim.
        assert!(
            canonical_claim(&Witness::Golomb {
                marks: vec![0, 1, 3]
            })
            .is_none()
        );
    }

    // Golomb has no sound witness->lower-bound binding defined: route to review.
    #[test]
    fn faithful_golomb_routes_to_review() {
        let w = Witness::Golomb {
            marks: vec![0, 1, 3],
        };
        assert!(verify_witness(&w).ok);
        let f = claim_witness_faithful("Golomb ruler a(3) >= 3.", &w);
        assert!(
            !f.faithful,
            "golomb is not floor-admissible: {:?}",
            f.reasons
        );
    }

    // ---- difference triangle set (HorizonMath (7,5), scope < 112) ----

    #[test]
    fn diff_triangle_accepts_valid_and_reports_scope() {
        // rows {0,1,3} (diffs 1,2,3) and {0,4,9} (diffs 4,5,9): all distinct.
        let w = Witness::DiffTriangle {
            rows: vec![vec![0, 1, 3], vec![0, 4, 9]],
            claimed_scope: Some(9),
        };
        let r = verify_witness(&w);
        assert!(r.ok, "{}", r.message);
        assert!(r.message.contains("scope 9"));
    }

    #[test]
    fn diff_triangle_rejects_global_difference_collision() {
        // row2 {0,2,5} has differences 2 and 3, which collide with row1.
        let w = Witness::DiffTriangle {
            rows: vec![vec![0, 1, 3], vec![0, 2, 5]],
            claimed_scope: None,
        };
        let r = verify_witness(&w);
        assert!(!r.ok);
        assert!(r.message.contains("repeats"));
    }

    #[test]
    fn diff_triangle_rejects_non_increasing_and_nonzero_start() {
        assert!(!verify_diff_triangle(&[vec![0, 3, 1]], None).ok);
        assert!(!verify_diff_triangle(&[vec![1, 2, 4]], None).ok);
    }

    #[test]
    fn diff_triangle_rejects_inflated_scope_claim() {
        // A valid set, but a record claim ("scope below 112") that lies about
        // the actual scope must fail.
        let w = Witness::DiffTriangle {
            rows: vec![vec![0, 1, 3], vec![0, 4, 9]],
            claimed_scope: Some(100),
        };
        assert!(!verify_witness(&w).ok);
    }

    #[test]
    fn gf2_sidon_accepts_distinct_xors_and_rejects_collision() {
        // {0,1,2}: XORs 1,2,3 all distinct -> GF(2) Sidon.
        let ok = Witness::Gf2Sidon {
            elements: vec![0, 1, 2],
            claimed_size: Some(3),
        };
        assert!(verify_witness(&ok).ok);
        // {0,1,2,3}: 0^3 = 3 and 1^2 = 3 collide -> not Sidon.
        let bad = Witness::Gf2Sidon {
            elements: vec![0, 1, 2, 3],
            claimed_size: None,
        };
        assert!(!verify_witness(&bad).ok);
        // duplicate element rejected.
        let dup = Witness::Gf2Sidon {
            elements: vec![5, 5],
            claimed_size: None,
        };
        assert!(!verify_witness(&dup).ok);
    }

    #[test]
    fn union_free_accepts_and_rejects_union_member() {
        // {1,2},{1,3},{2,3}: no member is a union of others over {1,2,3}.
        let ok = Witness::UnionFree {
            n: 3,
            sets: vec![vec![1, 2], vec![1, 3], vec![2, 3]],
            claimed_size: Some(3),
        };
        assert!(verify_witness(&ok).ok);
        // {1},{2},{1,2}: {1,2} = {1} ∪ {2} -> not union-free.
        let bad = Witness::UnionFree {
            n: 2,
            sets: vec![vec![1], vec![2], vec![1, 2]],
            claimed_size: None,
        };
        assert!(!verify_witness(&bad).ok);
    }

    #[test]
    fn rook_directions_counts_classes_and_checks_claim() {
        // n=2, perm [1,2]: one pair, one direction class (1,1). a(2)=1.
        let ok = Witness::RookDirections {
            n: 2,
            perm: vec![1, 2],
            claimed_directions: Some(1),
        };
        assert!(verify_witness(&ok).ok);
        // wrong claimed count rejected.
        let bad = Witness::RookDirections {
            n: 2,
            perm: vec![1, 2],
            claimed_directions: Some(2),
        };
        assert!(!verify_witness(&bad).ok);
        // repeated column (attacking rooks) rejected.
        let attack = Witness::RookDirections {
            n: 2,
            perm: vec![1, 1],
            claimed_directions: None,
        };
        assert!(!verify_witness(&attack).ok);
    }

    #[test]
    fn unsat_cert_accepts_rup_proofs_and_rejects_corruption() {
        // (x) ∧ (¬x): the empty clause is RUP from clauses 1, 2.
        let w = Witness::UnsatCert {
            cnf: vec![vec![1], vec![-1]],
            proof: vec![LratStep {
                id: 3,
                literals: vec![],
                hints: vec![1, 2],
                rat_hints: vec![],
            }],
        };
        assert!(verify_witness(&w).ok);
        // (a) ∧ (b) ∧ (¬a ∨ ¬b): empty clause RUP from 1, 2, 3.
        let w2 = Witness::UnsatCert {
            cnf: vec![vec![1], vec![2], vec![-1, -2]],
            proof: vec![LratStep {
                id: 4,
                literals: vec![],
                hints: vec![1, 2, 3],
                rat_hints: vec![],
            }],
        };
        assert!(verify_witness(&w2).ok);
        // Drop the conflict-producing antecedent → no conflict → rejected.
        let bad = Witness::UnsatCert {
            cnf: vec![vec![1], vec![2], vec![-1, -2]],
            proof: vec![LratStep {
                id: 4,
                literals: vec![],
                hints: vec![1, 2],
                rat_hints: vec![],
            }],
        };
        assert!(!verify_witness(&bad).ok);
        // A satisfiable CNF cannot derive the empty clause with any RUP step.
        let sat = Witness::UnsatCert {
            cnf: vec![vec![1, 2]],
            proof: vec![LratStep {
                id: 2,
                literals: vec![],
                hints: vec![1],
                rat_hints: vec![],
            }],
        };
        assert!(!verify_witness(&sat).ok);
    }

    #[test]
    fn crt_partial_cover_accepts_real_rows_and_rejects_corruption() {
        let m = "8168305011630835886634520238999";
        let rows = vec![
            CrtCoverRow {
                p: 5,
                ord2: 4,
                ord3: 4,
                h: 4,
                t_p: 1,
                m_mod_p: 4,
                line: [1, 3, 0, 4],
            },
            CrtCoverRow {
                p: 7,
                ord2: 3,
                ord3: 6,
                h: 6,
                t_p: 1,
                m_mod_p: 6,
                line: [2, 1, 0, 6],
            },
        ];
        assert!(verify_crt_partial_cover(m, &rows).ok);
        // Corrupt t_p.
        let mut bad = rows.clone();
        bad[0].t_p = 2;
        assert!(!verify_crt_partial_cover(m, &bad).ok);
        // Corrupt the affine line.
        let mut bad = rows.clone();
        bad[1].line = [2, 1, 1, 6];
        assert!(!verify_crt_partial_cover(m, &bad).ok);
        // m divisible by 3 is rejected.
        assert!(!verify_crt_partial_cover("9", &rows).ok);
    }

    #[test]
    fn kummer_no_carry_accepts_erdos684_table_and_rejects_corruption() {
        let entries = vec![
            KummerEntry { k: 3, m: 36 },
            KummerEntry { k: 7, m: 88200 },
            KummerEntry { k: 12, m: 64033200 },
        ];
        assert!(verify_kummer_no_carry(&entries).ok);
        // Wrong M_k.
        let bad = vec![KummerEntry { k: 3, m: 72 }];
        assert!(!verify_kummer_no_carry(&bad).ok);
        // Out of guard range.
        assert!(!verify_kummer_no_carry(&[KummerEntry { k: 25, m: 1 }]).ok);
    }

    #[test]
    fn min_binom_gcd_accepts_erdos700_cases_and_rejects_corruption() {
        let cases = vec![
            MinGcdCase { n: 30, f: 6 },
            MinGcdCase { n: 77, f: 7 },
            MinGcdCase { n: 49, f: 7 },
        ];
        assert!(verify_min_binom_gcd(&cases).ok);
        assert!(!verify_min_binom_gcd(&[MinGcdCase { n: 30, f: 5 }]).ok);
    }

    #[test]
    fn binom_deficiency_accepts_els93_row_and_rejects_corruption() {
        // ELS93 table row k=8, N=44: delta=2 at slots [4, 6].
        let good = DeficiencyEntry {
            k: 8,
            n: "44".to_string(),
            delta: 2,
            slots: Some(vec![4, 6]),
        };
        assert!(verify_binom_deficiency(&[good.clone()]).ok);
        // Count-only form.
        let count_only = DeficiencyEntry {
            slots: None,
            ..good.clone()
        };
        assert!(verify_binom_deficiency(&[count_only]).ok);
        // Wrong delta.
        let bad = DeficiencyEntry {
            delta: 1,
            slots: None,
            ..good.clone()
        };
        assert!(!verify_binom_deficiency(&[bad]).ok);
        // Wrong slots.
        let bad = DeficiencyEntry {
            slots: Some(vec![4, 7]),
            ..good
        };
        assert!(!verify_binom_deficiency(&[bad]).ok);
        // A big-N entry (the k=129 delta=1 example) exercises the u128 path.
        let big = DeficiencyEntry {
            k: 129,
            n: "3180883073384828665489".to_string(),
            delta: 1,
            slots: Some(vec![65]),
        };
        assert!(verify_binom_deficiency(&[big]).ok);
    }

    #[test]
    fn binom_exception_enum_matches_els_for_small_k_and_rejects_corruption() {
        // Re-derived ELS exceptions with k <= 8 (49 candidates).
        let els8: Vec<(u64, u64)> = vec![(7, 3), (13, 4), (14, 4), (23, 5), (62, 6), (44, 8)];
        assert!(verify_binom_exception_enum(8, &els8).ok);
        // Missing one exception fails.
        assert!(!verify_binom_exception_enum(8, &els8[1..]).ok);
        // A fabricated extra exception fails.
        let mut padded = els8.clone();
        padded.push((100, 5));
        assert!(!verify_binom_exception_enum(8, &padded).ok);
    }

    #[test]
    fn interval_product_accepts_erdos1056_example_and_rejects_corruption() {
        // erdosproblems.com/1056 example: p=11, cuts [2,4,7].
        // (3·4)=12≡1, (5·6·7)=210≡1 (mod 11).
        assert!(verify_interval_product(11, &[2, 4, 7]).ok);
        // A non-prime modulus is rejected.
        assert!(!verify_interval_product(12, &[2, 4, 7]).ok);
        // Perturb a cut so an interval product is no longer 1 mod p.
        assert!(!verify_interval_product(11, &[2, 4, 8]).ok);
        // Non-increasing cuts are rejected.
        assert!(!verify_interval_product(11, &[4, 4, 7]).ok);
    }

    #[test]
    fn sidon_accepts_valid_and_rejects_corrupted() {
        assert!(verify_sidon(&small_sidon(), 3).ok);
        // Corrupt: add a 4th point that creates a sum collision.
        // 110 + 000 = 110 and 100 + 010 = 110 -> collision.
        let mut bad = small_sidon();
        bad.push(vec![1, 1, 0]);
        assert!(!verify_sidon(&bad, 3).ok, "corrupted Sidon must fail");
    }

    #[test]
    fn packed_binary_sidon_path_matches_coordinate_semantics() {
        let good = small_sidon();
        let result = verify_sidon(&good, 3);
        assert!(result.ok, "{}", result.message);
        assert!(result.message.contains("10 pairwise sums"));

        let collision = vec![vec![0, 0, 0], vec![1, 0, 0], vec![0, 1, 0], vec![1, 1, 0]];
        assert!(!verify_sidon(&collision, 3).ok);
    }

    #[test]
    fn sidon_rejects_non_binary_and_dups() {
        assert!(!verify_sidon(&[vec![0, 2, 0]], 3).ok);
        assert!(!verify_sidon(&[vec![1, 0, 0], vec![1, 0, 0]], 3).ok);
    }

    #[test]
    fn claimed_size_mismatch_fails() {
        let w = Witness::Sidon {
            n: 3,
            points: small_sidon(),
            claimed_size: Some(99),
        };
        let r = verify_witness(&w);
        assert!(!r.ok, "claimed_size 99 != actual 4 must fail");
        assert!(r.message.contains("claimed_size"));
    }

    #[test]
    fn golomb_accepts_valid_and_rejects_corrupted() {
        // {0,1,4,6} is a perfect Golomb ruler (differences 1,4,6,3,5,2).
        assert!(verify_golomb(&[0, 1, 4, 6]).ok);
        // {0,1,2,4}: differences 1,2,4,1,... -> repeat -> fail.
        assert!(!verify_golomb(&[0, 1, 2, 4]).ok);
    }

    #[test]
    fn cap_accepts_valid_and_rejects_collinear() {
        // {0,1} along one axis in F_3^1 is a cap (need 3 for a line).
        assert!(verify_cap(&[vec![0], vec![1]], 1).ok);
        // {0,1,2} in F_3^1: 0+1+2 = 0 mod 3 -> collinear -> fail.
        assert!(!verify_cap(&[vec![0], vec![1], vec![2]], 1).ok);
    }

    #[test]
    fn bh_h2_matches_sidon() {
        assert!(verify_bh(&small_sidon(), 3, 2).ok);
        let mut bad = small_sidon();
        bad.push(vec![1, 1, 0]);
        assert!(!verify_bh(&bad, 3, 2).ok);
    }

    #[test]
    fn covering_accepts_full_and_rejects_gap() {
        // C(4,3,2): blocks {0,1,2},{0,1,3},{0,2,3},{1,2,3} cover every pair.
        let full = vec![vec![0, 1, 2], vec![0, 1, 3], vec![0, 2, 3], vec![1, 2, 3]];
        assert!(verify_covering(&full, 4, 3, 2).ok);
        // Drop a block: pair {2,3} only in {0,2,3} and {1,2,3}; remove both.
        let gap = vec![vec![0, 1, 2], vec![0, 1, 3]];
        assert!(!verify_covering(&gap, 4, 3, 2).ok);
    }

    #[test]
    fn constant_weight_checks_weight_and_distance() {
        // A(4,2,2): {1100, 0011} weight 2, distance 4 >= 2.
        let ok = vec![vec![1, 1, 0, 0], vec![0, 0, 1, 1]];
        assert!(verify_constant_weight(&ok, 4, 2, 2).ok);
        // wrong weight
        assert!(!verify_constant_weight(&[vec![1, 1, 1, 0]], 4, 2, 2).ok);
    }

    #[test]
    fn costas_accepts_valid_and_rejects_nonpermutation() {
        // {0,2,3,1} is a Costas array of order 4.
        assert!(verify_costas(&[0, 2, 3, 1]).ok);
        assert!(!verify_costas(&[0, 0, 1, 2]).ok);
    }

    #[test]
    fn linear_code_verifies_distance_and_refuses_nonprime() {
        // [3,1,3]_2 repetition code: generator [1,1,1], min weight 3.
        let g = vec![vec![1, 1, 1]];
        let r = verify_linear_code(&g, 2, 3);
        assert!(r.ok, "{}", r.message);
        // claim d=4 on a min-weight-3 code must fail.
        assert!(!verify_linear_code(&g, 2, 4).ok);
        // non-prime q refused.
        assert!(!verify_linear_code(&g, 4, 1).ok);
    }

    #[test]
    fn witness_serde_round_trip() {
        let w = Witness::Sidon {
            n: 3,
            points: small_sidon(),
            claimed_size: Some(4),
        };
        let json = serde_json::to_string(&w).unwrap();
        assert!(json.contains("\"kind\":\"sidon\""));
        let back: Witness = serde_json::from_str(&json).unwrap();
        assert_eq!(back, w);
        assert!(verify_witness(&back).ok);
    }
}

#[cfg(test)]
mod balanced_coloring_tests {
    use super::*;
    use std::collections::BTreeMap;

    fn pentagon_k5() -> BTreeMap<String, u32> {
        let pent = [(0, 1), (1, 2), (2, 3), (3, 4), (0, 4)];
        let mut ec = BTreeMap::new();
        for i in 0..5usize {
            for j in (i + 1)..5 {
                let c = if pent.contains(&(i, j)) { 1 } else { 2 };
                ec.insert(format!("{i},{j}"), c);
            }
        }
        ec
    }

    #[test]
    fn pentagon_coloring_is_balanced() {
        let r = verify_balanced_coloring(5, 2, &pentagon_k5());
        assert!(r.ok, "{}", r.message);
    }

    #[test]
    fn flipped_edge_breaks_balance() {
        let mut ec = pentagon_k5();
        ec.insert("0,1".to_string(), 2);
        let r = verify_balanced_coloring(5, 2, &ec);
        assert!(!r.ok);
    }

    #[test]
    fn dominates_orders_by_n_at_same_r() {
        let w5 = Witness::BalancedColoring {
            n: 5,
            r: 2,
            edge_colors: pentagon_k5(),
        };
        let w4 = Witness::BalancedColoring {
            n: 4,
            r: 2,
            edge_colors: BTreeMap::new(),
        };
        assert_eq!(dominates(&w5, &w4), Ok(true));
        assert_eq!(dominates(&w4, &w5), Ok(false));
    }
}

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

    /// cnf: (1 2)(-1 3)(2)(-2) — UNSAT via the unit pair. Step 5 adds
    /// the blocked clause (-1 -2): NOT RUP (clause (2) is satisfied
    /// under the falsifying assignment, blocking propagation) but RAT
    /// on pivot -1 — the only clause containing 1 is (1 2), whose
    /// resolvent {-1,-2,2} is tautological. Step 6 derives empty.
    fn rat_cert() -> (Vec<Vec<i64>>, Vec<LratStep>) {
        let cnf = vec![vec![1, 2], vec![-1, 3], vec![2], vec![-2]];
        let proof = vec![
            LratStep {
                id: 5,
                literals: vec![-1, -2],
                hints: vec![],
                rat_hints: vec![],
            },
            LratStep {
                id: 6,
                literals: vec![],
                hints: vec![3, 4],
                rat_hints: vec![],
            },
        ];
        (cnf, proof)
    }

    #[test]
    fn blocked_clause_step_verifies_as_rat() {
        let (cnf, proof) = rat_cert();
        let r = verify_unsat_cert(&cnf, &proof);
        assert!(r.ok, "{}", r.message);
    }

    #[test]
    fn rat_step_with_unhinted_resolvent_is_rejected() {
        // Add (1 -3) to the cnf: now clauses containing pivot-negation 1
        // are (1 2) [tautological resolvent, fine] AND (1 -3), whose
        // resolvent (-1 -2 -3) is NOT tautological and has no supplied
        // hints — the step must be refused, never guessed through.
        let (mut cnf, proof) = rat_cert();
        cnf.push(vec![1, -3]);
        let r = verify_unsat_cert(&cnf, &proof);
        assert!(!r.ok);
        assert!(
            r.message.contains("neither RUP-implied nor RAT"),
            "{}",
            r.message
        );
    }

    #[test]
    fn rat_with_supplied_resolvent_hints_verifies() {
        // Same extended cnf, but the step now supplies hints proving the
        // (1 -3) resolvent (-1 -2 -3) is RUP: falsify 1=T,2=T,3=T; then
        // clause (-2) [id 4] conflicts immediately.
        let (mut cnf, mut proof) = rat_cert();
        cnf.push(vec![1, -3]); // becomes clause id 5
        proof[0].id = 6;
        proof[0].rat_hints = vec![(5, vec![4])];
        proof[1].id = 7;
        let r = verify_unsat_cert(&cnf, &proof);
        assert!(r.ok, "{}", r.message);
    }

    #[test]
    fn unit_fraction_decomp_checks_exactness_coverage_and_ordering() {
        let c = |n, x, y, z| UnitFractionCase { n, x, y, z };
        // 4/3 = 1/1+1/4+1/12, 4/4 = 1/2+1/3+1/6, 4/5 = 1/2+1/4+1/20 (all exact, x<y<z).
        let good = vec![c(3, 1, 4, 12), c(4, 2, 3, 6), c(5, 2, 4, 20)];
        assert!(verify_unit_fraction_decomp(5, &good).ok);
        // A gap (missing n=4) fails coverage.
        assert!(!verify_unit_fraction_decomp(5, &[c(3, 1, 4, 12), c(5, 2, 4, 20)]).ok);
        // Inexact arithmetic fails (1/1+1/4+1/13 != 4/3).
        assert!(!verify_unit_fraction_decomp(3, &[c(3, 1, 4, 13)]).ok);
        // Non-distinct / non-ordered fails (y == z).
        assert!(!verify_unit_fraction_decomp(4, &[c(3, 1, 4, 12), c(4, 2, 6, 6)]).ok);
        // Out-of-range n fails.
        assert!(!verify_unit_fraction_decomp(3, &[c(3, 1, 4, 12), c(7, 2, 4, 28)]).ok);
    }

    #[test]
    fn distinct_partial_sums_checks_validity_coverage_and_primality() {
        // p = 3, F_3\{0} = {1,2}. Subsets {1},{2},{1,2}; expected 2^2-1 = 3.
        // [1]->(1); [2]->(2); [1,2]->(1,0) all distinct mod 3.
        let full = vec![vec![1u64], vec![2], vec![1, 2]];
        assert!(verify_distinct_partial_sums(3, &full).ok);
        // Missing {2} -> incomplete coverage.
        assert!(!verify_distinct_partial_sums(3, &[vec![1u64], vec![1, 2]]).ok);
        // A repeated partial sum: [3,3] is moot; use p=5, ordering [1,4] -> (1,0) ok,
        // but [2,3] -> (2,0) ok; force a bad one: [1,2,2] invalid (repeat elt). Test a
        // genuine repeated-sum: in F_5, [4,1] -> (4,0); [1,4] -> (1,0); both fine.
        // Repeated partial sum example: subset {2,3} in F_5 ordered [2,3] -> (2,0); fine.
        // Construct an explicit repeat: ordering [1,4,5%? ] — instead test out-of-range.
        assert!(!verify_distinct_partial_sums(3, &[vec![1u64], vec![2], vec![1, 5]]).ok);
        // Non-prime p fails.
        assert!(!verify_distinct_partial_sums(4, &[vec![1u64]]).ok);
    }

    #[test]
    fn powerful_triples_none_confirms_no_triple_and_counts_pairs() {
        // No three consecutive powerful integers up to 1000 (true).
        let r = verify_powerful_triples_none(1000, None);
        assert!(r.ok, "{}", r.message);
        // (8,9) is a consecutive powerful pair, so at least one exists.
        assert!(r.message.contains("pairs exist"));
        // A wrong pairs_claimed is rejected.
        assert!(!verify_powerful_triples_none(1000, Some(0)).ok);
        // 8 = 2^3 powerful, 9 = 3^2 powerful, 7 = prime not powerful: the pair
        // (8,9) is found but never a triple.
        assert!(verify_powerful_triples_none(10, None).ok);
    }

    #[test]
    fn two_full_three_full_finds_the_complete_set() {
        // No 2-full n with n+1 3-full in [1,100] (3-full n+1 in {8,16,27,32,64,81}
        // give n in {7,15,26,31,63,80}, none powerful).
        assert!(verify_two_full_three_full(100, &[]).ok);
        // A spurious claim is rejected.
        assert!(!verify_two_full_three_full(100, &[8]).ok);
        // A missing example is rejected: if any exists in range, [] must fail.
        // (Construct via a tiny range where the set is known empty -> [] passes.)
        assert!(verify_two_full_three_full(10, &[]).ok);
    }

    // Smallest prime p > n for which (n!+1) is a non-residue mod p (mirrors the
    // #398 generator); used to build a valid certificate inside the test.
    fn brocard_witness(n: u64) -> u64 {
        fn is_prime(n: u64) -> bool {
            if n < 2 {
                return false;
            }
            let mut d = 2;
            while d * d <= n {
                if n.is_multiple_of(d) {
                    return false;
                }
                d += 1;
            }
            true
        }
        fn modpow(mut b: u128, mut e: u128, m: u128) -> u128 {
            let mut r = 1u128;
            b %= m;
            while e > 0 {
                if e & 1 == 1 {
                    r = r * b % m;
                }
                e >>= 1;
                b = b * b % m;
            }
            r
        }
        let mut p = n + 1;
        loop {
            if is_prime(p) {
                let pm = p as u128;
                let mut f = 1u128;
                for k in 1..=n {
                    f = f * (k as u128) % pm;
                }
                let r = (f + 1) % pm;
                if r != 0 && modpow(r, (pm - 1) / 2, pm) == pm - 1 {
                    return p;
                }
            }
            p += 1;
        }
    }

    #[test]
    fn brocard_no_square_certifies_a_range_and_rejects_tampering() {
        // [8,40]: all non-exceptions, each with a generated witnessing prime.
        let (n_min, n_max) = (8u64, 40u64);
        let cases: Vec<BrocardCase> = (n_min..=n_max)
            .map(|n| BrocardCase {
                n,
                p: brocard_witness(n),
            })
            .collect();
        let w = Witness::BrocardNoSquare {
            n_min,
            n_max,
            cases: cases.clone(),
        };
        let r = verify_witness(&w);
        assert!(r.ok, "should certify [{n_min},{n_max}]: {}", r.message);

        // The known-solution branch: [4,7] has squares at 4,5,7 and a non-square at 6.
        let known = Witness::BrocardNoSquare {
            n_min: 4,
            n_max: 7,
            cases: vec![
                BrocardCase { n: 4, p: 0 },
                BrocardCase { n: 5, p: 0 },
                BrocardCase {
                    n: 6,
                    p: brocard_witness(6),
                },
                BrocardCase { n: 7, p: 0 },
            ],
        };
        assert!(
            verify_witness(&known).ok,
            "4,5,7 are the known squares; 6 is not"
        );

        // Tamper 1: a composite "witnessing prime" must be rejected.
        let mut bad = cases.clone();
        bad[0].p = bad[0].n * (bad[0].n + 1); // composite, > n
        assert!(
            !verify_witness(&Witness::BrocardNoSquare {
                n_min,
                n_max,
                cases: bad,
            })
            .ok,
            "a non-prime witness must fail"
        );
        // Tamper 2: dropping a case breaks coverage.
        let short: Vec<BrocardCase> = cases[1..].to_vec();
        assert!(
            !verify_witness(&Witness::BrocardNoSquare {
                n_min,
                n_max,
                cases: short,
            })
            .ok,
            "incomplete coverage must fail"
        );
        // Tamper 3: claiming a non-exception n is a known square fails (n=8 not in {4,5,7}).
        assert!(
            !verify_witness(&Witness::BrocardNoSquare {
                n_min: 8,
                n_max: 8,
                cases: vec![BrocardCase { n: 8, p: 0 }],
            })
            .ok,
            "n=8 with no witnessing prime must fail (8 is not a known square and p=0 invalid)"
        );
    }

    #[test]
    fn semiprime_egyptian_checks_decompositions_and_rejections() {
        // Hand-verified distinct-semiprime Egyptian expansions:
        //   1/6 = [6];  4/15 = 1/6+1/10;  7/30 = 1/6+1/15;  1/3 = 1/6+1/10+1/15.
        let good = Witness::SemiprimeEgyptian {
            cases: vec![
                SemiprimeEgyptianCase {
                    a: 1,
                    b: 6,
                    denominators: vec![6],
                },
                SemiprimeEgyptianCase {
                    a: 4,
                    b: 15,
                    denominators: vec![6, 10],
                },
                SemiprimeEgyptianCase {
                    a: 7,
                    b: 30,
                    denominators: vec![6, 15],
                },
                SemiprimeEgyptianCase {
                    a: 1,
                    b: 3,
                    denominators: vec![6, 10, 15],
                },
            ],
        };
        let r = verify_witness(&good);
        assert!(r.ok, "valid semiprime-Egyptian cases: {}", r.message);

        // A non-semiprime denominator (12 = 2^2*3, not squarefree) is rejected.
        assert!(
            !verify_semiprime_egyptian(&[SemiprimeEgyptianCase {
                a: 1,
                b: 12,
                denominators: vec![12],
            }])
            .ok,
            "12 is not a squarefree semiprime"
        );
        // 30 = 2*3*5 has THREE prime factors -> rejected.
        assert!(
            !verify_semiprime_egyptian(&[SemiprimeEgyptianCase {
                a: 1,
                b: 30,
                denominators: vec![30],
            }])
            .ok,
            "30 has three prime factors"
        );
        // A sum that does not equal a/b is rejected (1/6 != 1/5).
        assert!(
            !verify_semiprime_egyptian(&[SemiprimeEgyptianCase {
                a: 1,
                b: 5,
                denominators: vec![6],
            }])
            .ok,
            "1/6 != 1/5"
        );
        // Non-increasing denominators are rejected.
        assert!(
            !verify_semiprime_egyptian(&[SemiprimeEgyptianCase {
                a: 4,
                b: 15,
                denominators: vec![10, 6],
            }])
            .ok,
            "denominators must be strictly increasing"
        );
        // A non-squarefree target denominator b is rejected (b=12).
        assert!(
            !verify_semiprime_egyptian(&[SemiprimeEgyptianCase {
                a: 1,
                b: 12,
                denominators: vec![14, 21],
            }])
            .ok,
            "b=12 is not squarefree"
        );
    }
}