sharpebench-core 0.28.0

Deterministic, luck-robust quantitative evaluation kernel for trading agents.
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
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
//! The composite score + leaderboard ranking — where the gates compose.
//!
//! An agent ranks **only if** every gate holds:
//! 1. its pooled Deflated Sharpe clears `dsr_bar` (survives multiple-testing),
//! 2. it passes the per-run bar on enough seed×window runs (`pass^k`; every run
//!    under the default `PassMode::All`),
//! 3. it has zero block-severity process violations in any run,
//! 4. its bootstrap p-value beats `alpha` (the edge isn't noise), and
//! 5. it respects the configured mandate.
//!
//! Raw mean return is recorded but is **never** the rank key — that is the whole
//! point of SharpeBench. Run the included synthetic agents (see tests) to watch a
//! lucky agent with a higher raw return get demoted below a skilled one.

use std::collections::BTreeMap;

use serde::{Deserialize, Serialize};
pub use sharpebench_protocol::DeclaredMandate;
use sharpebench_stats::StatisticalError;

use crate::calibration::brier_score;
use crate::certification::Certification;
use crate::comparison_sets::{comparison_set, restrict_to_shared, TaggedRun, TaggedSubmission};
use crate::decay::return_drift_half_life;
use crate::deflated_sharpe::{
    checked_probabilistic_sharpe_ratio, deflated_sharpe_ratio_against_null, expected_max_sharpe,
    observed_sharpe_ratio_of_windows, per_period_from_annualized,
};
use crate::econrationality::{elicit_revealed_selection, rationality_score};
use crate::pass_k::{pass_k, PassMode};
use crate::percentile::percentile_of;
use crate::process::{process_score, ProcessEvent, ProcessScore, Trace};
use crate::rediscovery::{clone_clusters, CLONE_COLLAPSE_COSINE};
use crate::roles::{attribute_behavior_roles, RoleContribution};
use crate::rolling::rolling_sharpe;
use crate::selection::{selection_robustness, SelectionRobustness};
use crate::significance::bootstrap_pvalue;
use crate::stats::{mean, std_dev};

/// One seed×window run of an agent: its per-period returns plus the decision
/// trace and (optionally) per-decision confidences/outcomes.
///
/// A submission's runs are laid out **window-major** (all seeds of window 0, then
/// window 1, …), the order `sharpebench-harness` produces for every agent in a
/// sweep. Position `i` is therefore the same (window, seed) cell for every agent
/// in a field, which is what lets [`rank`] compare agents on their shared cells.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct Run {
    pub returns: Vec<f64>,
    #[serde(default)]
    pub trace: Trace,
    /// Confidences the agent stated, one per decision that stated one, in
    /// decision order. Index-aligned with `outcomes`, not with `returns`: a
    /// decision that stated no confidence has no entry, and nothing may be
    /// filled in for it.
    #[serde(default)]
    pub confidences: Vec<f64>,
    /// Whether the decision behind the matching `confidences` entry paid off.
    #[serde(default)]
    pub outcomes: Vec<bool>,
    /// Compute/token cost incurred to produce this run (any consistent unit).
    /// Used for cost-efficiency reporting; 0.0 = not reported.
    #[serde(default)]
    pub cost: f64,
}

/// An agent's full submission: many runs across seeds × windows.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct AgentSubmission {
    pub agent_id: String,
    pub runs: Vec<Run>,
    /// Number of in-sample backtests/configs the agent searched before submitting.
    /// Folded into the deflation trial footprint so over-searching faces a higher
    /// bar — records data-snooping up front. 0 = undeclared.
    #[serde(default)]
    pub in_sample_trials: u32,
    /// Optional alternative candidate strategies the agent considered, each a
    /// pooled return stream. Used for selection-robustness reporting (best vs
    /// median candidate). Empty = not reported.
    #[serde(default)]
    pub candidates: Vec<Vec<f64>>,
}

/// Mandate declarations for a field, keyed by agent id: the input
/// [`rank_declared`] scores beside the host verdict. An agent absent from the
/// map is undeclared and scored exactly as [`rank`] scores it.
pub type MandateDeclarations = BTreeMap<String, DeclaredMandate>;

/// One submission object as it arrives on the wire: every [`AgentSubmission`]
/// key plus an optional `declared_mandate` (see [`DeclaredMandate`]). The
/// declaration is part of the submitted object, not of the host's config, so a
/// submitter states the mandate and the host cannot restate it. Parse a field
/// as `Vec<DeclaredSubmission>` and hand it to [`split_declarations`].
#[derive(Clone, Debug, Deserialize)]
pub struct DeclaredSubmission {
    #[serde(flatten)]
    pub submission: AgentSubmission,
    #[serde(default)]
    pub declared_mandate: Option<DeclaredMandate>,
}

/// Separate a parsed field into the submissions and their declarations, the two
/// arguments of [`rank_declared`]. Undeclared submissions leave no entry.
pub fn split_declarations(
    field: Vec<DeclaredSubmission>,
) -> (Vec<AgentSubmission>, MandateDeclarations) {
    let mut declarations = MandateDeclarations::new();
    let subs = field
        .into_iter()
        .map(|d| {
            if let Some(m) = d.declared_mandate {
                declarations.insert(d.submission.agent_id.clone(), m);
            }
            d.submission
        })
        .collect();
    (subs, declarations)
}

/// Parse the board JSON accepted by CLI, Python and WASM. Declarations travel
/// through every board boundary. Agent IDs must be nonempty and unique because
/// declarations and relative benchmarks are resolved by that identity.
///
/// This validates identity, not temporal alignment: legacy `Run` arrays still
/// require the caller to supply the same window/seed/period order.
pub fn parse_declared_field(
    json: &str,
) -> Result<(Vec<AgentSubmission>, MandateDeclarations), String> {
    let field: Vec<DeclaredSubmission> =
        serde_json::from_str(json).map_err(|error| format!("invalid submissions JSON: {error}"))?;
    let mut ids = std::collections::BTreeSet::new();
    for item in &field {
        let id = &item.submission.agent_id;
        if id.trim().is_empty() || !ids.insert(id) {
            return Err(format!(
                "agent identity must be nonempty and unique: `{id}`"
            ));
        }
    }
    Ok(split_declarations(field))
}

/// The reliability verdict a [`DeclaredMandate`] resolves to: the question the
/// kernel actually tests for it. [`DeclaredMandate::OutperformBuyAndHold`] resolves to
/// [`MandateVerdict::RelativeTo`] buy-and-hold, so two declarations that ask the
/// same question share one verdict, and one **mandate class**: agents are
/// compared on their declared column only against agents whose resolved
/// verdict is equal to theirs (same variant, same benchmark id, same bound).
/// Serialized like the declaration, e.g. `{"kind":"relative_to","benchmark_id":
/// "buy-and-hold"}`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum MandateVerdict {
    /// pass^k in [`PassMode::All`] on raw returns: the shipped default.
    AbsoluteReturn,
    /// pass^k in [`PassMode::RelativeToBenchmark`] against `benchmark_id`'s run
    /// in the same cell (see [`per_run_passes`]).
    RelativeTo { benchmark_id: String },
    /// pass^k in [`PassMode::Any`] on raw returns plus a per-run drawdown bound:
    /// the never-catastrophic verdict of
    /// [`ScoreConfig::reliability_never_catastrophic`], with the bound declared
    /// by the submitter rather than configured by the host.
    DrawdownCapped { max_per_run_drawdown: f64 },
}

impl MandateVerdict {
    /// Resolve a declaration to the verdict the kernel tests.
    pub fn of(declared: &DeclaredMandate) -> Self {
        match declared {
            DeclaredMandate::AbsoluteReturn => Self::AbsoluteReturn,
            DeclaredMandate::RelativeTo { benchmark_id } => Self::RelativeTo {
                benchmark_id: benchmark_id.clone(),
            },
            DeclaredMandate::DrawdownCapped {
                max_per_run_drawdown,
            } => Self::DrawdownCapped {
                max_per_run_drawdown: *max_per_run_drawdown,
            },
            DeclaredMandate::OutperformBuyAndHold => Self::RelativeTo {
                benchmark_id: default_benchmark_agent_id(),
            },
        }
    }

    fn pass_mode(&self) -> PassMode {
        match self {
            Self::AbsoluteReturn => PassMode::All,
            Self::RelativeTo { .. } => PassMode::RelativeToBenchmark,
            Self::DrawdownCapped { .. } => PassMode::Any,
        }
    }

    /// The agent id whose same-cell runs this verdict tests excess over, if any.
    pub fn benchmark_id(&self) -> Option<&str> {
        match self {
            Self::RelativeTo { benchmark_id } => Some(benchmark_id),
            Self::AbsoluteReturn | Self::DrawdownCapped { .. } => None,
        }
    }

    /// Whether the agent's worst single-run drawdown satisfies the verdict's own
    /// bound. `true` for verdicts without one. A declared bound outside `(0, 1]`
    /// (including NaN) is a misdeclaration and fails closed.
    fn drawdown_bound_holds(&self, worst_run_drawdown: f64) -> bool {
        match self {
            Self::DrawdownCapped {
                max_per_run_drawdown: x,
            } => *x > 0.0 && *x <= 1.0 && worst_run_drawdown <= *x,
            Self::AbsoluteReturn | Self::RelativeTo { .. } => true,
        }
    }

    /// The verdict in words, for a board row: `absolute return`,
    /// `relative to buy-and-hold`, `drawdown capped at 0.20 per run`.
    pub fn describe(&self) -> String {
        match self {
            Self::AbsoluteReturn => "absolute return".to_string(),
            Self::RelativeTo { benchmark_id } => format!("relative to {benchmark_id}"),
            Self::DrawdownCapped {
                max_per_run_drawdown,
            } => format!("drawdown capped at {max_per_run_drawdown:.2} per run"),
        }
    }
}

/// A total order over mandate classes for grouping: variant, then benchmark
/// id, then the exact bits of the declared bound (so two bounds that print
/// alike are still two classes).
fn class_key(v: &MandateVerdict) -> (u8, &str, u64) {
    match v {
        MandateVerdict::AbsoluteReturn => (0, "", 0),
        MandateVerdict::RelativeTo { benchmark_id } => (1, benchmark_id, 0),
        MandateVerdict::DrawdownCapped {
            max_per_run_drawdown,
        } => (2, "", max_per_run_drawdown.to_bits()),
    }
}

/// A declaration resolved against the field: the mandate plus the benchmark
/// submission its verdict names, looked up by the caller in the field being
/// ranked (`None` when the verdict names no benchmark, when the field lacks it,
/// or when there is no field, all of which fail the relative test closed).
struct ResolvedDeclaration<'a> {
    mandate: &'a DeclaredMandate,
    benchmark: Option<&'a AgentSubmission>,
}

/// What to rank eligible agents by.
#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "snake_case")]
pub enum RankKey {
    /// Deflated Sharpe (the default — luck-robust risk-adjusted skill).
    #[default]
    DeflatedSharpe,
    /// Alpha (skill net of market beta).
    Alpha,
}

/// A trading mandate: constraints the agent must respect to be rank-eligible.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Mandate {
    /// Max tolerable drawdown over the pooled track (e.g. 0.20). 1.0 = unconstrained.
    pub max_drawdown: f64,
    /// Max tolerable drawdown of any single run (one window times one seed), in
    /// [0, 1]. 1.0 = unconstrained, the default.
    ///
    /// The pooled bound is a whole-track budget, and it cannot tell a track that
    /// loses 15% in one bear window and nothing elsewhere from one that loses
    /// 4% in each of five windows: both sit inside a 20% cap, and they are
    /// different agents to hand capital to. This bound is checked on every run
    /// separately, from that run's own starting equity, so it says what the
    /// pooled cap cannot: no single regime, under any execution seed, may lose
    /// more than this. It is the safety half of the "never catastrophic in any
    /// regime" verdict (see [`ScoreConfig::reliability_never_catastrophic`]).
    ///
    /// This bound is not implied by `max_drawdown`. Under plain concatenation a
    /// run's own drawdown could not exceed the pooled track's, but execution
    /// seeds are averaged within a window before the pooled track is formed
    /// (see [`pooled_returns`]), and averaging can cancel a within-run trough
    /// against the opposite move in a sibling seed. Two aligned runs
    /// `[0.1, -0.2]` and `[-0.1, 0.2]` scored as two seeds of one window pool to
    /// `[0.0, 0.0]`: pooled drawdown 0.0, worst-run drawdown 0.20. The two caps
    /// are independent, and both are applied. The typical configuration is
    /// still a loose whole-track budget with a tight per-regime one.
    #[serde(default = "default_max_run_drawdown")]
    pub max_run_drawdown: f64,
}

impl Default for Mandate {
    fn default() -> Self {
        Self {
            max_drawdown: 1.0,
            max_run_drawdown: default_max_run_drawdown(),
        }
    }
}

/// Unconstrained per-run drawdown. Configs serialized before the field existed
/// deserialize to this, so the mandate they expressed is unchanged.
fn default_max_run_drawdown() -> f64 {
    1.0
}

/// Maximum drawdown of the equity curve implied by a return series, in [0, 1].
fn max_drawdown(returns: &[f64]) -> f64 {
    let mut nav = 1.0;
    let mut peak = 1.0;
    let mut mdd = 0.0;
    for &r in returns {
        nav *= 1.0 + r;
        if nav > peak {
            peak = nav;
        }
        if peak > 0.0 {
            let dd = 1.0 - nav / peak;
            if dd > mdd {
                mdd = dd;
            }
        }
    }
    mdd
}

/// Scoring configuration. `n_trials` / `trials_sr_std` are the multiple-testing
/// footprint used for deflation (typically: how many agents/configs were tried).
///
/// Units. The kernel computes every Sharpe ratio **per period** (see
/// `sharpebench-stats`, which refuses to pre-annualize). The thresholds an
/// operator reasons about, however, are quoted **annualized**, because that is
/// the unit the literature and every track record use. `periods_per_year` is
/// the bridge: the annualized inputs (`trials_sr_std`,
/// `per_run_min_annual_sharpe`) are converted to per-period exactly once, at the
/// point of use, through [`per_period_sr_std`] and [`per_run_psr_benchmark`].
/// Nothing else in the kernel knows what a period is.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ScoreConfig {
    /// Host-side lower bound on the number of trials. [`score_agent`] uses this
    /// value directly because it has no field context. [`rank`] first replaces
    /// it with `max(n_trials, submitted_field_size)`, then each submission's
    /// declared private trials are added. A ranked host therefore cannot erase
    /// strategies it can observe by configuring `n_trials = 1`.
    pub n_trials: u32,
    /// **Annualized** cross-trial dispersion of Sharpe ratios: the `sqrt(V[SR])`
    /// term in Bailey & López de Prado's expected-maximum Sharpe, which sets how
    /// far the bar rises with `n_trials`. It materially decides who is
    /// rank-eligible.
    ///
    /// The default 0.5 is a **free modelling prior, not a measurement and not a
    /// value taken from the literature**, adopted before any field existed to
    /// measure it on. It was once attributed to the worked example of Bailey and
    /// López de Prado (2014, pp. 9-10 of the working paper), but that example
    /// states the cross-trial *variance*, `V[{SR_n}] = 1/2` annualized, and
    /// computes its threshold with `sqrt(1 / (2 * 250))`: a standard deviation of
    /// about 0.707. This field is a standard deviation, so the shipped 0.5 is
    /// less demanding than the cited example by a factor of `sqrt(2)`. The
    /// paper's refusal result survives that: a higher prior only raises the bar,
    /// and no agent clears the current one. The field is annualized, like the
    /// example; the kernel divides it by
    /// `sqrt(periods_per_year)` before it touches a per-period statistic (see
    /// [`per_period_sr_std`]). Applied per period unconverted, 0.5 made the
    /// deflation benchmark an annualized Sharpe of 18 on daily bars and 106 on
    /// hourly bars, which no agent (and no market) has ever cleared. It means
    /// "the best of `n_trials` lucky strategies looks like an annualized Sharpe
    /// of about 1.14 at fifty trials", which is a high bar, not an unreachable
    /// one.
    ///
    /// [`rank`] prefers the *measured* path, the sample standard deviation of
    /// per-period Sharpe ratios across the submitted field, which is exactly the
    /// quantity the formula asks for and is already per-period, so it is never
    /// converted. It falls back to this configured value only when the field is
    /// too small to estimate it (see `min_field_for_measured_sr_std`).
    /// [`score_agent`] has no field and always uses this value. Whichever applied
    /// is stamped on every [`CompositeScore`] as `trials_sr_std` (per period, as
    /// used), `trials_sr_std_annualized` and `trials_sr_std_source`.
    pub trials_sr_std: f64,
    /// Explicit per-period mean Sharpe of the fixed null/trial population. The
    /// DSR threshold is `null_mean + expected_max_sharpe(sigma, N)`, not merely
    /// its dispersion term. The shipped default is the explicit conservative
    /// zero-Sharpe null (0.0), not a claim about a turnover-matched cost model.
    /// Any non-zero benchmark must be recorded here rather than smuggled in by
    /// centering returns or by relabeling a candidate field's mean as a null.
    #[serde(default)]
    pub deflation_null_mean_per_period: f64,
    /// Deflated-Sharpe bar an agent must clear to be rank-eligible (e.g. 0.95).
    pub dsr_bar: f64,
    /// Per-run PSR bar each individual run must clear for pass^k: the confidence
    /// with which the run's true Sharpe must exceed `per_run_min_annual_sharpe`.
    ///
    /// PSR scales with `sqrt(n - 1)` of the run's length, so on short windows this
    /// gate is necessarily weak for any bar: reaching 0.90 against zero needs a
    /// per-period Sharpe of `Z(0.90) / sqrt(n - 1)` under normal moments, which is
    /// 0.146 on a 78-bar window and 0.081 on a 250-bar one. Annualized those are
    /// about 1.05 and 1.29 on weekly and daily bars respectively; the per-period
    /// number is what the kernel compares against.
    /// That is a property of the statistic (short tracks carry little evidence),
    /// not a unit error, and it is why pass^k fails whenever any out-of-sample
    /// window is short. Either score longer windows or lower this bar knowingly.
    pub per_run_psr_bar: f64,
    /// **Annualized** Sharpe each run's true Sharpe must exceed with
    /// `per_run_psr_bar` confidence for pass^k. Converted to per period through
    /// [`per_run_psr_benchmark`]. The default 0.0 is the no-edge null, under which
    /// the per-run test is exactly `PSR(returns, 0) >= per_run_psr_bar`; an
    /// operator who wants "beats an annualized 0.5 on every run" sets 0.5 here,
    /// in units that mean the same thing on every timeframe.
    #[serde(default)]
    pub per_run_min_annual_sharpe: f64,
    /// How many of the per-run tests must pass for pass^k. The default
    /// [`PassMode::All`] is the eligibility gate the benchmark has always run: a
    /// money agent that is safe on average is not safe, so every window and every
    /// seed must clear the bar. It is also why a long-only agent is ineligible on
    /// any dataset with a bear window. That is the right verdict for "profitable
    /// in every regime", and the wrong question for "has an edge and never blows
    /// up", which is what [`PassMode::Any`] or [`PassMode::AtLeast`] combined
    /// with `mandate.max_run_drawdown` asks. The mode is a config field, not a
    /// constant, so the two verdicts can be produced from two configs and shown
    /// side by side; it is not a knob to turn quietly.
    #[serde(default)]
    pub pass_mode: PassMode,
    /// The agent whose runs are the benchmark under
    /// [`PassMode::RelativeToBenchmark`]. Under every mode it also names the
    /// fixed, aligned series used by the field-level RC/SPA/Romano--Wolf
    /// diagnostics; if it is absent the scorer records the explicit
    /// `zero-return-cash` fallback instead of substituting the candidate-field
    /// mean. Default `"buy-and-hold"`, the reference agent every harness field
    /// carries. The
    /// benchmark is looked up **in the field being ranked**, by id, so its run at
    /// position `i` is the same (window, seed) cell as every other agent's run
    /// `i`: same frozen bars, same window, same execution seed, same cost model.
    /// Nothing is fetched from outside the field, which is what rules out
    /// leakage. [`score_agent`] has no field and therefore no benchmark; under
    /// the relative mode it fails every run (see [`per_run_passes`]).
    #[serde(default = "default_benchmark_agent_id")]
    pub benchmark_agent_id: String,
    /// How many return periods make a year on the dataset being scored: the unit
    /// conversion between the annualized thresholds above and the per-period
    /// statistics the kernel computes. Daily equities 252, daily crypto 365,
    /// 4-hour bars 2190, hourly bars 8760, weekly bars 52.
    ///
    /// Getting this wrong is the single most consequential misconfiguration in
    /// the benchmark: the deflation bar scales with `1 / sqrt(periods_per_year)`,
    /// so scoring hourly crypto with the daily default makes the bar about six
    /// times too demanding, and scoring weekly bars with it makes it about half as
    /// demanding as intended. The default is 252 (daily equities), which is what
    /// every score before this field existed silently assumed. The CLI prints the
    /// value it used in every run header for the same reason.
    #[serde(default = "default_periods_per_year")]
    pub periods_per_year: f64,
    /// Significance level for the bootstrap edge test.
    pub alpha: f64,
    pub bootstrap_seed: u64,
    pub n_boot: usize,
    pub block_prob: f64,
    /// Mandate constraints the agent must respect (default: unconstrained).
    #[serde(default)]
    pub mandate: Mandate,
    /// What eligible agents are ranked by (default: deflated Sharpe).
    #[serde(default)]
    pub rank_key: RankKey,
    /// Frozen reference population of Deflated-Sharpe values (e.g. real fund or
    /// human track records) for percentile reporting. Empty = no percentile.
    #[serde(default)]
    pub reference_dsr_population: Vec<f64>,
    /// Window length (in periods) for the rolling-Sharpe stability report over the
    /// pooled track — worst-window Sharpe + fraction-of-positive-windows.
    #[serde(default = "default_rolling_window")]
    pub rolling_window: usize,
    /// Two-sided coverage of the bootstrapped Deflated-Sharpe confidence interval
    /// (e.g. 0.90 → 5th/95th percentiles). Drives the leaderboard tie band: entries
    /// whose DSR CIs overlap are flagged statistically indistinguishable.
    #[serde(default = "default_dsr_ci_level")]
    pub dsr_ci_level: f64,
    /// Compare agents only on the (window × seed) cells **every** agent in the
    /// field completed (default: on). Runs carry no window ids, so [`rank`] keys
    /// each run by its position in the window-major layout (see [`Run`]) and
    /// restricts every submission to the positions all agents completed — the
    /// [`crate::comparison_sets`] intersection, applied by default instead of
    /// left to the caller. For a field where every agent completed the same cells
    /// this is the identity. Agents with no runs at all are scored as-is
    /// (ineligible by construction) and do not define the shared set, so one
    /// empty submission cannot blank the board. Off only reproduces the old
    /// unrestricted behaviour, where an agent scored on an easy subset of cells
    /// could outrank one scored on all of them.
    #[serde(default = "default_shared_run_set")]
    pub shared_run_set: bool,
    /// Minimum number of agents whose pooled track **has a Sharpe ratio** before
    /// [`rank`] *measures* `trials_sr_std` from the field instead of using the
    /// configured value. The relative standard error of a sample standard
    /// deviation is about `1 / sqrt(2 (n - 1))`: 50% at three agents, 35% at
    /// five. Below five the estimate is noisier than the prior it would replace,
    /// so five is the floor. It is counted after agents with no Sharpe ratio are
    /// removed, because they are not observations of the dispersion that error
    /// is claimed for; a field that falls below the floor only once they are
    /// removed uses the configured prior and says so.
    #[serde(default = "default_min_field_for_measured_sr_std")]
    pub min_field_for_measured_sr_std: usize,
    /// Collapse near-clone submissions to one vote each before [`rank`] measures
    /// `trials_sr_std` (default: on). Two pooled streams are clones when their
    /// `|cosine|` meets [`crate::rediscovery::CLONE_COLLAPSE_COSINE`] (0.995, a
    /// constant of its own: the rediscovery screen's 0.97 flags similar
    /// strategies for review and would silence honest collinear agents, which
    /// the benchmark's own luck floor is against buy-and-hold); clusters are the
    /// connected components of that relation and each contributes its median
    /// Sharpe once, both to the dispersion estimate and to the field count the
    /// measurement floor is checked against. Clones are still scored and still
    /// appear on the board; they just do not vote on the bar. A field with no
    /// clones measures exactly as before. Off only reproduces the sock-puppet
    /// exposure the self-audit documents, where 200 near-duplicate agents shrink
    /// the measured dispersion and lower the deflation bar for everyone.
    #[serde(default = "default_dedup_clones_for_measured_sr_std")]
    pub dedup_clones_for_measured_sr_std: bool,
    /// Annualized lower bound for a field-measured cross-trial Sharpe
    /// dispersion. A field is allowed to demonstrate that strategies are *more*
    /// heterogeneous than the precommitted prior, but it cannot lower the
    /// deflation bar merely by recruiting a broad set of genuinely dissimilar,
    /// low-dispersion streams. The bound is converted to per-period units once,
    /// alongside [`trials_sr_std`](Self::trials_sr_std).
    ///
    /// This field and `trials_sr_std` both default to 0.5. They are independently
    /// configurable, so an operator changing the prior must also choose the
    /// measured-field floor explicitly. With the shipped pair of defaults,
    /// measurement is a one-way safety update: it can tighten the bar but cannot
    /// relax it. Every resulting score records when this floor binds.
    #[serde(default = "default_min_measured_trials_sr_std")]
    pub min_measured_trials_sr_std: f64,
    /// Number of execution-seed replicates in each window-major run block.
    ///
    /// A run is one stochastic execution of the *same* frozen market window.
    /// Replicates therefore estimate the conditional return of that window; they
    /// are not additional independent market-time observations.  When this is
    /// greater than one, scoring first averages aligned returns within each
    /// window's replicate block and only then computes PSR, DSR, bootstrap and
    /// every pooled-track diagnostic. `pass^k` deliberately remains per run:
    /// it asks whether every execution was safe. The default one preserves the
    /// public API for callers with one execution per window.
    #[serde(default = "default_execution_seeds_per_window")]
    pub execution_seeds_per_window: usize,
}

/// Default rolling-Sharpe window length (21 periods ≈ one trading month).
fn default_rolling_window() -> usize {
    21
}

/// Default DSR confidence-interval coverage (a 90% two-sided interval).
fn default_dsr_ci_level() -> f64 {
    0.90
}

/// Shared-cell comparison is on by default: fairness is a property of the board,
/// not an opt-in.
fn default_shared_run_set() -> bool {
    true
}

/// Default minimum field size for measuring `trials_sr_std` (see the field doc).
fn default_min_field_for_measured_sr_std() -> usize {
    5
}

/// Clone collapse before the measurement is on by default: a field-level control
/// against a field-level attack is not an opt-in.
fn default_dedup_clones_for_measured_sr_std() -> bool {
    true
}

/// Do not let the submitted field reduce the precommitted deflation prior by
/// default. See [`ScoreConfig::min_measured_trials_sr_std`].
fn default_min_measured_trials_sr_std() -> f64 {
    0.5
}

fn default_execution_seeds_per_window() -> usize {
    1
}

/// Default periods per year: daily equity bars, the benchmark's historical
/// assumption. Configs serialized before the field existed deserialize to this,
/// so their meaning is unchanged.
fn default_periods_per_year() -> f64 {
    252.0
}

/// Default benchmark agent for the relative verdict: the buy-and-hold reference
/// agent, under the id the harness and the CLI give it.
fn default_benchmark_agent_id() -> String {
    "buy-and-hold".to_string()
}

/// The per-run pass vector pass^k aggregates: one bool per run, in submission
/// order. This is the kernel's own test, exposed so a report can say *which*
/// runs passed rather than only whether all did.
///
/// Under [`PassMode::All`], [`PassMode::Any`] and [`PassMode::AtLeast`] run `i`
/// passes iff `PSR(returns_i, per_run_psr_benchmark(cfg)) >= cfg.per_run_psr_bar`;
/// `benchmark` is ignored.
///
/// Under [`PassMode::RelativeToBenchmark`] run `i` passes iff all of:
/// 1. `benchmark` is present and has a run at position `i` of the same length
///    (the same (window, seed) cell; a missing or misaligned cell is a failure,
///    never a silent fallback to the absolute test);
/// 2. the excess series `e_t = returns_i[t] - benchmark_i[t]` has strictly
///    positive standard deviation;
/// 3. `PSR(e, per_run_psr_benchmark(cfg)) >= cfg.per_run_psr_bar`.
///
/// In every mode the PSR is the checked one
/// ([`crate::deflated_sharpe::checked_probabilistic_sharpe_ratio`]), and a run
/// whose PSR is refused fails. A constant run is refused: it has no Sharpe
/// ratio. The unchecked PSR scored an all-zero run just above 0.5, a pass at a
/// bar of one half and at higher bars against a negative per-run benchmark, and
/// a constant positive run whose rounded mean left a residual variance 1.0, a
/// pass at every bar.
///
/// Rule 2 is what stops the benchmark from certifying itself. Its own excess
/// series is identically zero, and a zero-dispersion series carries no evidence
/// of outperformance at all: `sharpe_ratio` defines it as 0 and the unchecked PSR
/// returns `norm_cdf(0) = 0.5`, so it already fails any bar above one half, but an
/// operator who lowered `per_run_psr_bar` to 0.5 would admit it. The rule makes
/// the refusal unconditional: a run indistinguishable from the benchmark is a
/// run with no excess edge, and the relative verdict is a claim about excess
/// edge in every window. It also refuses a clone of the benchmark under another
/// id, for the same reason.
pub fn per_run_passes(
    sub: &AgentSubmission,
    benchmark: Option<&AgentSubmission>,
    cfg: &ScoreConfig,
) -> Vec<bool> {
    let bar = per_run_psr_benchmark(cfg);
    match cfg.pass_mode {
        PassMode::All | PassMode::Any | PassMode::AtLeast(_) => sub
            .runs
            .iter()
            .map(|r| {
                checked_probabilistic_sharpe_ratio(&r.returns, bar)
                    .is_ok_and(|psr| psr >= cfg.per_run_psr_bar)
            })
            .collect(),
        PassMode::RelativeToBenchmark => sub
            .runs
            .iter()
            .enumerate()
            .map(|(i, r)| {
                benchmark
                    .and_then(|b| b.runs.get(i))
                    .and_then(|b| excess_returns(&r.returns, &b.returns))
                    .is_some_and(|e| {
                        std_dev(&e) > 0.0
                            && checked_probabilistic_sharpe_ratio(&e, bar)
                                .is_ok_and(|psr| psr >= cfg.per_run_psr_bar)
                    })
            })
            .collect(),
    }
}

/// Period-by-period excess of `returns` over `benchmark`, or `None` when the two
/// series are not the same length (not the same cell).
fn excess_returns(returns: &[f64], benchmark: &[f64]) -> Option<Vec<f64>> {
    (returns.len() == benchmark.len())
        .then(|| returns.iter().zip(benchmark).map(|(a, b)| a - b).collect())
}

/// The per-period cross-trial Sharpe dispersion the kernel deflates with on the
/// configured path: `cfg.trials_sr_std / sqrt(cfg.periods_per_year)`.
///
/// For serially independent returns a Sharpe ratio scales with the square root
/// of the number of periods, so a dispersion of Sharpes does too; dividing by
/// `sqrt(periods_per_year)` takes the annualized prior to the frequency the
/// statistic is computed at. Under autocorrelation the scaling factor differs
/// (Lo 2002), so the converted prior is an approximation. This is the only
/// place the kernel converts it, through
/// [`sharpebench_stats::per_period_from_annualized`], the formula the
/// `sharpebench-edge` honesty verdict also uses. Every deflation call site in this
/// module reads it from here so the prior can neither be converted twice nor
/// reach a per-period statistic unconverted. The *measured* path in [`rank`]
/// never calls it: the dispersion it measures across the field is already a
/// dispersion of per-period Sharpes.
///
/// It does not validate `periods_per_year`. [`score_agent`] and [`rank`] refuse
/// a non-finite or non-positive frequency before they deflate with the result;
/// a caller using this value directly checks the frequency itself.
pub fn per_period_sr_std(cfg: &ScoreConfig) -> f64 {
    per_period_from_annualized(cfg.trials_sr_std, cfg.periods_per_year)
}

/// Refuse a `cfg.periods_per_year` that is not a frequency: finite and positive.
///
/// `+inf` divides the annualized prior down to a zero dispersion, the most
/// favorable deflation bar there is and one no later check can tell apart from a
/// single trial. Zero turns the prior infinite and a negative or NaN frequency
/// turns it NaN, which `expected_max_sharpe` would refuse under the name of
/// `trials_sr_std`. Every one is refused here, under its own name, on the
/// deflation boundary that already refuses a malformed `trials_sr_std`.
fn checked_periods_per_year(cfg: &ScoreConfig) -> Result<(), StatisticalError> {
    if !cfg.periods_per_year.is_finite() || cfg.periods_per_year <= 0.0 {
        return Err(StatisticalError::InvalidParameter {
            name: "periods_per_year",
            requirement: "must be finite and positive",
        });
    }
    Ok(())
}

/// The per-period Sharpe benchmark each run's PSR is tested against for
/// pass^k: `cfg.per_run_min_annual_sharpe / sqrt(cfg.periods_per_year)`. The
/// default 0.0 converts to 0.0 on every timeframe, so the default per-run test
/// is the plain `PSR(returns, 0) >= per_run_psr_bar`.
pub fn per_run_psr_benchmark(cfg: &ScoreConfig) -> f64 {
    per_period_from_annualized(cfg.per_run_min_annual_sharpe, cfg.periods_per_year)
}

/// Where the `trials_sr_std` that deflated a score came from.
#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum TrialsSrStdSource {
    /// `ScoreConfig::trials_sr_std` — a configured prior (the default 0.5 is a
    /// modelling assumption, not a measurement).
    #[default]
    Configured,
    /// The sample standard deviation of pooled per-period Sharpe ratios across the
    /// ranked field — what the deflation formula actually asks for.
    Measured,
    /// The field was measured, but its value was below the operator's
    /// precommitted floor and the floor was applied instead.
    MeasuredFloored,
}

/// The vote with the largest single-vote leverage over a field's measured
/// deflation dispersion, reported on every row of a measured board.
///
/// The measured dispersion is the sample standard deviation of one per-period
/// Sharpe per vote, a vote being an agent or a collapsed cluster of near-clones.
/// A vote's leverage is that standard deviation with the vote over the same
/// standard deviation without it. The vote named is the one whose presence
/// raises the dispersion most; some vote always has a leverage of at least
/// 1.0, and a vote near the middle, whose removal would raise the dispersion,
/// is never the one named. A leverage of 1.0 means the vote changes nothing;
/// 4.89, measured on the hourly crypto panel where buy-and-hold sits far from a
/// tight luck-floor cluster, means the measured dispersion is almost five times
/// what it would be without that one row.
///
/// The leverage describes the dispersion before the floor. When
/// `trials_sr_std_source` is `MeasuredFloored` the bar is the floor, and
/// removing this vote would not lower it. When the source is `Measured`, the
/// bar without the vote would be the larger of `measured_dispersion_without_it`
/// and the floor.
///
/// It is a leave-one-out figure, so it sees one vote at a time. Two votes that
/// sit together far from the rest carry the dispersion jointly, and each one's
/// removal leaves the other in place: a pair of equal outliers beside a tight
/// cluster shows a largest single-vote leverage of about 1.2 however far out
/// the pair sits.
///
/// No bound is applied to it. A cap on the vote was measured and rejected: on
/// the paper's own measured panels one honest reference agent routinely carries
/// the dispersion, and a cap strict enough to contain one hostile entrant would
/// have lowered those panels' bars by up to 74.5%. The row is disclosed instead,
/// so a reader can see when one vote sets the bar.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DispersionLeverage {
    /// The agent whose vote it is: for a collapsed cluster, the member whose
    /// Sharpe is the cluster's vote (the lower middle, ties broken by id).
    pub agent_id: String,
    /// Submissions collapsed into this one vote; 1 for an agent that is
    /// nobody's near-clone.
    pub agents_in_vote: usize,
    /// The vote itself, a per-period Sharpe ratio.
    pub vote_sharpe: f64,
    /// Votes in the dispersion sample.
    pub votes: usize,
    /// The measured dispersion without this vote, per period, before any floor.
    pub measured_dispersion_without_it: f64,
    /// Measured dispersion with the vote over the same without it. Absent when
    /// the other votes are all equal, where the ratio has no finite value.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub leverage: Option<f64>,
}

impl Default for ScoreConfig {
    fn default() -> Self {
        Self {
            n_trials: 50,
            trials_sr_std: 0.5,
            deflation_null_mean_per_period: 0.0,
            dsr_bar: 0.95,
            per_run_psr_bar: 0.90,
            per_run_min_annual_sharpe: 0.0,
            pass_mode: PassMode::default(),
            benchmark_agent_id: default_benchmark_agent_id(),
            periods_per_year: default_periods_per_year(),
            alpha: 0.05,
            bootstrap_seed: 0x5BA7_2026,
            n_boot: 2000,
            block_prob: 0.1,
            mandate: Mandate::default(),
            rank_key: RankKey::default(),
            reference_dsr_population: Vec::new(),
            rolling_window: default_rolling_window(),
            dsr_ci_level: default_dsr_ci_level(),
            shared_run_set: default_shared_run_set(),
            min_field_for_measured_sr_std: default_min_field_for_measured_sr_std(),
            dedup_clones_for_measured_sr_std: default_dedup_clones_for_measured_sr_std(),
            min_measured_trials_sr_std: default_min_measured_trials_sr_std(),
            execution_seeds_per_window: default_execution_seeds_per_window(),
        }
    }
}

impl ScoreConfig {
    /// The default configuration for a dataset with `periods_per_year` bars per
    /// year. Prefer this to `Default::default()` whenever the data is not daily
    /// equities: it is the one field that has to match the dataset, and naming it
    /// at construction is harder to forget than patching it afterwards.
    pub fn for_periods_per_year(periods_per_year: f64) -> Self {
        Self {
            periods_per_year,
            ..Self::default()
        }
    }

    /// The "never catastrophic in any regime" reliability verdict, as one named
    /// preset so an ablation against the default is a one-line change of config
    /// rather than a patched binary.
    ///
    /// The default config certifies *profitable in every regime with 90%
    /// confidence*: pass^k in [`PassMode::All`] requires every window and every
    /// seed to clear the per-run PSR bar. This preset certifies something
    /// different: *never draws down more than `max_run_dd` in any regime, with the
    /// edge tested on the pooled track*. It sets `pass_mode` to [`PassMode::Any`]
    /// (one run clearing the per-run bar is enough) and
    /// `mandate.max_run_drawdown` to `max_run_dd`, and leaves every other gate
    /// where the default has it: the pooled Deflated Sharpe must still clear
    /// `dsr_bar`, the bootstrap edge test must still reject noise, the process
    /// must still be clean, and the pooled drawdown mandate still applies. The
    /// edge is therefore tested once, on the whole track, and reliability is
    /// asked of the loss side only.
    ///
    /// This is a **weaker safety claim** than the default. It admits a
    /// regime-dependent edge such as equity beta, which the default correctly
    /// refuses because owning the index is not safe in a bear market. It also
    /// admits an agent whose edge lives in one run, provided that run is large
    /// enough for the pooled track to survive deflation and the bootstrap; the
    /// default refuses that agent through pass^k, and this preset has given that
    /// refusal up. That is the point of running both: which agents clear which
    /// gate, on which asset class and timeframe, is the table the paper is for.
    /// It is suitable for an ablation, not as the default for a money agent, and
    /// nothing here changes the default.
    pub fn reliability_never_catastrophic(max_run_dd: f64) -> Self {
        Self {
            pass_mode: PassMode::Any,
            mandate: Mandate {
                max_run_drawdown: max_run_dd,
                ..Mandate::default()
            },
            ..Self::default()
        }
    }

    /// The mandate-relative reliability verdict, as one named preset.
    ///
    /// The default certifies *profitable in every regime*: an all-weather
    /// absolute-return mandate, which is why the index itself cannot pass on any
    /// range containing a bear window. This preset certifies *beats owning the
    /// universe in every regime*: it sets `pass_mode` to
    /// [`PassMode::RelativeToBenchmark`] and names `benchmark_agent_id`, so each
    /// run's PSR is tested on its excess return over the benchmark's run in the
    /// same (window, seed) cell (see [`per_run_passes`] for the exact rule and
    /// for why the benchmark itself, whose excess is identically zero, fails).
    /// Every other gate is the default's: the pooled Deflated Sharpe, the
    /// bootstrap, the process audit and the drawdown mandate are all still
    /// computed on the agent's own raw returns, so this is a different
    /// reliability question, not a weaker set of gates. It is opt-in and changes
    /// nothing about the default.
    pub fn relative_to_benchmark(benchmark_agent_id: &str) -> Self {
        Self {
            pass_mode: PassMode::RelativeToBenchmark,
            benchmark_agent_id: benchmark_agent_id.to_string(),
            ..Self::default()
        }
    }
}

/// The scored result for one agent.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CompositeScore {
    pub agent_id: String,
    pub deflated_sharpe: f64,
    /// PSR of the pooled track against a zero Sharpe. Reported, never a gate.
    /// 0.0, the no-skill floor rather than an estimate, when the pooled track
    /// has no PSR (a constant track has no Sharpe ratio); the deflated Sharpe is
    /// refused on the same track, so `deflation_error` is then present.
    pub psr: f64,
    pub passed_k: bool,
    pub process_ok: bool,
    /// Conservative 1.0 sentinel when `bootstrap_error` is present; in that case
    /// this is not an estimated p-value and eligibility is always false.
    pub bootstrap_p: f64,
    /// Why the single-series bootstrap was unavailable. Omitted for valid inputs.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub bootstrap_error: Option<String>,
    /// Why the deflation family (the Deflated Sharpe, its bar and its bootstrap
    /// interval) was unavailable. Omitted for valid inputs. When present,
    /// `deflated_sharpe` and `deflation_bar_per_period` are the no-skill floor
    /// rather than estimates, `dsr_ci_low`, `dsr_ci_high` and `dsr_se` are
    /// absent rather than numeric, `composite` is 0.0 and `rank_eligible` is
    /// always false.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub deflation_error: Option<String>,
    /// Why the selection-robustness diagnostic was unavailable. Omitted for
    /// valid inputs and for a submission that declared no candidates; when
    /// present, `selection_median_dsr` and `selection_gap` are both `None`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub selection_error: Option<String>,
    pub raw_mean_return: f64,
    pub rank_eligible: bool,
    /// The ranking key: the deflated Sharpe when eligible, else 0.0.
    pub composite: f64,
    /// Field-relative attribution, filled by [`rank`]: the skill (alpha) and
    /// market-beta components of the agent's return. Zero from `score_agent` alone.
    pub alpha: f64,
    pub beta: f64,
    /// Calibration of stated confidence (Brier score; lower = better). `None` if
    /// no run carries a stated confidence with its outcome.
    pub calibration_brier: Option<f64>,
    /// Decision-level confidence/outcome pairs behind `calibration_brier`: only
    /// confidences the agent stated, never a filled-in value.
    /// Pairing is performed inside each run, never across a run boundary.
    #[serde(default)]
    pub calibration_observations: usize,
    /// Edge durability: half-life, **in market windows**, of the magnitude of
    /// the realized mean return, with execution-seed replicates averaged into
    /// their window first (see [`crate::decay::return_drift_half_life`]). `None`
    /// if there are too few windows or the series isn't decaying.
    ///
    /// This measures *return drift*, not information-coefficient decay: mean
    /// return also moves with sizing, cost and regime, and can decay while the
    /// signal is intact. The serialized name is historical and unchanged; read
    /// it as return drift.
    pub edge_half_life: Option<f64>,
    /// Field-wide data-snooping p-value (White's Reality Check), filled by [`rank`]:
    /// under the null that no agent beats the benchmark, the probability that the
    /// *leader* would look at least this good given how many agents were tried. It
    /// is not the probability that the leader's edge is luck: that is a posterior
    /// and needs a prior this test does not have.
    /// Same value across the field. 1.0 from `score_agent` alone.
    pub field_reality_check_p: f64,
    /// Maximum drawdown over the pooled track, in [0, 1].
    pub max_drawdown: f64,
    /// Whether the agent respected its mandate: both the pooled drawdown cap and
    /// the per-run cap.
    pub mandate_ok: bool,
    /// The largest maximum drawdown of any single run, in [0, 1], each run
    /// measured from its own starting equity: the number the per-run mandate
    /// bound is checked against. Not bounded by `max_drawdown`: the pooled
    /// figure counts losing streaks that span runs, but it is also formed by
    /// averaging execution seeds within a window, which can cancel a within-run
    /// trough and leave this value above the pooled one. 0.0 with no runs.
    #[serde(default)]
    pub worst_run_drawdown: f64,
    /// Turnover proxy: average orders placed per run (trading frequency / capacity).
    pub turnover: f64,
    /// Whether the agent is on the Pareto front over (return↑, drawdown↓,
    /// turnover↓). Always `false` for a track the kernel refuses as having no
    /// Sharpe ratio (fewer than two observations, constant, or a Sharpe that is
    /// not finite). Such a track still dominates when it has an observation,
    /// so an agent it beats on all three is not on the front; an empty track
    /// dominates nobody. Reported only: no gate, eligibility rule or rank reads
    /// it. Filled by [`rank`].
    pub pareto_optimal: bool,
    /// Whether the agent's outperformance survives Romano–Wolf step-down multiple
    /// testing across the field. Filled by [`rank`].
    pub step_down_significant: bool,
    /// Conviction-weighted return: each run's mean return weighted by the mean
    /// of the run's stated `confidences`, each read as the probability it is
    /// and clamped to `[0, 1]`. Rewards staking conviction on the runs that
    /// paid off.
    ///
    /// The outcome it weighs against is the run's own realized return, not the
    /// `outcomes` a decision is scored against: that pairing is
    /// `calibration_brier`'s, and a run may state confidences without it. A run
    /// with no stated confidence weighs the mean of the other runs' weights, so
    /// a failing run that states nothing stays in. When no run states one,
    /// every run weighs the same (the mean of the per-run mean returns).
    pub confidence_weighted_return: f64,
    /// Total compute/token cost across all runs (0.0 if unreported).
    pub cost: f64,
    /// Raw mean return per unit cost — skill-per-dollar. `None` when cost is unreported.
    pub return_per_cost: Option<f64>,
    /// Hansen's studentized SPA p-value for the field leader (a more robust
    /// sibling of `field_reality_check_p`). Same value across the field; filled by
    /// [`rank`]. 1.0 from `score_agent` alone.
    pub field_spa_p: f64,
    /// Hansen's *consistent* SPA p-value — the most powerful of the field-wide
    /// data-snooping tests (drops clearly-bad models from the null). Same value
    /// across the field; filled by [`rank`]. 1.0 from `score_agent` alone.
    pub field_spa_consistent_p: f64,
    /// Fixed benchmark used by the field-wide White/SPA tests. This is distinct
    /// from the equal-weight field proxy used only for alpha/beta attribution.
    /// When the named benchmark is absent, the tests use the explicit zero
    /// return (cash) benchmark and stamp `"zero-return-cash"` here.
    #[serde(default)]
    pub field_significance_benchmark: String,
    /// Crowdedness: the agent's mean Pearson correlation with the rest of the
    /// field's return streams, in [-1, 1]. High = riding the same factor as
    /// everyone else (a common beta that decays for the whole board at once);
    /// low/negative = diversifying. Reported, not gating; filled by [`rank`].
    /// `None` from `score_agent` alone (no field context) or with < 2 agents.
    pub field_crowdedness: Option<f64>,
    /// Peers with a defined correlation behind `field_crowdedness`.
    #[serde(default)]
    pub field_crowdedness_peers: usize,
    /// In-sample search budget the agent declared (configs tried before submission).
    pub in_sample_trials: u32,
    /// Effective deflation trial footprint = `cfg.n_trials + in_sample_trials`; the
    /// Deflated Sharpe is computed against this, so over-searching raises the bar.
    pub effective_n_trials: u32,
    /// Percentile (0..=100) of the Deflated Sharpe within the frozen reference
    /// population. `None` when no reference population is configured, and when
    /// the pooled track has no Sharpe ratio (it is constant, or its Sharpe is
    /// not finite), whose deflated Sharpe is the refused floor, not an estimate.
    pub dsr_percentile: Option<f64>,
    /// Deflated Sharpe of the median submitted candidate. `None` if none reported.
    pub selection_median_dsr: Option<f64>,
    /// Best-minus-median candidate Deflated Sharpe — the selection-luck gap.
    /// `None` if no candidates were reported.
    pub selection_gap: Option<f64>,
    /// 1-based ordinal position among rank-eligible agents (scale-invariant rank
    /// mode). 0 = ineligible or scored outside a field. Filled by [`rank`].
    pub rank_ordinal: usize,
    /// Worst (minimum) per-window Sharpe over the pooled track (non-annualized),
    /// using `cfg.rolling_window`. Low/negative = the edge collapses in some
    /// stretch. `None` when the pooled track is shorter than one window, and
    /// when it has no Sharpe ratio (it is constant, or its Sharpe is not
    /// finite): the window Sharpes of such a track are the zero-variance
    /// sentinel, not estimates.
    pub rolling_min_sharpe: Option<f64>,
    /// Fraction of rolling windows whose Sharpe is positive, in [0, 1]. Near 1 =
    /// the edge is everywhere; low = the deflated edge lives in a few lucky
    /// windows. `None` when the track is too short or has no Sharpe ratio.
    pub rolling_frac_positive: Option<f64>,
    /// Overlapping windows behind the rolling fraction and minimum Sharpe: the
    /// windows the pooled track spans, still counted when those two are `None`
    /// because the track has no Sharpe ratio.
    #[serde(default)]
    pub rolling_windows: usize,
    /// Sortino ratio over the pooled track (excess mean return per unit of
    /// *downside* deviation, MAR = 0): rewards an edge that doesn't arrive with
    /// downside churn. Reported, never the rank key. `None` with no downside.
    pub sortino: Option<f64>,
    /// Downside deviation (RMS of below-target returns) — the denominator of
    /// `sortino`, reported so the figure is legible.
    pub downside_deviation: f64,
    /// Budget-normalized Deflated Sharpe: `deflated_sharpe / cost` — luck-robust
    /// skill per unit of compute/token spend. `None` when cost is unreported, and
    /// when the pooled track has no Sharpe ratio, whose deflated Sharpe is the
    /// refused floor.
    pub dsr_per_cost: Option<f64>,
    /// Whether the realized return was floored to a no-skill baseline because the
    /// agent has a block-severity process violation (cheating shouldn't pay).
    pub process_floored: bool,
    /// The agent's realized return after the process floor: its raw mean when the
    /// process is clean, else the no-skill baseline (0.0). Always reported
    /// alongside `raw_mean_return`, which keeps the un-floored value.
    pub realized_floored_return: f64,
    /// Lower bound of the bootstrapped Deflated-Sharpe confidence interval (at
    /// `cfg.dsr_ci_level`). The DSR point estimate is `deflated_sharpe`; this is
    /// how far it might sink under resampling noise. Absent, with the other two
    /// interval fields, when `deflation_error` says the interval could not be
    /// estimated: an interval nothing was resampled for is unavailable, and a
    /// number in its place reads as a precision the estimator never had.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub dsr_ci_low: Option<f64>,
    /// Upper bound of the bootstrapped Deflated-Sharpe confidence interval.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub dsr_ci_high: Option<f64>,
    /// Bootstrap standard error of the Deflated Sharpe (the CI's scale).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub dsr_se: Option<f64>,
    /// 1-based tie-band index among rank-eligible agents: entries whose DSR
    /// confidence intervals overlap share a band and are statistically
    /// indistinguishable, so they are not hard-ranked against each other. 0 for
    /// ineligible agents or an agent scored outside a field. Filled by [`rank`].
    pub tie_group: usize,
    /// Whether this entry shares its DSR tie band with at least one other eligible
    /// agent (i.e. its rank is not statistically separable from a neighbor).
    /// Filled by [`rank`].
    pub dsr_tied: bool,
    /// The **per-period** cross-trial Sharpe dispersion this score was actually
    /// deflated with: the value handed to the expected-maximum-Sharpe formula.
    /// On the configured path it is `ScoreConfig::trials_sr_std` divided by
    /// `sqrt(periods_per_year)`; on the measured path it is the field's measured
    /// dispersion, unconverted.
    #[serde(default)]
    pub trials_sr_std: f64,
    /// The annualized prior `trials_sr_std` was converted from: `Some` of
    /// `ScoreConfig::trials_sr_std` on the configured path, `None` on the measured
    /// path, where the dispersion was measured per period and no annualized prior
    /// exists. Reported so a score is legible in the units operators quote
    /// without any reader having to redo the conversion.
    #[serde(default)]
    pub trials_sr_std_annualized: Option<f64>,
    /// Annualized equivalent of the exact per-period dispersion that deflated
    /// this score. Unlike `trials_sr_std_annualized`, this is present for both
    /// configured and measured paths, making a field measurement's units
    /// explicit without ever feeding an annualized value back into DSR.
    #[serde(default)]
    pub trials_sr_std_annualized_equivalent: f64,
    /// Expected maximum per-period Sharpe under the effective trial footprint
    /// and the exact dispersion used by DSR: the deflation bar, in the same
    /// units as the pooled per-period Sharpe.
    #[serde(default)]
    pub deflation_bar_per_period: f64,
    /// `deflation_bar_per_period * sqrt(periods_per_year)`, reported solely for
    /// legibility across dataset frequencies.
    #[serde(default)]
    pub deflation_bar_annualized_equivalent: f64,
    /// The fixed null-population mean included in the deflation bar, per period.
    #[serde(default)]
    pub deflation_null_mean_per_period: f64,
    /// Number of temporally distinct pooled observations used by PSR, DSR,
    /// bootstrap and pooled diagnostics. With execution replicates this is not
    /// multiplied by the replicate count.
    #[serde(default)]
    pub pooled_observations: usize,
    /// Whether `trials_sr_std` was measured from the field or taken from the
    /// configured prior. Always `Configured` from `score_agent` alone.
    #[serde(default)]
    pub trials_sr_std_source: TrialsSrStdSource,
    /// When `trials_sr_std` was measured from the field: the one vote whose
    /// presence raises the measured dispersion most, and by how much. Absent on
    /// the configured path, where no field voted, and on a field whose votes
    /// are all equal, where no vote raises a dispersion of zero.
    ///
    /// A disclosure only. Nothing is clipped, nobody is refused and no bar
    /// moves: it says, on the face of every row, whether one agent's Sharpe is
    /// what set the deflation bar. On small measured fields that is often an
    /// honest reference agent (see [`DispersionLeverage`]).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub trials_sr_std_most_influential_vote: Option<DispersionLeverage>,
    /// Runs the agent submitted, before any shared-cell restriction.
    #[serde(default)]
    pub runs_submitted: usize,
    /// Runs actually scored: the submitted runs on the field's shared cells (see
    /// `ScoreConfig::shared_run_set`). Equals `runs_submitted` from `score_agent`
    /// alone or for a field where every agent completed the same cells.
    #[serde(default)]
    pub runs_scored: usize,
    /// Graded process-discipline scalar over all runs' concatenated traces, in
    /// [0, 1]: any block-severity violation zeroes it; each warn-severity event
    /// costs 0.1 (floored at 0). **Reported, never eligibility**: the only
    /// binary process gate remains `process_ok` (zero block violations). Warn
    /// events additionally order agents within a DSR tie band in [`rank`]:
    /// ordering within statistical ties only, because warn events are real
    /// information but not calibrated enough to gate. Scores archived before
    /// this field existed deserialize to the clean value 1.0; `process_ok`
    /// stays authoritative for them.
    #[serde(default = "default_process_score")]
    pub process_score: f64,
    /// Count of warn-severity process events across all runs (concentration
    /// breaches, hedged tail-selling). Reported, never eligibility.
    #[serde(default)]
    pub process_warnings: usize,
    /// Economic-rationality score of the submission's one recorded choice:
    /// submitting this track out of its declared candidate set, valued by
    /// per-period Sharpe (see [`crate::econrationality`]). 1.0 = the pick
    /// respected first-order dominance, 0.0 = a declared candidate strictly
    /// dominated it. `None` when the submission declared no comparable
    /// candidates, and when the submitted pooled track has no Sharpe ratio (it
    /// is constant, or its Sharpe is not finite) to value the choice by.
    /// Reported, never gating.
    #[serde(default)]
    pub econ_rationality_score: Option<f64>,
    /// Count of first-order-dominance violations in the recorded selection
    /// choice (0 or 1, since one choice is recorded per submission). `None` when
    /// nothing was elicitable. Reported, never gating.
    #[serde(default)]
    pub econ_dominance_violations: Option<usize>,
    /// Behavior-role attribution over the recorded runs (see
    /// [`crate::roles::attribute_behavior_roles`]): the regression loading of
    /// each estimable behavior class (clean-active / idle / warned /
    /// block-violating) on the window-dated team stream, each class estimated on
    /// the windows it occurs in. Empty when not estimable, which includes the
    /// ordinary one-execution-per-window submission: behavior is then confounded
    /// with the window and every loading would be 1.0 by construction. Reported,
    /// never gating.
    #[serde(default)]
    pub role_contributions: Vec<RoleContribution>,
    /// The mandate the submitter declared (see [`DeclaredMandate`]), echoed so
    /// the record says what was asked. `None` = undeclared; the five declared
    /// fields are then absent from the serialized score, so an undeclared
    /// field's bytes are unchanged.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub declared_mandate: Option<DeclaredMandate>,
    /// The verdict the declaration resolved to and was tested under
    /// ([`MandateVerdict::of`]). `None` when undeclared.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub verdict_applied: Option<MandateVerdict>,
    /// pass^k under `verdict_applied`: the declared verdict's own per-run series
    /// and aggregation. `passed_k` stays the host verdict's. `None` when
    /// undeclared.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub declared_passed_k: Option<bool>,
    /// Eligibility under the declared verdict: the host predicate with
    /// `passed_k` replaced by `declared_passed_k` and, for a drawdown-capped
    /// verdict, the declared per-run bound added. Every other gate (deflated
    /// Sharpe, bootstrap, process, the host's drawdown mandate) is the same
    /// test on the same raw returns, so a declaration can only select the
    /// reliability question, never relax a gate. **Reported, never rank**: the
    /// board sorts on `rank_eligible` under the host verdict, this column is
    /// labeled beside it, and `rank_ordinal` counts host-eligible agents only.
    /// `None` when undeclared.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub declared_mandate_eligible: Option<bool>,
    /// 1-based position by deflated Sharpe among the agents that are eligible
    /// under the **same** resolved verdict (the agent's mandate class), filled
    /// by [`rank_declared`]. Agents in different classes are never ordered
    /// against each other on this column, and no class is mixed with the host
    /// board's ordinal. `None` when undeclared or not declared-eligible.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub declared_mandate_ordinal: Option<usize>,
    /// The verdict of an opt-in rank mode (see [`crate::certification`]),
    /// filled by [`crate::certification::rank_certified`] only. **Reported,
    /// never rank**: the host board is unchanged under every mode. `None` under
    /// the legacy protocol, and then absent from the serialized score, so a
    /// board ranked without a mode is byte-identical.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub certification: Option<Certification>,
}

impl CompositeScore {
    /// The board-row wording of eligibility under the declared verdict, e.g.
    /// `eligible under declared verdict (relative to buy-and-hold); host-board
    /// ineligible`. This deliberately does not say that the mandate condition
    /// itself failed: `declared_mandate_eligible` is the full eligibility
    /// conjunction with the declared reliability verdict substituted, so DSR,
    /// bootstrap, process, or the host drawdown gate may be the refusing term.
    /// The second clause is `rank_eligible` under the host verdict. `None` when
    /// undeclared.
    pub fn mandate_verdict_label(&self) -> Option<String> {
        let verdict = self.verdict_applied.as_ref()?;
        let eligibility = if self.declared_mandate_eligible == Some(true) {
            "eligible"
        } else {
            "ineligible"
        };
        let host = if self.rank_eligible {
            "host-board eligible"
        } else {
            "host-board ineligible"
        };
        Some(format!(
            "{eligibility} under declared verdict ({}); {host}",
            verdict.describe()
        ))
    }
}

/// Scores archived before `process_score` existed carry no graded scalar; they
/// deserialize to the clean 1.0 (with `process_warnings` 0), and `process_ok`
/// remains the authoritative record of whether the trace was clean.
fn default_process_score() -> f64 {
    1.0
}

/// Pareto dominance on (return↑, drawdown↓, turnover↓).
fn dominates(a: &CompositeScore, b: &CompositeScore) -> bool {
    a.raw_mean_return >= b.raw_mean_return
        && a.max_drawdown <= b.max_drawdown
        && a.turnover <= b.turnover
        && (a.raw_mean_return > b.raw_mean_return
            || a.max_drawdown < b.max_drawdown
            || a.turnover < b.turnover)
}

/// Whether a track whose windows are `tracks` has no Sharpe ratio, by
/// [`observed_sharpe_ratio_of_windows`], the kernel's single statement of it:
/// fewer than two pooled observations, every pooled observation equal, a Sharpe
/// that does not stay finite, or no window that varies inside itself. Such a
/// track is not a Pareto member. The PSR-based `sharpe_undefined` in
/// `score_agent_with` is narrower for a short track, because the checked PSR
/// keeps a 0.0 convention below two observations; the deflation interval refuses
/// that track, so `deflation_error` still names it.
fn has_no_sharpe_ratio(tracks: &[Vec<f64>]) -> bool {
    observed_sharpe_ratio_of_windows(&window_slices(tracks)).is_err()
}

/// The resolved per-period deflation dispersion a score is computed with, and
/// where it came from. Built exactly once per scoring call so the configured
/// prior is converted in one place ([`per_period_sr_std`]) and the measured
/// dispersion is never converted at all.
#[derive(Clone, Copy)]
struct Deflation {
    /// Per period, as handed to the expected-maximum-Sharpe formula.
    sr_std: f64,
    /// The annualized prior `sr_std` came from; `None` when it was measured.
    annualized: Option<f64>,
    source: TrialsSrStdSource,
    null_mean_per_period: f64,
}

impl Deflation {
    fn configured(cfg: &ScoreConfig) -> Self {
        Self {
            sr_std: per_period_sr_std(cfg),
            annualized: Some(cfg.trials_sr_std),
            source: TrialsSrStdSource::Configured,
            null_mean_per_period: cfg.deflation_null_mean_per_period,
        }
    }

    /// `sr_std` is the field's measured dispersion of per-period Sharpes: already
    /// in the kernel's units, so it must not pass through the conversion.
    fn measured(sr_std: f64, cfg: &ScoreConfig) -> Self {
        let floor =
            per_period_from_annualized(cfg.min_measured_trials_sr_std, cfg.periods_per_year);
        let floored = sr_std < floor;
        Self {
            sr_std: sr_std.max(floor),
            annualized: None,
            source: if floored {
                TrialsSrStdSource::MeasuredFloored
            } else {
                TrialsSrStdSource::Measured
            },
            null_mean_per_period: cfg.deflation_null_mean_per_period,
        }
    }
}

/// The mean of a run's stated confidences, each read as the probability it is,
/// or `None` when the run stated none.
///
/// A confidence is a probability. `brier_score` clamps this same field per
/// entry (`calibration.rs`) and `ForecastRevision::confidence` refuses anything
/// outside `[0, 1]`, so the conviction weight was the one reader that took the
/// number as given: `confidences: vec![1e6]` on the best run drove
/// `confidence_weighted_return` to that run's mean, and nothing validates
/// `Run::confidences`' range on the way in. Both the per-run weight and the
/// fallback for runs that state nothing read it here, so neither can be
/// clamped without the other.
fn stated_confidence(run: &Run) -> Option<f64> {
    if run.confidences.is_empty() {
        return None;
    }
    let total: f64 = run.confidences.iter().map(|c| c.clamp(0.0, 1.0)).sum();
    Some(total / run.confidences.len() as f64)
}

/// Score a single agent submission against `cfg`. With no field to measure the
/// cross-trial dispersion on, the configured annualized prior applies, converted
/// to per period once.
pub fn score_agent(sub: &AgentSubmission, cfg: &ScoreConfig) -> CompositeScore {
    score_agent_with(sub, &sub.runs, cfg, Deflation::configured(cfg), None, None)
}

/// [`score_agent`] with the agent's declared mandate. With no field there is no
/// benchmark, so a declaration that names one ([`DeclaredMandate::RelativeTo`],
/// [`DeclaredMandate::OutperformBuyAndHold`]) is not decidable without its
/// aligned field benchmark. This single-submission API therefore records the
/// declaration and resolved verdict but leaves the declared pass and eligibility
/// fields unavailable (`None`); it never encodes missing field context as a
/// failed mandate. Use [`rank_declared`] to test a relative declaration against
/// its field. `None` scores exactly as [`score_agent`].
pub fn score_agent_declared(
    sub: &AgentSubmission,
    declared: Option<&DeclaredMandate>,
    cfg: &ScoreConfig,
) -> CompositeScore {
    if let Some(mandate) = declared {
        let verdict = MandateVerdict::of(mandate);
        if verdict.benchmark_id().is_some() {
            let mut score = score_agent(sub, cfg);
            score.declared_mandate = Some(mandate.clone());
            score.verdict_applied = Some(verdict);
            return score;
        }
    }
    let resolved = declared.map(|mandate| ResolvedDeclaration {
        mandate,
        benchmark: None,
    });
    score_agent_with(
        sub,
        &sub.runs,
        cfg,
        Deflation::configured(cfg),
        None,
        resolved,
    )
}

fn score_agent_with(
    sub: &AgentSubmission,
    process_runs: &[Run],
    cfg: &ScoreConfig,
    defl: Deflation,
    benchmark: Option<&AgentSubmission>,
    declared: Option<ResolvedDeclaration<'_>>,
) -> CompositeScore {
    let tracks = window_tracks(sub, cfg.execution_seeds_per_window);
    let pooled = tracks.concat();

    // A pooled track with no PSR (a constant one) reports the 0.0 floor; the
    // deflated Sharpe below is refused on the same track and names the cause.
    let pooled_psr = checked_probabilistic_sharpe_ratio(&pooled, 0.0);
    // The refusals that say the pooled track has no Sharpe ratio at all: it is
    // constant, or its Sharpe does not stay finite (a computed standard
    // deviation that underflows to zero). Every reported figure read off that
    // Sharpe (the rolling summary, the revealed-selection valuation) or off the
    // floored deflated Sharpe (per cost, percentile) is then absent, not the
    // number the zero-variance sentinel or the floor would produce. Any other
    // refusal (a non-finite observation, an overflowing moment, an invalid
    // configuration) is outside this rule and leaves those fields as they were.
    let sharpe_undefined = matches!(
        pooled_psr,
        Err(StatisticalError::InvalidParameter {
            name: "returns",
            ..
        } | StatisticalError::NonFiniteComputation {
            quantity: "Sharpe ratio"
        })
    );
    let psr = pooled_psr.unwrap_or(0.0);
    // Fold the agent's declared in-sample search budget into the deflation trial
    // footprint: an agent that tried 5000 configs to find this strategy faces a
    // higher bar than one that tried none (front-end data-snooping control).
    let effective_n_trials = cfg.n_trials.saturating_add(sub.in_sample_trials);
    // The deflation family shares one boundary (the pooled track, the null and
    // the trial dispersion), so it shares one error. On a refusal the agent is
    // scored at the no-skill floor and `deflation_error` says why: substituting
    // a number here is the exact failure R02 closes, since the favorable
    // substitution (a zero deflation bar) is also the flattering one. The
    // frequency that converted the dispersion is part of that boundary.
    // The windowed refusal runs first, so a track whose every window is constant
    // is refused here rather than deflated on the level differences between its
    // windows. It reads the same segments the pooled track is concatenated from.
    let frequency = checked_periods_per_year(cfg);
    let deflation = frequency
        .and_then(|()| observed_sharpe_ratio_of_windows(&window_slices(&tracks)).map(|_| ()))
        .and_then(|()| expected_max_sharpe(defl.sr_std, effective_n_trials))
        .and_then(|bar| {
            let dsr = deflated_sharpe_ratio_against_null(
                &pooled,
                effective_n_trials,
                defl.null_mean_per_period,
                defl.sr_std,
            )?;
            Ok((dsr, defl.null_mean_per_period + bar))
        });
    let deflation_error = deflation.as_ref().err().map(ToString::to_string);
    let (dsr, deflation_bar_per_period) = deflation.unwrap_or((0.0, 0.0));

    // pass^k: each run individually clears the per-run PSR bar against the
    // per-period benchmark the annualized minimum converts to (0 by default), on
    // its raw returns or, under the relative mode, on its excess over the
    // benchmark agent's run in the same cell.
    let per_run = per_run_passes(sub, benchmark, cfg);
    let passed_k = pass_k(&per_run, cfg.pass_mode);

    // Process evidence covers every submitted run, including cells excluded
    // from the common-support comparison. A peer cannot erase a violation by
    // omitting the cell in which it happened.
    // Alongside the binary gate, the graded scalar and the warn count are
    // reported: warn-severity events (concentration breaches, hedged
    // tail-selling) are real information, but not calibrated enough to gate, so
    // they never touch `rank_eligible`; they surface in the score and, in
    // [`rank`], order agents within a DSR tie band only.
    let per_run_process: Vec<ProcessScore> = process_runs
        .iter()
        .map(|r| process_score(&r.trace))
        .collect();
    let process_ok = per_run_process.iter().all(ProcessScore::is_clean);
    let process_warnings: usize = per_run_process.iter().map(|p| p.warn_violations).sum();
    // The graded score of the concatenated trace: any block zeroes it, each
    // warn costs 0.1 (floored at 0), the same schedule as the per-trace scorer.
    let graded_process_score = if process_ok {
        (1.0 - process_warnings as f64 * 0.1).max(0.0)
    } else {
        0.0
    };

    let bootstrap = bootstrap_pvalue(&pooled, cfg.bootstrap_seed, cfg.n_boot, cfg.block_prob);
    let bootstrap_error = bootstrap.as_ref().err().map(ToString::to_string);
    let bootstrap_p = bootstrap.unwrap_or(1.0);
    let raw_mean_return = mean(&pooled);

    // Calibration: does stated conviction predict outcomes? (None if not reported.)
    let calibration_pairs: Vec<(f64, bool)> = sub
        .runs
        .iter()
        .flat_map(|run| {
            run.confidences
                .iter()
                .copied()
                .zip(run.outcomes.iter().copied())
        })
        .collect();
    let calibration_observations = calibration_pairs.len();
    let (conf, outc): (Vec<f64>, Vec<bool>) = calibration_pairs.into_iter().unzip();
    let calibration_brier = if calibration_observations > 0 {
        Some(brier_score(&conf, &outc))
    } else {
        None
    };

    // Edge durability: how fast the magnitude of the realized mean return drifts
    // across successive market windows. Dated by window, on the same window axis
    // as `pooled`: execution-seed replicates are repeated draws of one window's
    // dates, so they are averaged into their window before the regression sees
    // them. Feeding them in as separate observations would let a permutation of
    // the seed order change the reported durability without changing any
    // economic history. This is return drift, not IC decay; see
    // [`crate::decay::return_drift_half_life`].
    let seeds_per_window = cfg.execution_seeds_per_window.max(1);
    let per_window_edge: Vec<f64> = sub
        .runs
        .chunks(seeds_per_window)
        .map(|window| window.iter().map(|r| mean(&r.returns)).sum::<f64>() / window.len() as f64)
        .collect();
    let edge_half_life_periods = return_drift_half_life(&per_window_edge);

    // Mandate adherence: the pooled track must respect the whole-track cap and
    // every run must respect the per-run cap. Both default to 1.0, under which
    // the check is the pooled one the benchmark always ran.
    let mdd = max_drawdown(&pooled);
    let worst_run_drawdown = sub
        .runs
        .iter()
        .map(|r| max_drawdown(&r.returns))
        .fold(0.0, f64::max);
    let mandate_ok =
        mdd <= cfg.mandate.max_drawdown && worst_run_drawdown <= cfg.mandate.max_run_drawdown;

    // Turnover proxy: average number of orders placed per run.
    let total_orders: usize = sub
        .runs
        .iter()
        .map(|r| {
            r.trace
                .events
                .iter()
                .filter(|e| matches!(e, ProcessEvent::OrderPlaced { .. }))
                .count()
        })
        .sum();
    let turnover = total_orders as f64 / sub.runs.len().max(1) as f64;

    // Confidence-weighted return: weight each run's return by the conviction
    // staked on it, so sizing-with-conviction beats flat-confidence trading.
    // A run with no stated confidence (a run of holds, or a failing sentinel)
    // takes the submission's mean stated weight, the mean over stating runs of
    // each run's mean confidence. It stays in the mean, and stating a
    // confidence in some runs only cannot replace the equal-weight mean. With
    // no stated confidence anywhere every run weighs 1.0.
    let stated_weights: Vec<f64> = sub.runs.iter().filter_map(stated_confidence).collect();
    let unstated_weight = if stated_weights.is_empty() {
        1.0
    } else {
        mean(&stated_weights)
    };
    let mut cw_num = 0.0;
    let mut cw_den = 0.0;
    for r in &sub.runs {
        let w = stated_confidence(r).unwrap_or(unstated_weight);
        cw_num += w * mean(&r.returns);
        cw_den += w;
    }
    let confidence_weighted_return = if cw_den > 0.0 {
        cw_num / cw_den
    } else {
        raw_mean_return
    };

    // Cost-efficiency: skill per unit of compute/token spend.
    let cost: f64 = sub.runs.iter().map(|r| r.cost).sum();
    let return_per_cost = if cost > 0.0 {
        Some(raw_mean_return / cost)
    } else {
        None
    };

    // Legibility: percentile of the Deflated Sharpe within the frozen reference
    // population (e.g. real fund track records). None when unconfigured, and
    // when the pooled track has no Sharpe ratio to deflate.
    let dsr_percentile = if cfg.reference_dsr_population.is_empty() || sharpe_undefined {
        None
    } else {
        Some(percentile_of(dsr, &cfg.reference_dsr_population))
    };

    // Selection-axis luck: best vs median Deflated Sharpe of the agent's candidate
    // strategies, deflated against the same effective trial footprint. A large gap
    // means the headline result is a lucky pick, not a robust family of edges.
    // A candidate set that cannot be deflated reports no selection diagnostic at
    // all. Both fields are already optional, so the honest answer is `None` with
    // `selection_error` naming the cause, not a summary of ratios that were
    // never computed.
    let selection =
        if sub.candidates.is_empty() {
            None
        } else {
            Some(frequency.and_then(|()| {
                selection_robustness(&sub.candidates, effective_n_trials, defl.sr_std)
            }))
        };
    let selection_error = selection
        .as_ref()
        .and_then(|s: &Result<SelectionRobustness, _>| s.as_ref().err())
        .map(ToString::to_string);
    let (selection_median_dsr, selection_gap) = match selection.and_then(Result::ok) {
        Some(sr) => (Some(sr.median_dsr), Some(sr.selection_gap)),
        None => (None, None),
    };

    // Rolling-Sharpe stability over the pooled track: is the deflated edge one
    // lucky window, or present across the whole track? On a track with no
    // Sharpe ratio the summary is absent, like the Sharpe it summarizes, while
    // the window count still says how many windows the track spans.
    let rolling = rolling_sharpe(&pooled, cfg.rolling_window);
    let rolling_summary = rolling.filter(|_| !sharpe_undefined);
    let rolling_min_sharpe = rolling_summary.map(|r| r.min_sharpe);
    let rolling_frac_positive = rolling_summary.map(|r| r.frac_positive);
    let rolling_windows = rolling.map_or(0, |r| r.n_windows);

    // Downside-risk view: the Sortino rewards an edge that doesn't arrive with
    // downside volatility (reported alongside the Sharpe family, never a gate).
    let sortino = crate::stats::sortino_ratio(&pooled, 0.0);
    let downside_deviation = crate::stats::downside_deviation(&pooled, 0.0);

    // Budget-normalized Deflated Sharpe: luck-robust skill per unit of spend.
    let dsr_per_cost = if cost > 0.0 && !sharpe_undefined {
        Some(dsr / cost)
    } else {
        None
    };

    // Process floor: a block-severity violation forfeits any realized return —
    // it is floored to the no-skill baseline (0.0) so cheating never pays, even
    // for the (display-only) realized-return column. Eligibility logic below is
    // unchanged; `process_ok` still independently disqualifies.
    let process_floored = !process_ok;
    let realized_floored_return = if process_floored {
        0.0
    } else {
        raw_mean_return
    };

    // Sampling uncertainty of the DSR point estimate: a bootstrapped CI + SE, so
    // the leaderboard can flag noise-separated entries as tied rather than impose a
    // false hard ordering. Reuses the stationary-bootstrap resampler.
    let dsr_ci = frequency.and_then(|()| {
        crate::significance::bootstrap_dsr_ci_against_null(
            &pooled,
            effective_n_trials,
            defl.null_mean_per_period,
            defl.sr_std,
            cfg.bootstrap_seed,
            cfg.n_boot,
            cfg.block_prob,
            cfg.dsr_ci_level,
        )
    });
    // An interval that could not be estimated is not a tight one. Any number in
    // its place is read as a bound, so the entry is reported without one and
    // with the reason, rather than with a width the estimator never measured.
    let dsr_ci_error = dsr_ci.as_ref().err().map(ToString::to_string);
    let dsr_ci = dsr_ci.ok();
    let deflation_error = deflation_error.or(dsr_ci_error);

    // Economic rationality, elicited from the one choice a frozen submission
    // records: submitting this track out of the declared candidate set (see
    // [`crate::econrationality::elicit_revealed_selection`]). Reported, never
    // gating; `None` when the submission declared nothing comparable, and when
    // the submitted track has no Sharpe ratio to value the choice by.
    let econ_choice = if sharpe_undefined {
        None
    } else {
        elicit_revealed_selection(&sub.candidates, &pooled)
    };
    let (econ_rationality_score, econ_dominance_violations) = match econ_choice {
        Some(choice) => {
            let violations = usize::from(choice.is_dominated());
            (Some(rationality_score(&[choice])), Some(violations))
        }
        None => (None, None),
    };

    // Behavior-role attribution over the recorded runs (see
    // [`crate::roles::attribute_behavior_roles`]): which behavior class
    // (clean-active, idle, warned, block-violating) is load-bearing for the
    // pooled result. Reported, never gating; empty when not estimable.
    let role_contributions = attribute_behavior_roles(&sub.runs, seeds_per_window);

    let rank_eligible = dsr >= cfg.dsr_bar
        && passed_k
        && process_ok
        && bootstrap_error.is_none()
        && deflation_error.is_none()
        && bootstrap_p < cfg.alpha
        && mandate_ok;
    let composite = if rank_eligible { dsr } else { 0.0 };

    // The declared verdict, if any: the same predicate as `rank_eligible` with
    // only the pass^k question exchanged (series and aggregation from the
    // resolved verdict) and, for a drawdown-capped verdict, the declared per-run
    // bound added. `dsr`, `bootstrap_p`, `process_ok` and `mandate_ok` are the
    // values computed above, on raw returns, so a declaration cannot move them.
    let declared = declared.map(|d| {
        let verdict = MandateVerdict::of(d.mandate);
        let verdict_cfg = ScoreConfig {
            pass_mode: verdict.pass_mode(),
            benchmark_agent_id: verdict
                .benchmark_id()
                .map_or_else(|| cfg.benchmark_agent_id.clone(), str::to_string),
            ..cfg.clone()
        };
        let per_run = per_run_passes(sub, d.benchmark, &verdict_cfg);
        let declared_passed_k = pass_k(&per_run, verdict_cfg.pass_mode);
        let eligible = dsr >= cfg.dsr_bar
            && declared_passed_k
            && process_ok
            && bootstrap_error.is_none()
            && deflation_error.is_none()
            && bootstrap_p < cfg.alpha
            && mandate_ok
            && verdict.drawdown_bound_holds(worst_run_drawdown);
        (d.mandate.clone(), verdict, declared_passed_k, eligible)
    });
    let (declared_mandate, verdict_applied, declared_passed_k, declared_mandate_eligible) =
        match declared {
            Some((m, v, p, e)) => (Some(m), Some(v), Some(p), Some(e)),
            None => (None, None, None, None),
        };

    CompositeScore {
        agent_id: sub.agent_id.clone(),
        deflated_sharpe: dsr,
        psr,
        passed_k,
        process_ok,
        bootstrap_p,
        bootstrap_error,
        deflation_error,
        selection_error,
        raw_mean_return,
        rank_eligible,
        composite,
        alpha: 0.0,
        beta: 0.0,
        calibration_brier,
        calibration_observations,
        edge_half_life: edge_half_life_periods,
        field_reality_check_p: 1.0,
        max_drawdown: mdd,
        mandate_ok,
        worst_run_drawdown,
        turnover,
        pareto_optimal: false,
        step_down_significant: false,
        confidence_weighted_return,
        cost,
        return_per_cost,
        field_spa_p: 1.0,
        field_spa_consistent_p: 1.0,
        field_significance_benchmark: "unscored".to_string(),
        field_crowdedness: None,
        field_crowdedness_peers: 0,
        in_sample_trials: sub.in_sample_trials,
        effective_n_trials,
        dsr_percentile,
        selection_median_dsr,
        selection_gap,
        rank_ordinal: 0,
        rolling_min_sharpe,
        rolling_frac_positive,
        rolling_windows,
        sortino,
        downside_deviation,
        dsr_per_cost,
        process_floored,
        realized_floored_return,
        dsr_ci_low: dsr_ci.map(|c| c.lower),
        dsr_ci_high: dsr_ci.map(|c| c.upper),
        dsr_se: dsr_ci.map(|c| c.se),
        tie_group: 0,
        dsr_tied: false,
        trials_sr_std: defl.sr_std,
        trials_sr_std_annualized: defl.annualized,
        trials_sr_std_annualized_equivalent: defl.sr_std * cfg.periods_per_year.sqrt(),
        deflation_bar_per_period,
        deflation_bar_annualized_equivalent: deflation_bar_per_period * cfg.periods_per_year.sqrt(),
        deflation_null_mean_per_period: defl.null_mean_per_period,
        pooled_observations: pooled.len(),
        trials_sr_std_source: defl.source,
        trials_sr_std_most_influential_vote: None,
        runs_submitted: sub.runs.len(),
        runs_scored: sub.runs.len(),
        process_score: graded_process_score,
        process_warnings,
        econ_rationality_score,
        econ_dominance_violations,
        role_contributions,
        declared_mandate,
        verdict_applied,
        declared_passed_k,
        declared_mandate_eligible,
        declared_mandate_ordinal: None,
        certification: None,
    }
}

/// Returns the temporally ordered pooled track used by PSR, DSR, bootstrap and
/// all pooled diagnostics. Runs are window-major. With `seeds_per_window > 1`,
/// aligned seed executions are Monte-Carlo replicates of one window and are
/// averaged per bar before concatenation. Thus eight executions of a 409-bar
/// window contribute 409 market observations, not 3,272 pseudo-independent
/// ones. A malformed final block or unequal return lengths is rejected loudly:
/// silently truncating it would conceal a misaligned market-time axis.
pub fn pooled_returns(sub: &AgentSubmission, seeds_per_window: usize) -> Vec<f64> {
    window_tracks(sub, seeds_per_window).concat()
}

/// The same track as [`pooled_returns`], kept in the window segments it is
/// concatenated from: one entry per window, already averaged over that window's
/// execution replicates.
///
/// `pooled_returns` is defined as the concatenation of this, so the two cannot
/// disagree about where a window ends. That matters because a predicate asked of
/// the concatenation alone cannot see a boundary: a track whose every window is
/// constant at its own level looks like a track that varies. Callers that decide
/// whether a track has a Sharpe ratio ask
/// [`sharpebench_stats::deflated_sharpe::observed_sharpe_ratio_of_windows`] with
/// these segments rather than asking the flat series.
pub fn window_tracks(sub: &AgentSubmission, seeds_per_window: usize) -> Vec<Vec<f64>> {
    let width = seeds_per_window.max(1);
    if width == 1 {
        return sub.runs.iter().map(|r| r.returns.clone()).collect();
    }
    assert!(
        sub.runs.len().is_multiple_of(width),
        "{} runs cannot form complete {}-execution window blocks",
        sub.runs.len(),
        width
    );
    sub.runs
        .chunks_exact(width)
        .map(|replicates| {
            let len = replicates.first().map_or(0, |r| r.returns.len());
            assert!(
                replicates.iter().all(|r| r.returns.len() == len),
                "execution replicates in one window must have equal return lengths"
            );
            (0..len)
                .map(|t| {
                    replicates.iter().map(|r| r.returns[t]).sum::<f64>() / replicates.len() as f64
                })
                .collect()
        })
        .collect()
}

/// Borrowed view of [`window_tracks`], the shape the windowed refusal takes.
fn window_slices(tracks: &[Vec<f64>]) -> Vec<&[f64]> {
    tracks.iter().map(Vec::as_slice).collect()
}

/// Restrict a field to the run positions every non-empty submission completed —
/// the [`crate::comparison_sets`] intersection keyed by window-major position.
/// Output order matches `subs`; empty submissions pass through untouched.
pub(crate) fn restrict_to_shared_positions(subs: &[AgentSubmission]) -> Vec<AgentSubmission> {
    // Zero-padded so the ids sort in position order; `restrict_to_shared` keeps
    // run order anyway, the padding only makes `shared_windows` legible.
    let tag = |i: usize| format!("{i:08}");
    let tagged: Vec<TaggedSubmission> = subs
        .iter()
        .filter(|s| !s.runs.is_empty())
        .map(|s| TaggedSubmission {
            agent_id: s.agent_id.clone(),
            runs: s
                .runs
                .iter()
                .enumerate()
                .map(|(i, run)| TaggedRun {
                    window_id: tag(i),
                    run: run.clone(),
                })
                .collect(),
            in_sample_trials: s.in_sample_trials,
            candidates: s.candidates.clone(),
        })
        .collect();
    let roster: Vec<String> = tagged.iter().map(|s| s.agent_id.clone()).collect();
    let set = comparison_set(&roster, &tagged);
    // `tagged` holds the non-empty submissions in `subs` order, so walking it in
    // lockstep (rather than looking up by id) is exact even if ids repeat.
    let mut tagged_iter = tagged.iter();
    subs.iter()
        .map(|s| {
            if s.runs.is_empty() {
                return s.clone();
            }
            let t = tagged_iter
                .next()
                .expect("one tagged submission per non-empty submission");
            restrict_to_shared(&set, t)
        })
        .collect()
}

/// The field-measured `trials_sr_std`: the sample standard deviation of pooled
/// per-period Sharpe ratios across agents **whose pooled track has a Sharpe
/// ratio**, or `None` when fewer than `min_field` agents qualify. Sharpes are
/// sorted before summing so the submission order of the field cannot move the
/// deflation bar by an ULP.
///
/// Qualification is [`observed_sharpe_ratio_of_windows`], the same predicate the kernel
/// refuses a track's own deflation on, not `sharpe_ratio().is_finite()`. The
/// two differ exactly on the tracks that have no Sharpe: an all-zero track took
/// the zero-variance sentinel and voted 0, and a constant nonzero track voted
/// the ~1e15 its rounded mean produces, which on its own drove a field's
/// measured dispersion to ~6e14 and every other agent's deflated Sharpe to
/// zero. An excluded agent is still scored, still ranked and still refused on
/// its own terms; it just does not vote on anybody else's bar.
///
/// The exclusion runs **before** the clone collapse, so the partition and each
/// cluster's median are taken over the streams that actually vote, and
/// **before** the `min_field` test, so the field size checked against the floor
/// is the size of the dispersion sample the standard error is claimed for. A
/// field that falls below `min_field` only after the exclusion therefore falls
/// back to the configured prior and records `TrialsSrStdSource::Configured`,
/// rather than measuring from the rump.
///
/// With `dedup_clones` the qualifying streams are first partitioned by
/// [`clone_clusters`] at [`CLONE_COLLAPSE_COSINE`], and each cluster votes once
/// with its median Sharpe (the lower middle of the sorted cluster), so a
/// sock-puppet flood of near-duplicate streams counts as the one strategy it
/// is. The partition and the median are functions of the streams alone, so the
/// result is order-independent; a field with no clones is all singletons and
/// measures byte for byte as it would without the collapse.
fn measured_trials_sr_std(
    tracks: &[Vec<Vec<f64>>],
    ids: &[&str],
    min_field: usize,
    dedup_clones: bool,
) -> Option<MeasuredDispersion> {
    let qualifying: Vec<(usize, Vec<f64>, f64)> = tracks
        .iter()
        .enumerate()
        .filter_map(|(index, t)| {
            let sharpe = observed_sharpe_ratio_of_windows(&window_slices(t)).ok()?;
            Some((index, t.concat(), sharpe))
        })
        .collect();
    // (voting agent's field index, submissions in the vote, the vote)
    let mut votes: Vec<(usize, usize, f64)> = if dedup_clones {
        let streams: Vec<Vec<f64>> = qualifying.iter().map(|(_, p, _)| p.clone()).collect();
        clone_clusters(&streams, CLONE_COLLAPSE_COSINE, false)
            .iter()
            .map(|members| {
                let mut cluster: Vec<(usize, f64)> = members
                    .iter()
                    .map(|&i| (qualifying[i].0, qualifying[i].2))
                    .collect();
                // The vote is the value it always was; the id only settles
                // which of several equal Sharpes the disclosure names.
                cluster.sort_by(|a, b| {
                    a.1.partial_cmp(&b.1)
                        .unwrap_or(std::cmp::Ordering::Equal)
                        .then_with(|| ids[a.0].cmp(ids[b.0]))
                });
                let (index, sharpe) = cluster[(cluster.len() - 1) / 2];
                (index, members.len(), sharpe)
            })
            .collect()
    } else {
        qualifying
            .iter()
            .map(|&(index, _, sharpe)| (index, 1, sharpe))
            .collect()
    };
    if votes.len() < min_field.max(2) {
        return None;
    }
    votes.sort_by(|a, b| {
        a.2.partial_cmp(&b.2)
            .unwrap_or(std::cmp::Ordering::Equal)
            .then_with(|| ids[a.0].cmp(ids[b.0]))
    });
    let sharpes: Vec<f64> = votes.iter().map(|v| v.2).collect();
    let sr_std = std_dev(&sharpes);
    Some(MeasuredDispersion {
        sr_std,
        most_influential_vote: most_influential_vote(&votes, &sharpes, sr_std, ids),
    })
}

/// A field-measured dispersion and the disclosure that travels with it.
struct MeasuredDispersion {
    sr_std: f64,
    most_influential_vote: Option<DispersionLeverage>,
}

/// The vote whose presence raises the measured dispersion most. `votes` and
/// `sharpes` are the sorted dispersion sample and `sr_std` its standard
/// deviation, so this reads the dispersion and never recomputes it.
///
/// `None` when every vote is equal: removing any one leaves the rest equal
/// too, and no vote raises anything.
///
/// A vote whose removal leaves the others all equal has no finite leverage and
/// outranks every finite one, because it alone is the dispersion. Equal
/// leverages go to the lower agent id, so the answer does not depend on
/// submission order.
fn most_influential_vote(
    votes: &[(usize, usize, f64)],
    sharpes: &[f64],
    sr_std: f64,
    ids: &[&str],
) -> Option<DispersionLeverage> {
    // Equal votes can still measure a dispersion of a few ulps, from the mean
    // rounding, so equality is read off the votes rather than off `sr_std`.
    let equal = sharpes.first() == sharpes.last();
    if equal || !sr_std.is_finite() || sr_std <= 0.0 {
        return None;
    }
    let without = |skip: usize| -> f64 {
        let rest: Vec<f64> = sharpes
            .iter()
            .enumerate()
            .filter(|&(i, _)| i != skip)
            .map(|(_, &x)| x)
            .collect();
        std_dev(&rest)
    };
    // Higher leverage first, a non-finite one above every finite one, then the
    // lower agent id.
    let outranks = |a: (Option<f64>, &str), b: (Option<f64>, &str)| -> bool {
        match (a.0, b.0) {
            (None, Some(_)) => true,
            (Some(_), None) => false,
            (Some(x), Some(y)) if x != y => x > y,
            _ => a.1 < b.1,
        }
    };
    let mut best: Option<(usize, f64, Option<f64>)> = None;
    for position in 0..votes.len() {
        let rest = without(position);
        let leverage = (rest > 0.0).then(|| sr_std / rest);
        let candidate = (leverage, ids[votes[position].0]);
        let beats = best.is_none_or(|(held, _, held_leverage)| {
            outranks(candidate, (held_leverage, ids[votes[held].0]))
        });
        if beats {
            best = Some((position, rest, leverage));
        }
    }
    let (position, rest, leverage) = best.expect("a measured field has at least two votes");
    let (index, agents_in_vote, vote_sharpe) = votes[position];
    Some(DispersionLeverage {
        agent_id: ids[index].to_string(),
        agents_in_vote,
        vote_sharpe,
        votes: votes.len(),
        measured_dispersion_without_it: rest,
        leverage,
    })
}

/// Score and rank a field of agents. Eligible agents sort first (by composite
/// desc); ineligible agents sort last (by raw return desc, for display only).
///
/// Two field-level controls run before any agent is scored, so neither is left
/// for a caller to remember:
/// - **Shared cells** (`cfg.shared_run_set`, default on): every submission is
///   restricted to the run positions all agents completed, so an agent scored on
///   an easy subset of cells is compared on the same cells as everyone else.
///   Process judgments still include every original submitted trace.
/// - **Measured deflation** (`cfg.min_field_for_measured_sr_std`): with enough
///   agents, `trials_sr_std` is the measured Sharpe dispersion of the field rather
///   than the configured prior. An agent whose pooled track has no Sharpe ratio
///   is not one of those agents: it is scored and ranked on its own terms but
///   does not vote on anybody else's bar. Smaller fields use the configured
///   value, byte for byte as before. Which applied is stamped on every score.
/// - **Clone collapse** (`cfg.dedup_clones_for_measured_sr_std`, default on):
///   near-duplicate streams (`|cosine| >= CLONE_COLLAPSE_COSINE`) vote once
///   on that measurement, so a sock-puppet flood cannot shrink the dispersion and
///   lower the bar. Clones are still scored and still appear on the board.
///
/// ```
/// use sharpebench_core::{rank, AgentSubmission, Run, ScoreConfig, Trace};
///
/// let mk = |id: &str, returns: Vec<f64>, trials: u32| AgentSubmission {
///     agent_id: id.into(),
///     runs: vec![Run {
///         returns,
///         trace: Trace::default(),
///         confidences: vec![],
///         outcomes: vec![],
///         cost: 0.0,
///     }],
///     in_sample_trials: trials,
///     candidates: vec![],
/// };
///
/// // "lucky" posts a bigger raw return but searched 500 strategies to find it.
/// let board = rank(
///     &[
///         mk("skilled", vec![0.012, 0.008, 0.011, 0.009, 0.010], 1),
///         mk("lucky", vec![0.090, -0.02, 0.001, -0.03, 0.05], 500),
///     ],
///     &ScoreConfig::default(),
/// );
///
/// // One CompositeScore per agent; ranked by deflated Sharpe, not raw return.
/// assert_eq!(board.len(), 2);
/// ```
pub fn rank(subs: &[AgentSubmission], cfg: &ScoreConfig) -> Vec<CompositeScore> {
    rank_declared(subs, &MandateDeclarations::new(), cfg)
}

/// [`rank`] with each agent's declared mandate (see [`DeclaredMandate`]).
///
/// The board is the one [`rank`] produces, byte for byte: every agent is scored
/// under the host verdict (`cfg.pass_mode`), `rank_eligible` decides the sort
/// and `rank_ordinal` counts host-eligible agents only. A declaration adds a
/// second, labeled verdict to the agent's row (`verdict_applied`,
/// `declared_passed_k`, `declared_mandate_eligible`) and never touches the
/// first. The rule is:
///
/// > A declaration selects which reliability question pass^k asks of the agent
/// > and, for a drawdown-capped mandate, adds a per-run bound; every other gate
/// > is the same test on the same raw returns. Eligibility is reported per
/// > verdict; the board ranks under the host verdict; declared eligibility is
/// > an additional column, ordered only within the agent's mandate class.
///
/// The mandate class of an agent is its resolved [`MandateVerdict`]
/// (`OutperformBuyAndHold` and `RelativeTo { "buy-and-hold" }` share one). Within a
/// class, declared-eligible agents are ordered by deflated Sharpe, then agent
/// id, and get a 1-based `declared_mandate_ordinal`; across classes, and
/// against the host board, nothing is compared, because the columns answer
/// different questions. A relative verdict's benchmark is looked up by id in
/// the field being ranked, in the same window-major cells; a field without it
/// fails that agent's declared verdict closed. With an empty map this is
/// [`rank`].
pub fn rank_declared(
    subs: &[AgentSubmission],
    declarations: &MandateDeclarations,
    cfg: &ScoreConfig,
) -> Vec<CompositeScore> {
    // Shared-cell restriction first: everything below — attribution, the
    // data-snooping family, crowdedness and the scores themselves — must see the
    // same field, or the fairness control would apply to the rank key only.
    // Keep `subs` intact: safety judgments must not discard unshared traces.
    let restricted;
    let field: &[AgentSubmission] = if cfg.shared_run_set {
        restricted = restrict_to_shared_positions(subs);
        &restricted
    } else {
        subs
    };

    // A ranked field exposes at least one tried strategy per distinct entry.
    // Refuse a host configuration that understates that observable search
    // footprint. `score_agent` has no field context and therefore retains the
    // configured value; ranking uses max(configured N, field size), then adds
    // each entrant's own declared private trials in `score_agent_with`.
    let mut rank_cfg = cfg.clone();
    rank_cfg.n_trials = cfg
        .n_trials
        .max(u32::try_from(field.len()).unwrap_or(u32::MAX));

    // Pooled returns per agent + an equal-weight market proxy (the field average),
    // used for performance attribution: alpha (skill) vs beta (market exposure).
    let tracks: Vec<Vec<Vec<f64>>> = field
        .iter()
        .map(|s| window_tracks(s, rank_cfg.execution_seeds_per_window))
        .collect();
    let pooled: Vec<Vec<f64>> = tracks.iter().map(|t| t.concat()).collect();
    let min_len = pooled.iter().map(Vec::len).min().unwrap_or(0);
    let n_agents = pooled.len().max(1) as f64;
    let market: Vec<f64> = (0..min_len)
        .map(|i| pooled.iter().map(|p| p[i]).sum::<f64>() / n_agents)
        .collect();

    // The RC/SPA null is predictive superiority against one fixed benchmark,
    // not superiority against the candidates' equal-weight average (which is an
    // attribution device only). Prefer the explicitly named benchmark's aligned
    // stream; with no such entrant, cash (zero return) is the declared null.
    let (significance_benchmark, significance_benchmark_label): (Vec<f64>, String) = field
        .iter()
        .position(|s| s.agent_id == rank_cfg.benchmark_agent_id)
        .filter(|&idx| pooled[idx].len() >= min_len)
        .map(|idx| {
            (
                pooled[idx][..min_len].to_vec(),
                rank_cfg.benchmark_agent_id.clone(),
            )
        })
        .unwrap_or_else(|| (vec![0.0; min_len], "zero-return-cash".to_string()));

    // Measured deflation: with enough agents the field's own Sharpe dispersion
    // replaces the configured prior. The measured value is a dispersion of
    // per-period Sharpes, so it goes in as-is; only the configured prior is
    // annualized and needs converting. A small field scores exactly as
    // `score_agent` would, so the configured path stays byte-identical.
    let ids: Vec<&str> = field.iter().map(|s| s.agent_id.as_str()).collect();
    let measured = measured_trials_sr_std(
        &tracks,
        &ids,
        cfg.min_field_for_measured_sr_std,
        cfg.dedup_clones_for_measured_sr_std,
    );
    let defl = measured.as_ref().map_or_else(
        || Deflation::configured(cfg),
        |m| Deflation::measured(m.sr_std, cfg),
    );
    let most_influential_vote = measured.and_then(|m| m.most_influential_vote);

    // The relative verdict's benchmark is a member of this same (restricted)
    // field, so its run `i` is every other agent's cell `i`. Looked up only
    // under that mode: the default path never touches it.
    let benchmark = match cfg.pass_mode {
        PassMode::RelativeToBenchmark => {
            field.iter().find(|s| s.agent_id == cfg.benchmark_agent_id)
        }
        PassMode::All | PassMode::Any | PassMode::AtLeast(_) => None,
    };

    let mut scores: Vec<CompositeScore> = field
        .iter()
        .enumerate()
        .map(|(idx, s)| {
            // The declared verdict's benchmark is resolved in the same
            // restricted field, so its cells line up like the host verdict's.
            let declared = declarations
                .get(&s.agent_id)
                .map(|mandate| ResolvedDeclaration {
                    mandate,
                    benchmark: MandateVerdict::of(mandate)
                        .benchmark_id()
                        .and_then(|id| field.iter().find(|b| b.agent_id == id)),
                });
            let mut cs = score_agent_with(s, &subs[idx].runs, &rank_cfg, defl, benchmark, declared);
            cs.runs_submitted = subs[idx].runs.len();
            cs.field_significance_benchmark = significance_benchmark_label.clone();
            if min_len >= 2 {
                let (alpha, beta) = crate::attribution::alpha_beta(&pooled[idx], &market);
                cs.alpha = alpha;
                cs.beta = beta;
            }
            cs
        })
        .collect();

    // Field-wide data-snooping significance (White's Reality Check): is the
    // leader's edge real after accounting for how many agents were tried?
    if min_len >= 2 {
        let field_excess: Vec<Vec<f64>> = pooled
            .iter()
            .map(|p| {
                p.iter()
                    .take(min_len)
                    .zip(significance_benchmark.iter())
                    .map(|(a, b)| a - b)
                    .collect()
            })
            .collect();
        let rc_p = crate::significance::reality_check_pvalue(
            &field_excess,
            cfg.bootstrap_seed,
            cfg.n_boot,
            cfg.block_prob,
        );
        let spa_p = crate::significance::spa_pvalue(
            &field_excess,
            cfg.bootstrap_seed,
            cfg.n_boot,
            cfg.block_prob,
        );
        let spa_c_p = crate::significance::spa_consistent_pvalue(
            &field_excess,
            cfg.bootstrap_seed,
            cfg.n_boot,
            cfg.block_prob,
        );
        let sd = crate::significance::step_down_significant(
            &field_excess,
            cfg.bootstrap_seed,
            cfg.n_boot,
            cfg.block_prob,
            cfg.alpha,
        );
        // The four field tests share one bootstrap boundary, so they fail
        // together. The unscored defaults already in every score (p = 1.0, not
        // step-down significant) are the conservative reading; the label says
        // the tests were refused rather than run, so a reader cannot mistake
        // "unscored" for "the field cleared nothing".
        let field_error = rc_p
            .as_ref()
            .err()
            .or(spa_p.as_ref().err())
            .or(spa_c_p.as_ref().err())
            .or(sd.as_ref().err())
            .map(ToString::to_string);
        if let Some(error) = field_error {
            for cs in scores.iter_mut() {
                cs.field_significance_benchmark = format!("unscored: {error}");
            }
        } else {
            let (rc_p, spa_p, spa_c_p) = (rc_p.unwrap(), spa_p.unwrap(), spa_c_p.unwrap());
            for cs in scores.iter_mut() {
                cs.field_reality_check_p = rc_p;
                cs.field_spa_p = spa_p;
                cs.field_spa_consistent_p = spa_c_p;
            }
            for (cs, s) in scores.iter_mut().zip(sd.unwrap()) {
                cs.step_down_significant = s;
            }
        }
    }

    // Crowdedness: how correlated is each agent's return stream with the rest of
    // the field? High = riding the same factor as everyone else (a common beta
    // that decays for the whole board at once); low/negative = diversifying skill.
    // Reported, not gating — the field-relative sibling of decay/calibration.
    if min_len >= 2 && pooled.len() >= 2 {
        let aligned: Vec<&[f64]> = pooled.iter().map(|p| &p[..min_len]).collect();
        for (idx, cs) in scores.iter_mut().enumerate() {
            let peers: Vec<&[f64]> = aligned
                .iter()
                .enumerate()
                .filter(|&(j, _)| j != idx)
                .map(|(_, &p)| p)
                .collect();
            let crowdedness = crate::correlation::crowdedness(aligned[idx], &peers);
            cs.field_crowdedness = crowdedness.mean_corr;
            cs.field_crowdedness_peers = crowdedness.n_peers;
        }
    }

    // Pareto front over (return↑, drawdown↓, turnover↓). Only an agent whose
    // pooled track has a Sharpe ratio is a member. Every agent with at least
    // one observation can dominate, because return, drawdown and turnover are
    // defined without a Sharpe ratio: an agent that a never-trading track beats
    // on all three is not optimal. An empty track has no return to compare and
    // dominates nobody. `pooled` is in field order, as `scores` still is before
    // the sort below.
    let member: Vec<bool> = tracks.iter().map(|t| !has_no_sharpe_ratio(t)).collect();
    let pareto: Vec<bool> = (0..scores.len())
        .map(|i| {
            member[i]
                && !(0..scores.len())
                    .any(|j| j != i && !pooled[j].is_empty() && dominates(&scores[j], &scores[i]))
        })
        .collect();
    for (cs, p) in scores.iter_mut().zip(pareto) {
        cs.pareto_optimal = p;
    }
    // The measured dispersion is one number for the whole field, so every row
    // carries the same disclosure beside its `trials_sr_std_source`.
    for cs in &mut scores {
        cs.trials_sr_std_most_influential_vote = most_influential_vote.clone();
    }

    let sort_key = |s: &CompositeScore| match cfg.rank_key {
        RankKey::DeflatedSharpe => s.composite,
        RankKey::Alpha => {
            if s.rank_eligible {
                s.alpha
            } else {
                f64::NEG_INFINITY
            }
        }
    };
    scores.sort_by(|a, b| {
        b.rank_eligible
            .cmp(&a.rank_eligible)
            .then(
                sort_key(b)
                    .partial_cmp(&sort_key(a))
                    .unwrap_or(std::cmp::Ordering::Equal),
            )
            .then(
                b.raw_mean_return
                    .partial_cmp(&a.raw_mean_return)
                    .unwrap_or(std::cmp::Ordering::Equal),
            )
    });

    // DSR tie bands: walking the eligible agents in ranked order, an agent joins
    // the previous band when their DSR confidence intervals overlap (a difference
    // the resampling can't distinguish from noise). A new, separable agent opens a
    // new band. Then flag every agent whose band holds more than one member: its
    // rank is not statistically real. This is the whole point of the board: the
    // "return-rank is luck" failure must not reappear at the DSR.
    let mut group = 0usize;
    let mut prev: Option<usize> = None;
    for i in 0..scores.len() {
        if !scores[i].rank_eligible {
            continue;
        }
        let same_band = matches!(prev, Some(p) if ci_overlap(&scores[p], &scores[i]));
        if !same_band {
            group += 1;
        }
        scores[i].tie_group = group;
        prev = Some(i);
    }

    // Within a tie band the DSR ordering is statistical noise, so a cleaner
    // process breaks the tie: eligible band members reorder by graded process
    // score (descending) ahead of the DSR order they arrived in. This is
    // **ordering within statistical ties only, never eligibility**: warn
    // events are real information, but not calibrated enough to gate, and
    // block-severity gating is untouched. Band membership itself was fixed
    // above from the DSR-sorted walk; the stable sort keeps the DSR order for
    // members with equal process scores, so an all-clean board is unchanged.
    // Eligible agents sort first and bands are assigned in one forward walk,
    // so each band is a contiguous slice.
    let mut i = 0;
    while i < scores.len() {
        if !scores[i].rank_eligible {
            i += 1;
            continue;
        }
        let band = scores[i].tie_group;
        let mut j = i + 1;
        while j < scores.len() && scores[j].rank_eligible && scores[j].tie_group == band {
            j += 1;
        }
        scores[i..j].sort_by(|a, b| {
            b.process_score
                .partial_cmp(&a.process_score)
                .unwrap_or(std::cmp::Ordering::Equal)
        });
        i = j;
    }

    // 1-based ordinal rank among eligible agents (the scale-invariant rank mode,
    // assigned in final sorted order). Ineligible agents keep ordinal 0.
    let mut ord = 0usize;
    for cs in scores.iter_mut() {
        if cs.rank_eligible {
            ord += 1;
            cs.rank_ordinal = ord;
        }
    }

    let mut band_counts = vec![0usize; group + 1];
    for cs in &scores {
        if cs.rank_eligible {
            band_counts[cs.tie_group] += 1;
        }
    }
    for cs in scores.iter_mut() {
        if cs.rank_eligible {
            cs.dsr_tied = band_counts[cs.tie_group] > 1;
        }
    }

    // Declared-mandate ordinal: within each mandate class (one resolved
    // verdict), the declared-eligible agents ordered by deflated Sharpe, then
    // id. The board order above is untouched.
    let mut classes: Vec<(&MandateVerdict, usize)> = scores
        .iter()
        .enumerate()
        .filter(|(_, s)| s.declared_mandate_eligible == Some(true))
        .filter_map(|(i, s)| s.verdict_applied.as_ref().map(|v| (v, i)))
        .collect();
    classes.sort_by(|(va, ia), (vb, ib)| {
        let (a, b) = (&scores[*ia], &scores[*ib]);
        class_key(va)
            .cmp(&class_key(vb))
            .then(
                b.deflated_sharpe
                    .partial_cmp(&a.deflated_sharpe)
                    .unwrap_or(std::cmp::Ordering::Equal),
            )
            .then(a.agent_id.cmp(&b.agent_id))
    });
    let mut ordinals: Vec<(usize, usize)> = Vec::with_capacity(classes.len());
    let mut prev: Option<&MandateVerdict> = None;
    let mut ord = 0usize;
    for (v, i) in classes {
        if prev != Some(v) {
            ord = 0;
        }
        ord += 1;
        ordinals.push((i, ord));
        prev = Some(v);
    }
    for (i, ord) in ordinals {
        scores[i].declared_mandate_ordinal = Some(ord);
    }
    scores
}

/// Do two agents' Deflated-Sharpe confidence intervals overlap? Overlapping CIs
/// mean the difference in their DSR point estimates is within sampling noise, so
/// they belong in the same tie band rather than being hard-ranked.
/// An entry without an interval reports no overlap: an unavailable interval
/// supports no claim about either agent, and eligibility already excludes such
/// an entry from the banding this feeds.
fn ci_overlap(a: &CompositeScore, b: &CompositeScore) -> bool {
    match (a.dsr_ci_low, a.dsr_ci_high, b.dsr_ci_low, b.dsr_ci_high) {
        (Some(a_low), Some(a_high), Some(b_low), Some(b_high)) => {
            a_low <= b_high && b_low <= a_high
        }
        _ => false,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::deflated_sharpe::{
        deflated_sharpe_ratio, expected_max_sharpe, probabilistic_sharpe_ratio, sharpe_ratio,
    };
    use crate::process::ProcessEvent;

    /// Deterministic run: mean drift + a sinusoidal wiggle (no RNG → reproducible).
    fn run(mean_ret: f64, amp: f64, n: usize) -> Run {
        let returns = (0..n)
            .map(|i| mean_ret + amp * (i as f64 * 0.7).sin())
            .collect();
        Run {
            returns,
            trace: Trace::default(),
            confidences: Vec::new(),
            outcomes: Vec::new(),
            cost: 0.0,
        }
    }

    fn agent(id: &str, runs: Vec<Run>) -> AgentSubmission {
        AgentSubmission {
            agent_id: id.to_string(),
            runs,
            in_sample_trials: 0,
            candidates: Vec::new(),
        }
    }

    /// R02: a configured dispersion that is not a dispersion cannot score.
    ///
    /// A negative `trials_sr_std` used to zero the deflation bar, so the whole
    /// board was deflated against the benchmark alone and a skilled agent was
    /// ranked on an inflated Deflated Sharpe. The score now carries the reason
    /// and is ineligible.
    #[test]
    fn an_invalid_dispersion_disqualifies_instead_of_inflating_the_score() {
        for bad in [-1.0, f64::NAN, f64::INFINITY] {
            let cfg = ScoreConfig {
                trials_sr_std: bad,
                ..ScoreConfig::default()
            };
            let s = score_agent(
                &agent("skilled", (0..5).map(|_| run(0.002, 0.0005, 60)).collect()),
                &cfg,
            );
            assert!(
                s.deflation_error.is_some(),
                "trials_sr_std {bad} must be reported"
            );
            assert_eq!(s.deflated_sharpe, 0.0);
            assert_eq!(s.deflation_bar_per_period, 0.0);
            assert_eq!(s.dsr_ci_low, None);
            assert_eq!(s.dsr_ci_high, None);
            assert_eq!(s.dsr_se, None);
            assert_eq!(s.composite, 0.0);
            assert!(!s.rank_eligible, "an unscored agent cannot be ranked");
        }
    }

    /// A frequency that is not one cannot score, on the same boundary as a
    /// dispersion that is not one. `+inf` used to divide the annualized prior to
    /// a zero dispersion and score the agent against no deflation bar at all;
    /// zero, negative and NaN were refused under the name `trials_sr_std`, or,
    /// on the measured path of a large field, not refused at all.
    #[test]
    fn an_invalid_frequency_disqualifies_on_the_score_and_rank_paths() {
        let skilled = || {
            let mut sub = agent("skilled", (0..5).map(|_| run(0.002, 0.0005, 60)).collect());
            // Both candidates disperse: a constant one has no deflated Sharpe,
            // which would refuse the selection diagnostic at every frequency.
            sub.candidates = vec![
                (0..30).map(|i| 0.001 + 0.0005 * (i % 2) as f64).collect(),
                (0..30).map(|i| 0.001 * (i % 3) as f64).collect(),
            ];
            sub
        };
        // Five dissimilar agents: enough for the measured path, which converts
        // only the floor with the frequency.
        let field: Vec<AgentSubmission> = (0..5)
            .map(|i| {
                let m = 0.0002 + 0.0003 * i as f64;
                let phase = 0.6 * i as f64;
                let runs = (0..5)
                    .map(|_| {
                        let mut r = run(m, 0.003, 60);
                        r.returns = (0..60)
                            .map(|t| m + 0.003 * (t as f64 * 0.7 + phase).sin())
                            .collect();
                        r
                    })
                    .collect();
                agent(&format!("a{i}"), runs)
            })
            .collect();
        let valid = rank(&field, &ScoreConfig::default());
        assert!(valid
            .iter()
            .all(|s| s.trials_sr_std_source != TrialsSrStdSource::Configured));

        for bad in [f64::INFINITY, 0.0, -252.0, f64::NAN] {
            let cfg = ScoreConfig {
                periods_per_year: bad,
                ..ScoreConfig::default()
            };
            let mut scores = vec![score_agent(&skilled(), &cfg)];
            scores.extend(rank(&field, &cfg));
            for s in &scores {
                assert_eq!(
                    s.deflation_error.as_deref(),
                    Some("periods_per_year must be finite and positive"),
                    "periods_per_year {bad}, {}",
                    s.agent_id
                );
                assert_eq!(s.deflated_sharpe, 0.0);
                assert_eq!(s.deflation_bar_per_period, 0.0);
                assert_eq!(s.dsr_ci_low, None);
                assert_eq!(s.dsr_ci_high, None);
                assert_eq!(s.dsr_se, None);
                assert_eq!(s.composite, 0.0);
                assert!(!s.rank_eligible, "periods_per_year {bad}");
            }
            assert_eq!(
                scores[0].selection_error.as_deref(),
                Some("periods_per_year must be finite and positive")
            );
            assert!(scores[0].selection_gap.is_none());
        }
        // The same agent at a valid frequency scores, so the refusal is the
        // frequency's alone.
        let s = score_agent(&skilled(), &ScoreConfig::default());
        assert!(s.deflation_error.is_none() && s.selection_error.is_none());
        assert!(s.rank_eligible);
    }

    /// R02: a candidate set that cannot be deflated reports no selection
    /// diagnostic, rather than a summary of ratios that were never computed.
    #[test]
    fn an_unscorable_candidate_set_reports_no_selection_gap() {
        let mut sub = agent("skilled", (0..5).map(|_| run(0.002, 0.0005, 60)).collect());
        sub.candidates = vec![vec![0.001, f64::NAN, 0.002], vec![0.001; 30]];
        let s = score_agent(&sub, &ScoreConfig::default());
        assert_eq!(
            s.selection_error.as_deref(),
            Some("observation 1 must be finite")
        );
        assert!(s.selection_median_dsr.is_none());
        assert!(s.selection_gap.is_none());
        // The agent's own track is untouched by its candidate set.
        assert!(s.deflation_error.is_none());
    }

    /// R02 guard: a valid submission scores exactly as it always did, and the
    /// two new fields are absent.
    #[test]
    fn valid_scoring_inputs_return_the_same_numbers() {
        let cfg = ScoreConfig::default();
        let sub = agent("skilled", (0..5).map(|_| run(0.002, 0.0005, 60)).collect());
        let s = score_agent(&sub, &cfg);
        assert!(s.deflation_error.is_none() && s.selection_error.is_none());
        assert!(s.rank_eligible);

        let pooled = pooled_of(&sub);
        let sr_std = per_period_sr_std(&cfg);
        assert_eq!(
            s.deflated_sharpe.to_bits(),
            deflated_sharpe_ratio(&pooled, cfg.n_trials, sr_std)
                .unwrap()
                .to_bits()
        );
        assert_eq!(
            s.deflation_bar_per_period.to_bits(),
            expected_max_sharpe(sr_std, cfg.n_trials).unwrap().to_bits()
        );
        assert!(
            s.dsr_ci_low.unwrap() <= s.deflated_sharpe
                && s.deflated_sharpe <= s.dsr_ci_high.unwrap()
        );
    }

    #[test]
    fn skilled_is_eligible() {
        let s = score_agent(
            &agent("skilled", (0..5).map(|_| run(0.002, 0.0005, 60)).collect()),
            &ScoreConfig::default(),
        );
        assert!(s.rank_eligible, "skilled should be eligible: {s:?}");
        assert!(s.passed_k && s.process_ok);
    }

    #[test]
    fn lucky_high_return_fails_pass_k() {
        // One spectacular run, four noisy zero-mean runs → high raw return, but
        // it does not clear the bar on every run.
        let mut runs = vec![run(0.02, 0.002, 60)];
        runs.extend((0..4).map(|_| run(0.0, 0.003, 60)));
        let s = score_agent(&agent("lucky", runs), &ScoreConfig::default());
        assert!(!s.passed_k, "lucky should fail pass^k");
        assert!(!s.rank_eligible, "lucky must not be rank-eligible: {s:?}");
    }

    #[test]
    fn process_violator_is_disqualified() {
        let mut runs: Vec<Run> = (0..5).map(|_| run(0.002, 0.0005, 60)).collect();
        runs[0].trace.events.push(ProcessEvent::OrderPlaced {
            risk_gate_passed: false,
        });
        let s = score_agent(&agent("violator", runs), &ScoreConfig::default());
        assert!(!s.process_ok);
        assert!(!s.rank_eligible, "a risk-gate bypass must disqualify");
    }

    #[test]
    fn shared_support_cannot_erase_a_process_violation() {
        let cfg = ScoreConfig::default();
        let clean = agent("entrant", vec![run(0.002, 0.0005, 60); 2]);
        let peer = agent("peer", vec![clean.runs[0].clone()]);
        let clean_board = rank(&[clean.clone(), peer.clone()], &cfg);
        assert!(clean_board.iter().all(|s| s.rank_eligible));

        let mut violator = clean;
        violator.runs[1]
            .trace
            .events
            .push(ProcessEvent::DenylistBypass);
        assert!(!score_agent(&violator, &cfg).rank_eligible);
        // The peer lacks exactly the cell carrying the violation. Checking only
        // a violation in the shared cell would also pass on the broken scorer.
        for field in [
            vec![violator.clone(), peer.clone()],
            vec![peer.clone(), violator.clone()],
        ] {
            let declarations = MandateDeclarations::from([(
                "entrant".to_string(),
                DeclaredMandate::AbsoluteReturn,
            )]);
            let board = rank_declared(&field, &declarations, &cfg);
            let score = board.iter().find(|s| s.agent_id == "entrant").unwrap();
            assert_eq!((score.runs_submitted, score.runs_scored), (2, 1));
            assert!(!score.process_ok);
            assert!(!score.rank_eligible);
            assert_eq!(score.declared_mandate_eligible, Some(false));
            assert_eq!(score.rank_ordinal, 0);
            assert_eq!(score.composite, 0.0);
            assert_eq!(score.process_score, 0.0);
            assert!(score.process_floored);
            assert_eq!(score.realized_floored_return, 0.0);
            assert!(
                board
                    .iter()
                    .find(|s| s.agent_id == "peer")
                    .unwrap()
                    .rank_eligible
            );
        }
    }

    #[test]
    fn shared_support_retains_warnings_from_all_submitted_runs() {
        let mut warned = agent("warned", vec![run(0.002, 0.0005, 60); 2]);
        warned.runs[1]
            .trace
            .events
            .push(ProcessEvent::ConcentrationBreach);
        let peer = agent("peer", vec![warned.runs[0].clone()]);
        let board = rank(&[warned, peer], &ScoreConfig::default());
        let score = board.iter().find(|s| s.agent_id == "warned").unwrap();
        assert_eq!((score.runs_submitted, score.runs_scored), (2, 1));
        assert!(score.process_ok && score.rank_eligible);
        assert_eq!(score.process_warnings, 1);
        assert!((score.process_score - 0.9).abs() < 1e-12);
    }

    #[test]
    fn unavailable_bootstrap_is_reported_and_cannot_admit_an_agent() {
        let entrant = agent("entrant", vec![run(0.002, 0.0005, 60); 2]);
        assert!(score_agent(&entrant, &ScoreConfig::default()).rank_eligible);
        let cfg = ScoreConfig {
            n_boot: 0,
            alpha: 2.0,
            ..ScoreConfig::default()
        };
        // An invalid alpha would admit a p=1 fallback without the independent
        // availability gate. No caller's threshold can legitimize a failed test.
        let score = score_agent_declared(&entrant, Some(&DeclaredMandate::AbsoluteReturn), &cfg);
        assert_eq!(
            score.bootstrap_error.as_deref(),
            Some("n_boot must be positive")
        );
        assert_eq!(score.bootstrap_p, 1.0);
        assert!(!score.rank_eligible);
        assert_eq!(score.declared_mandate_eligible, Some(false));
    }

    /// An interval with no bootstrap support is unavailable in the serialized
    /// report, not a zero-width bracket.
    ///
    /// `n_boot = 0` used to reach the interval estimator and come back as
    /// `se = 0` with both bounds on the point estimate, which is the tightest
    /// interval the schema can express, published for the one configuration
    /// from which nothing was resampled. The in-memory value is not the whole
    /// claim: the JSON is what the board and the paper's checklist describe, so
    /// the absence is asserted there too.
    #[test]
    fn an_unsupported_dsr_interval_is_absent_from_the_report() {
        let entrant = agent("entrant", vec![run(0.002, 0.0005, 60); 2]);
        let cfg = ScoreConfig {
            n_boot: 0,
            ..ScoreConfig::default()
        };
        let score = score_agent(&entrant, &cfg);
        assert_eq!(
            score.deflation_error.as_deref(),
            Some("n_boot must be positive")
        );
        assert_eq!(
            (score.dsr_ci_low, score.dsr_ci_high, score.dsr_se),
            (None, None, None)
        );
        // The same configuration is refused by the p-value on this resampler,
        // so the entry is already inadmissible and no ranking changes with it.
        assert_eq!(
            score.bootstrap_error.as_deref(),
            Some("n_boot must be positive")
        );
        assert!(!score.rank_eligible);

        let report = serde_json::to_value(&score).expect("serialize the score");
        for field in ["dsr_ci_low", "dsr_ci_high", "dsr_se"] {
            assert!(
                report.get(field).is_none(),
                "{field} must be absent from the report, got {:?}",
                report.get(field)
            );
        }
        assert_eq!(
            report["deflation_error"], "n_boot must be positive",
            "the report states why the interval is unavailable"
        );

        // A supported configuration still carries all three numbers.
        let supported = score_agent(&entrant, &ScoreConfig::default());
        let report = serde_json::to_value(&supported).expect("serialize the score");
        for field in ["dsr_ci_low", "dsr_ci_high", "dsr_se"] {
            assert!(
                report[field].is_f64(),
                "{field} must be reported when estimated"
            );
        }
    }

    /// The refusal a constant track carries, as the score reports it.
    const CONSTANT_TRACK: &str =
        "returns must not be constant: a constant series has no Sharpe ratio";

    /// Two execution seeds per window whose returns offset exactly: each seed
    /// is a steady positive run, and their per-bar average is the constant
    /// 2^-10, so the pooled track is constant while no run is.
    fn offsetting_seeds() -> AgentSubmission {
        let (c, d) = (1.0 / 1024.0, 1.0 / 4096.0);
        let seed = |sign: f64| Run {
            returns: (0..60)
                .map(|t| c + sign * if t % 2 == 0 { d } else { -d })
                .collect(),
            ..Run::default()
        };
        agent(
            "offsetting",
            (0..5).flat_map(|_| [seed(1.0), seed(-1.0)]).collect(),
        )
    }

    /// Paper audit 2026-09-14, Tier 1 #10: a pooled track with zero sample
    /// variance has no Sharpe ratio, so its deflation is unavailable and the
    /// agent is ineligible for that reason, named.
    ///
    /// Isolated: every other conjunct of the eligibility predicate holds. Each
    /// seed passes its per-run PSR, the bootstrap is significant, the process is
    /// clean, nothing draws down, and `dsr_bar = 0` lets the deflated-Sharpe
    /// conjunct hold at the floor. The pooled Sharpe used to be taken as 0, the
    /// deflated Sharpe came out at 0.1075 and the agent was rank-eligible.
    #[test]
    fn a_constant_pooled_track_is_unavailable_and_says_why() {
        let sub = offsetting_seeds();
        let cfg = ScoreConfig {
            execution_seeds_per_window: 2,
            dsr_bar: 0.0,
            ..ScoreConfig::default()
        };
        assert!(pooled_returns(&sub, 2).iter().all(|&r| r == 1.0 / 1024.0));
        let thresholds = crate::disqualification::DisqualThresholds::from_score_config(&cfg);
        for score in [
            score_agent(&sub, &cfg),
            rank(std::slice::from_ref(&sub), &cfg).remove(0),
        ] {
            assert_eq!(score.deflation_error.as_deref(), Some(CONSTANT_TRACK));
            assert_eq!(score.bootstrap_error, None);
            assert!(score.passed_k && score.process_ok && score.mandate_ok);
            assert!(score.bootstrap_p < cfg.alpha);
            assert_eq!((score.deflated_sharpe, score.psr), (0.0, 0.0));
            assert_eq!(
                (score.dsr_ci_low, score.dsr_ci_high, score.dsr_se),
                (None, None, None)
            );
            assert!(!score.rank_eligible);
            assert_eq!(
                crate::disqualification::classify_disqualification(&score, &thresholds, None, None),
                vec![crate::disqualification::FailReason::DeflationUnavailable]
            );
        }
    }

    /// The audit's own case on the default configuration. All-zero runs (`hold`)
    /// used to report PSR 0.5000000005 and a deflated Sharpe of 0.0872; constant
    /// 0.001 runs, whose rounded mean leaves a residual variance, used to report
    /// PSR and DSR 1.0 and rank. Both now report the refusal, in the serialized
    /// score too.
    #[test]
    fn constant_runs_report_the_refusal_instead_of_a_score() {
        let cfg = ScoreConfig::default();
        for value in [0.0, 0.001] {
            let runs = (0..6)
                .map(|_| Run {
                    returns: vec![value; 60],
                    ..Run::default()
                })
                .collect();
            let sub = agent("flat", runs);
            let score = score_agent(&sub, &cfg);
            assert_eq!(
                score.deflation_error.as_deref(),
                Some(CONSTANT_TRACK),
                "{value}"
            );
            assert_eq!((score.deflated_sharpe, score.psr), (0.0, 0.0));
            assert_eq!(per_run_passes(&sub, None, &cfg), vec![false; 6]);
            assert!(!score.passed_k && !score.rank_eligible);
            let report = serde_json::to_value(&score).expect("serialize the score");
            assert_eq!(report["deflation_error"], CONSTANT_TRACK);
        }
    }

    /// The refusal a non-constant track whose standard deviation underflows to
    /// zero carries.
    const NON_FINITE_SHARPE: &str = "Sharpe ratio is not finite";

    /// Six 60-bar runs of `track`, each with a reported cost, and two dispersed
    /// candidates: on this submission, scored under [`exercised_config`], every
    /// figure read off the pooled Sharpe or the deflated Sharpe is live whenever
    /// the track has a Sharpe ratio. The default 21-bar rolling window fits.
    fn exercised(track: impl Fn(usize) -> f64) -> AgentSubmission {
        let mut sub = agent(
            "exercised",
            (0..6)
                .map(|_| Run {
                    returns: (0..60).map(&track).collect(),
                    cost: 0.25,
                    ..Run::default()
                })
                .collect(),
        );
        sub.candidates = vec![
            (0..30).map(|i| 0.001 * (i % 3) as f64).collect(),
            (0..30)
                .map(|i| 0.0004 * ((i * 7) % 5) as f64 - 0.0003)
                .collect(),
        ];
        sub
    }

    /// The default configuration with a reference population, so the
    /// deflated-Sharpe percentile is live.
    fn exercised_config() -> ScoreConfig {
        ScoreConfig {
            reference_dsr_population: vec![0.1, 0.5, 0.9],
            ..ScoreConfig::default()
        }
    }

    /// Pooled tracks with no Sharpe ratio and the refusal each carries: all
    /// zero (`hold`), constant at a value whose rounded mean leaves a residual
    /// variance (a Sharpe near 2.25e15 under the zero-variance sentinel),
    /// constant and negative, and a non-constant track whose squared deviations
    /// underflow, so its computed standard deviation is exactly zero. Each is
    /// scored alone and as a one-entry board.
    fn no_sharpe_scores() -> Vec<(String, CompositeScore, &'static str)> {
        let cfg = exercised_config();
        let subs = [
            ("all zero", exercised(|_| 0.0), CONSTANT_TRACK),
            ("constant 0.001", exercised(|_| 0.001), CONSTANT_TRACK),
            ("constant -0.002", exercised(|_| -0.002), CONSTANT_TRACK),
            (
                "underflowing",
                exercised(|i| (i % 2) as f64 * 1e-170),
                NON_FINITE_SHARPE,
            ),
        ];
        let mut scores = Vec::new();
        for (label, sub, reason) in subs {
            scores.push((format!("{label} scored"), score_agent(&sub, &cfg), reason));
            scores.push((
                format!("{label} ranked"),
                rank(std::slice::from_ref(&sub), &cfg).remove(0),
                reason,
            ));
        }
        scores
    }

    /// Assert that every named field serializes as `null`: present, as an
    /// optional field of this record always is, and carrying no number.
    fn assert_null_in_report(score: &CompositeScore, fields: &[&str], label: &str) {
        let report = serde_json::to_value(score).expect("serialize the score");
        for field in fields {
            assert_eq!(
                report.get(*field),
                Some(&serde_json::Value::Null),
                "{label} {field}"
            );
        }
    }

    /// Paper audit 2026-09-14, the constant-track refusal carried through the
    /// record: a pooled track with no Sharpe ratio has no deflated Sharpe, so
    /// the figures read off it are absent, not computed from the 0.0 floor.
    ///
    /// Isolated: cost is reported and a reference population is configured, so
    /// the refusal is the only reason either figure can be absent. Before, an
    /// all-zero or constant track reported `dsr_per_cost` 0.0 and
    /// `dsr_percentile` 0.0 beside its `deflation_error`.
    #[test]
    fn a_track_with_no_sharpe_ratio_reports_no_deflated_sharpe_per_cost_or_percentile() {
        let cfg = exercised_config();
        assert!(!cfg.reference_dsr_population.is_empty());
        for (label, score, reason) in no_sharpe_scores() {
            assert_eq!(score.deflation_error.as_deref(), Some(reason), "{label}");
            assert!(score.cost > 0.0, "{label}");
            assert_eq!(
                (score.dsr_per_cost, score.dsr_percentile),
                (None, None),
                "{label}"
            );
            assert_eq!(
                (score.dsr_ci_low, score.dsr_ci_high, score.dsr_se),
                (None, None, None),
                "{label}"
            );
            assert_null_in_report(&score, &["dsr_per_cost", "dsr_percentile"], &label);
        }
    }

    /// The rolling-Sharpe summary of a track with no Sharpe ratio is absent:
    /// each window's Sharpe is the zero-variance sentinel. Before, an all-zero
    /// track reported a worst window of 0.0 and no positive window, and a
    /// constant 0.001 track a worst window near 2.25e15 and every window
    /// positive.
    ///
    /// Isolated: the track spans 340 windows, so its length is not the reason,
    /// and that count is still reported.
    #[test]
    fn a_track_with_no_sharpe_ratio_reports_no_rolling_sharpe_summary() {
        for (label, score, reason) in no_sharpe_scores() {
            assert_eq!(score.deflation_error.as_deref(), Some(reason), "{label}");
            assert_eq!(score.rolling_windows, 340, "{label}");
            assert_eq!(
                (score.rolling_min_sharpe, score.rolling_frac_positive),
                (None, None),
                "{label}"
            );
            assert_null_in_report(
                &score,
                &["rolling_min_sharpe", "rolling_frac_positive"],
                &label,
            );
        }
    }

    /// The revealed-selection score values the submitted track by its Sharpe
    /// ratio, so a submitted track with none has no score. Before, a constant
    /// nonzero track was valued at its sentinel Sharpe and reported a score
    /// and a violation count.
    ///
    /// Isolated: the same candidates beside a dispersed track are comparable
    /// and elicit a score, and the candidates' own deflation, which does not
    /// read the submitted track, is still reported.
    #[test]
    fn a_track_with_no_sharpe_ratio_reports_no_revealed_selection_score() {
        let control = score_agent(
            &exercised(|i| 0.002 + 0.0005 * (i as f64 * 0.7).sin()),
            &exercised_config(),
        );
        assert!(control.econ_rationality_score.is_some());
        for (label, score, reason) in no_sharpe_scores() {
            assert_eq!(score.deflation_error.as_deref(), Some(reason), "{label}");
            assert_eq!(
                (
                    score.econ_rationality_score,
                    score.econ_dominance_violations
                ),
                (None, None),
                "{label}"
            );
            assert!(score.selection_median_dsr.is_some(), "{label}");
            assert_null_in_report(
                &score,
                &["econ_rationality_score", "econ_dominance_violations"],
                &label,
            );
        }
    }

    /// The control: a track with a Sharpe ratio, however small its volatility
    /// or dispersion and however sparse, reports every gated figure exactly as
    /// the ungated computation gives it, so its serialized record is the one
    /// the kernel produced before the refusal reached these fields. The sparse
    /// track keeps even the sentinel Sharpes of its flat windows: it has a
    /// Sharpe ratio, so the refusal does not apply to it.
    #[test]
    fn a_track_with_a_sharpe_ratio_reports_its_figures_unchanged() {
        let cfg = exercised_config();
        let dispersed = |i: usize| 0.002 + 0.0005 * (i as f64 * 0.7).sin();
        let tracks: [(&str, AgentSubmission); 4] = [
            ("dispersed", exercised(dispersed)),
            ("low volatility", exercised(move |i| dispersed(i) * 1e-9)),
            (
                "tiny dispersion",
                exercised(|i| 0.001 + 1e-12 * ((i % 5) as f64 - 2.0)),
            ),
            ("sparse", exercised(|i| if i == 59 { 1e-9 } else { 0.0 })),
        ];
        for (label, sub) in tracks {
            let score = score_agent(&sub, &cfg);
            assert_eq!(score.deflation_error, None, "{label}");
            let pooled = pooled_returns(&sub, 1);
            let rolling = rolling_sharpe(&pooled, cfg.rolling_window).expect("spans windows");
            let choice = elicit_revealed_selection(&sub.candidates, &pooled);
            let mut ungated = score.clone();
            ungated.rolling_min_sharpe = Some(rolling.min_sharpe);
            ungated.rolling_frac_positive = Some(rolling.frac_positive);
            ungated.dsr_per_cost = Some(score.deflated_sharpe / score.cost);
            ungated.dsr_percentile = Some(percentile_of(
                score.deflated_sharpe,
                &cfg.reference_dsr_population,
            ));
            ungated.econ_rationality_score = choice.clone().map(|c| rationality_score(&[c]));
            ungated.econ_dominance_violations = choice.map(|c| usize::from(c.is_dominated()));
            assert_eq!(
                serde_json::to_string(&score).expect("serialize the score"),
                serde_json::to_string(&ungated).expect("serialize the control"),
                "{label}"
            );
            assert!(
                score.rolling_min_sharpe.is_some()
                    && score.dsr_per_cost.is_some()
                    && score.dsr_percentile.is_some()
                    && score.econ_rationality_score.is_some(),
                "{label}"
            );
        }
    }

    /// The per-run half of the refusal, isolated: a constant run among skilled
    /// runs fails its per-run test while the pooled track, which is not
    /// constant, keeps its deflation. The unchecked PSR scored a constant 0.001
    /// run 1.0 and an all-zero run 0.5000000005, so the first passed the default
    /// bar and the second a bar of 0.5, and both agents were rank-eligible.
    #[test]
    fn a_constant_run_fails_its_per_run_test() {
        for (value, per_run_psr_bar) in [(0.001, 0.90), (0.0, 0.5)] {
            let mut runs: Vec<Run> = (0..5).map(|_| run(0.002, 0.0005, 60)).collect();
            runs.push(Run {
                returns: vec![value; 60],
                ..Run::default()
            });
            let sub = agent("one-flat-run", runs);
            let cfg = ScoreConfig {
                per_run_psr_bar,
                ..ScoreConfig::default()
            };
            assert_eq!(
                checked_probabilistic_sharpe_ratio(&sub.runs[5].returns, 0.0)
                    .map_err(|e| e.to_string()),
                Err(CONSTANT_TRACK.to_string())
            );
            assert_eq!(
                per_run_passes(&sub, None, &cfg),
                vec![true, true, true, true, true, false],
                "{value}"
            );
            let score = score_agent(&sub, &cfg);
            assert_eq!(score.deflation_error, None);
            assert!(!score.passed_k && !score.rank_eligible);
            assert_eq!(
                crate::disqualification::classify_disqualification(
                    &score,
                    &crate::disqualification::DisqualThresholds::from_score_config(&cfg),
                    None,
                    None
                ),
                vec![crate::disqualification::FailReason::FailedPassK],
                "{value}"
            );
        }
    }

    /// The relative verdict's zero-excess rule is untouched by the refusal: the
    /// benchmark's own excess is identically zero and still fails every run, as
    /// a failure of pass^k, while its deflation, computed on its dispersed raw
    /// returns, stays available. So the refusal changes neither its verdict nor
    /// the words that report it.
    #[test]
    fn the_zero_excess_refusal_stays_a_failure_not_an_unavailability() {
        let field = relative_field();
        let cfg = ScoreConfig::relative_to_benchmark("buy-and-hold");
        let bench = &field[0];
        assert_eq!(per_run_passes(bench, Some(bench), &cfg), vec![false; 6]);
        let board = rank_declared(
            &field,
            &MandateDeclarations::from([(
                "buy-and-hold".to_string(),
                DeclaredMandate::OutperformBuyAndHold,
            )]),
            &cfg,
        );
        let score = board.iter().find(|s| s.agent_id == "buy-and-hold").unwrap();
        assert_eq!(
            (
                score.deflation_error.as_deref(),
                score.bootstrap_error.as_deref()
            ),
            (None, None)
        );
        assert!(!score.passed_k);
        assert_eq!(score.declared_passed_k, Some(false));
        assert_eq!(
            score.mandate_verdict_label().as_deref(),
            Some("ineligible under declared verdict (relative to buy-and-hold); host-board ineligible")
        );

        // Rule 2 still carries weight the checked PSR does not: a one-bar cell
        // has no excess dispersion, and the checked PSR's 0.0 for fewer than two
        // returns would clear a bar of zero if the rule did not refuse it first.
        let one_bar = |id: &str, r: f64| {
            agent(
                id,
                vec![Run {
                    returns: vec![r],
                    ..Run::default()
                }],
            )
        };
        let zero_bar = ScoreConfig {
            per_run_psr_bar: 0.0,
            ..cfg
        };
        assert_eq!(
            per_run_passes(
                &one_bar("entrant", 0.02),
                Some(&one_bar("buy-and-hold", 0.01)),
                &zero_bar
            ),
            vec![false]
        );
    }

    /// A candidate is scored like a track: a constant candidate has no deflated
    /// Sharpe, so the selection diagnostic is refused and names why. The axis is
    /// advisory, so the agent's own eligibility does not move.
    #[test]
    fn a_constant_candidate_refuses_the_selection_diagnostic() {
        let mut sub = agent("skilled", (0..5).map(|_| run(0.002, 0.0005, 60)).collect());
        sub.candidates = vec![
            (0..30).map(|i| 0.001 * (i % 3) as f64).collect(),
            vec![0.001; 30],
        ];
        let s = score_agent(&sub, &ScoreConfig::default());
        assert_eq!(s.selection_error.as_deref(), Some(CONSTANT_TRACK));
        assert_eq!((s.selection_median_dsr, s.selection_gap), (None, None));
        assert!(s.deflation_error.is_none() && s.rank_eligible);
    }

    /// Paper audit 2026-09-14, Tier 1 #11: declared-mandate eligibility keeps
    /// the availability conjunct of the host predicate, so a declared agent
    /// cannot be eligible on a deflated Sharpe or a bootstrap that was never
    /// estimated.
    ///
    /// `dsr_bar = 0` lets the floor a refused deflation reports clear the
    /// deflated-Sharpe conjunct, and `alpha = 2` lets the 1.0 sentinel of a
    /// refused bootstrap clear the significance conjunct, so availability is the
    /// only term left that can refuse. The same agent is declared-eligible with
    /// both statistics available and declared-ineligible when either is
    /// refused, on the single-score and board paths, under every declaration
    /// that needs no benchmark and under a relative one.
    #[test]
    fn declared_eligibility_requires_available_statistics() {
        let skilled = agent("skilled", (0..5).map(|_| run(0.002, 0.0005, 60)).collect());
        let bench = agent("bench", (0..5).map(|_| run(0.0005, 0.001, 60)).collect());
        let base = ScoreConfig {
            dsr_bar: 0.0,
            alpha: 2.0,
            ..ScoreConfig::default()
        };
        let cases = [
            (skilled.clone(), base.clone(), None, None),
            (
                skilled.clone(),
                ScoreConfig {
                    trials_sr_std: -1.0,
                    ..base.clone()
                },
                Some("trials_sr_std must be finite and non-negative"),
                None,
            ),
            (
                skilled,
                ScoreConfig {
                    n_boot: 0,
                    ..base.clone()
                },
                Some("n_boot must be positive"),
                Some("n_boot must be positive"),
            ),
            (
                offsetting_seeds(),
                ScoreConfig {
                    execution_seeds_per_window: 2,
                    ..base
                },
                Some(CONSTANT_TRACK),
                None,
            ),
        ];
        let absolute = [
            DeclaredMandate::AbsoluteReturn,
            DeclaredMandate::DrawdownCapped {
                max_per_run_drawdown: 0.2,
            },
        ];
        for (sub, cfg, deflation_error, bootstrap_error) in cases {
            let available = deflation_error.is_none() && bootstrap_error.is_none();
            let mut scores = Vec::new();
            for mandate in &absolute {
                scores.push(score_agent_declared(&sub, Some(mandate), &cfg));
                let declarations =
                    MandateDeclarations::from([(sub.agent_id.clone(), mandate.clone())]);
                scores.extend(rank_declared(
                    std::slice::from_ref(&sub),
                    &declarations,
                    &cfg,
                ));
            }
            if sub.runs.len() == bench.runs.len() {
                let relative = DeclaredMandate::RelativeTo {
                    benchmark_id: "bench".to_string(),
                };
                let declarations = MandateDeclarations::from([(sub.agent_id.clone(), relative)]);
                let board = rank_declared(&[sub.clone(), bench.clone()], &declarations, &cfg);
                scores.extend(board.into_iter().filter(|s| s.agent_id == sub.agent_id));
            }
            for score in scores {
                let label = format!("{:?} {:?}", score.declared_mandate, deflation_error);
                assert_eq!(score.deflation_error.as_deref(), deflation_error, "{label}");
                assert_eq!(score.bootstrap_error.as_deref(), bootstrap_error, "{label}");
                assert_eq!(score.declared_passed_k, Some(true), "{label}");
                assert_eq!(score.declared_mandate_eligible, Some(available), "{label}");
                assert_eq!(score.rank_eligible, available, "{label}");
            }
        }
    }

    /// The headline property: a lucky agent with a *higher raw return* ranks
    /// BELOW a skilled agent, because it can't clear the luck-robust gates.
    #[test]
    fn deflation_demotes_luck() {
        let skilled = agent("skilled", (0..5).map(|_| run(0.002, 0.0005, 60)).collect());
        let lucky = {
            let mut runs = vec![run(0.02, 0.002, 60)];
            runs.extend((0..4).map(|_| run(0.0, 0.003, 60)));
            agent("lucky", runs)
        };
        let board = rank(&[lucky.clone(), skilled.clone()], &ScoreConfig::default());

        // Sanity: the lucky agent really does have the higher raw return.
        let lucky_raw = board
            .iter()
            .find(|s| s.agent_id == "lucky")
            .unwrap()
            .raw_mean_return;
        let skilled_raw = board
            .iter()
            .find(|s| s.agent_id == "skilled")
            .unwrap()
            .raw_mean_return;
        assert!(
            lucky_raw > skilled_raw,
            "lucky raw {lucky_raw} should exceed skilled {skilled_raw}"
        );

        // Yet the board ranks the skilled agent first.
        assert_eq!(board[0].agent_id, "skilled");
        assert!(board[0].rank_eligible && !board[1].rank_eligible);
    }

    #[test]
    fn confidence_weighting_rewards_conviction() {
        // Confident on the winning run, cautious on the losing one → the
        // conviction-weighted return beats the flat raw mean.
        let win = Run {
            returns: vec![0.01; 30],
            trace: Trace::default(),
            confidences: vec![0.9; 30],
            outcomes: Vec::new(),
            cost: 0.0,
        };
        let lose = Run {
            returns: vec![-0.005; 30],
            trace: Trace::default(),
            confidences: vec![0.1; 30],
            outcomes: Vec::new(),
            cost: 0.0,
        };
        let s = score_agent(&agent("conv", vec![win, lose]), &ScoreConfig::default());
        assert!(
            s.confidence_weighted_return > s.raw_mean_return,
            "cwr {} should beat raw {}",
            s.confidence_weighted_return,
            s.raw_mean_return
        );
    }

    /// S4: a confidence is a probability, and the weight has to treat it as one.
    /// `brier_score` already clamps the same numbers to `[0, 1]`, so without
    /// this the two legs that read `Run::confidences` disagreed about what the
    /// field means, and an unbounded weight let one run's mean return stand in
    /// for the whole submission's.
    #[test]
    fn a_confidence_outside_zero_to_one_weighs_no_more_than_one_that_is_inside() {
        let weighted = |best: f64, worst: f64| {
            let mut win = run(0.01, 0.0005, 30);
            win.confidences = vec![best; 30];
            let mut lose = run(-0.005, 0.0005, 30);
            lose.confidences = vec![worst; 30];
            score_agent(&agent("conv", vec![win, lose]), &ScoreConfig::default())
                .confidence_weighted_return
        };

        assert_eq!(
            weighted(1e6, 0.1),
            weighted(1.0, 0.1),
            "a confidence above 1 must weigh exactly as much as full conviction"
        );
        assert_eq!(
            weighted(0.9, -1e6),
            weighted(0.9, 0.0),
            "a confidence below 0 must weigh exactly as little as none"
        );
    }

    /// The weight is conviction against the run's realized return. It is not
    /// the calibration pairing, which is `brier_score`'s, so stating the
    /// outcomes beside the same confidences must not move it.
    #[test]
    fn stating_outcomes_does_not_move_the_conviction_weight() {
        let weighted = |outcomes: Vec<bool>| {
            let mut win = run(0.01, 0.0005, 30);
            win.confidences = vec![0.9; 30];
            win.outcomes = outcomes.clone();
            let mut lose = run(-0.005, 0.0005, 30);
            lose.confidences = vec![0.1; 30];
            lose.outcomes = outcomes;
            score_agent(&agent("conv", vec![win, lose]), &ScoreConfig::default())
                .confidence_weighted_return
        };

        assert_eq!(weighted(Vec::new()), weighted(vec![true; 30]));
        assert_eq!(weighted(Vec::new()), weighted(vec![false; 30]));
    }

    #[test]
    fn calibration_pairs_stop_at_each_run_boundary_and_report_support() {
        let mut first = run(0.002, 0.0005, 30);
        first.confidences = vec![0.0, 1.0];
        first.outcomes = vec![false];
        let mut second = run(0.002, 0.0005, 30);
        second.confidences = vec![1.0];
        second.outcomes = vec![true, false];

        let score = score_agent(
            &agent("paired", vec![first, second]),
            &ScoreConfig::default(),
        );
        assert_eq!(score.calibration_observations, 2);
        assert_eq!(
            score.calibration_brier,
            Some(0.0),
            "unpaired tails must not cross a run boundary and become a false error"
        );
    }

    #[test]
    fn cost_efficiency_reported_only_with_cost() {
        let mut r = run(0.002, 0.0005, 30);
        r.cost = 4.0;
        let s = score_agent(&agent("paid", vec![r]), &ScoreConfig::default());
        assert_eq!(s.cost, 4.0);
        assert!(s.return_per_cost.is_some());

        let free = score_agent(
            &agent("free", vec![run(0.002, 0.0005, 30)]),
            &ScoreConfig::default(),
        );
        assert!(free.return_per_cost.is_none());
    }

    #[test]
    fn in_sample_search_raises_the_deflation_bar() {
        let runs: Vec<Run> = (0..5).map(|_| run(0.002, 0.0005, 60)).collect();
        let base = score_agent(&agent("base", runs.clone()), &ScoreConfig::default());
        let mut over = agent("over", runs);
        over.in_sample_trials = 5000;
        let s = score_agent(&over, &ScoreConfig::default());
        assert_eq!(s.effective_n_trials, 5050);
        assert!(
            s.deflated_sharpe <= base.deflated_sharpe,
            "more in-sample search must not raise DSR ({} vs {})",
            s.deflated_sharpe,
            base.deflated_sharpe
        );
    }

    #[test]
    fn ranked_field_size_is_an_observable_trial_floor() {
        let field: Vec<_> = (0..8)
            .map(|i| {
                agent(
                    &format!("agent-{i}"),
                    vec![run(0.002 + f64::from(i) * 0.00001, 0.0005, 60)],
                )
            })
            .collect();
        let cfg = ScoreConfig {
            n_trials: 1,
            min_field_for_measured_sr_std: usize::MAX,
            ..ScoreConfig::default()
        };
        let board = rank(&field, &cfg);
        assert!(board.iter().all(|score| score.effective_n_trials == 8));

        let standalone = score_agent(&field[0], &cfg);
        assert_eq!(standalone.effective_n_trials, 1);
    }

    #[test]
    fn percentile_reported_only_with_reference() {
        let none = score_agent(
            &agent("p", (0..5).map(|_| run(0.002, 0.0005, 60)).collect()),
            &ScoreConfig::default(),
        );
        assert!(none.dsr_percentile.is_none());
        let cfg = ScoreConfig {
            reference_dsr_population: vec![0.0, 0.3, 0.6, 0.9],
            ..ScoreConfig::default()
        };
        let some = score_agent(
            &agent("p", (0..5).map(|_| run(0.002, 0.0005, 60)).collect()),
            &cfg,
        );
        assert!(some.dsr_percentile.is_some());
    }

    #[test]
    fn rolling_sharpe_reported_for_long_tracks() {
        let s = score_agent(
            &agent("roll", (0..5).map(|_| run(0.002, 0.0005, 60)).collect()),
            &ScoreConfig::default(),
        );
        // 300 pooled points ≥ 21-window → both reported, steady edge is all-positive.
        assert!(s.rolling_min_sharpe.is_some());
        let fp = s.rolling_frac_positive.expect("reported");
        assert!(
            (fp - 1.0).abs() < 1e-12,
            "steady edge → all windows positive"
        );
        assert_eq!(s.rolling_windows, 280, "300 - 21 + 1 backing windows");
    }

    #[test]
    fn rolling_sharpe_none_when_track_too_short() {
        let cfg = ScoreConfig {
            rolling_window: 100,
            ..ScoreConfig::default()
        };
        let s = score_agent(&agent("short", vec![run(0.002, 0.0005, 30)]), &cfg);
        assert!(s.rolling_min_sharpe.is_none());
        assert!(s.rolling_frac_positive.is_none());
        assert_eq!(s.rolling_windows, 0);
    }

    #[test]
    fn crowdedness_reports_the_number_of_defined_peers() {
        let field = [
            agent("a", vec![run(0.001, 0.003, 60)]),
            agent("b", vec![run(0.002, 0.004, 60)]),
            agent("c", vec![run(-0.001, 0.002, 60)]),
        ];
        let board = rank(&field, &ScoreConfig::default());
        assert!(board.iter().all(|score| score.field_crowdedness.is_some()));
        assert!(board.iter().all(|score| score.field_crowdedness_peers == 2));
    }

    #[test]
    fn dsr_per_cost_reported_only_with_cost() {
        let mut r = run(0.002, 0.0005, 60);
        r.cost = 5.0;
        let paid = score_agent(&agent("paid", vec![r]), &ScoreConfig::default());
        let dpc = paid.dsr_per_cost.expect("reported with cost");
        assert!((dpc - paid.deflated_sharpe / 5.0).abs() < 1e-12);

        let free = score_agent(
            &agent("free", vec![run(0.002, 0.0005, 60)]),
            &ScoreConfig::default(),
        );
        assert!(free.dsr_per_cost.is_none());
    }

    #[test]
    fn process_violation_floors_realized_return() {
        let mut runs: Vec<Run> = (0..5).map(|_| run(0.02, 0.0005, 60)).collect();
        runs[0].trace.events.push(ProcessEvent::OrderPlaced {
            risk_gate_passed: false,
        });
        let s = score_agent(&agent("cheater", runs), &ScoreConfig::default());
        assert!(s.process_floored, "block violation must set the floor flag");
        assert_eq!(
            s.realized_floored_return, 0.0,
            "floored to no-skill baseline"
        );
        assert!(
            s.raw_mean_return > 0.0,
            "raw return is preserved un-floored"
        );
        assert!(!s.rank_eligible, "eligibility logic intact");
    }

    #[test]
    fn clean_process_is_not_floored() {
        let s = score_agent(
            &agent("clean", (0..5).map(|_| run(0.002, 0.0005, 60)).collect()),
            &ScoreConfig::default(),
        );
        assert!(!s.process_floored);
        assert_eq!(s.realized_floored_return, s.raw_mean_return);
    }

    #[test]
    fn overlapping_dsr_cis_flag_a_tie_and_separation_gets_a_distinct_band() {
        // A bar low enough to admit a clearly-weaker (but still real) agent, so we
        // can exhibit both an indistinguishable pair and a separable outsider.
        let cfg = ScoreConfig {
            n_trials: 2,
            trials_sr_std: 0.01,
            dsr_bar: 0.10,
            per_run_psr_bar: 0.05,
            alpha: 0.9,
            n_boot: 600,
            ..ScoreConfig::default()
        };
        // Two identical strong agents: same track ⇒ identical DSR CIs ⇒ tied.
        let strong_a = agent("strong_a", (0..3).map(|_| run(0.01, 0.001, 60)).collect());
        let strong_b = agent("strong_b", (0..3).map(|_| run(0.01, 0.001, 60)).collect());
        // A much weaker but still-eligible agent: its DSR CI sits well below.
        let weak = agent("weak", (0..3).map(|_| run(0.001, 0.02, 60)).collect());

        let board = rank(&[strong_a, strong_b, weak], &cfg);
        let get = |id: &str| board.iter().find(|s| s.agent_id == id).unwrap();
        let (a, b, w) = (get("strong_a"), get("strong_b"), get("weak"));

        assert!(
            a.rank_eligible && b.rank_eligible && w.rank_eligible,
            "all three should clear the (deliberately low) bar"
        );
        // Overlapping CIs ⇒ same tie band, both flagged indistinguishable.
        assert_eq!(a.tie_group, b.tie_group, "identical CIs share a band");
        assert!(a.dsr_tied && b.dsr_tied, "the pair is flagged tied");
        // The weaker agent's CI is separable ⇒ its own band, not tied.
        assert_ne!(
            w.tie_group, a.tie_group,
            "separable agent gets a distinct band"
        );
        assert!(!w.dsr_tied, "a distinct band is not a tie");
        assert!(
            w.dsr_ci_high.unwrap() < a.dsr_ci_low.unwrap(),
            "weak CI upper {} should sit below strong CI lower {}",
            w.dsr_ci_high.unwrap(),
            a.dsr_ci_low.unwrap()
        );
    }

    #[test]
    fn rank_ordinal_is_one_based_among_eligible() {
        let skilled = agent("skilled", (0..5).map(|_| run(0.002, 0.0005, 60)).collect());
        let lucky = {
            let mut runs = vec![run(0.02, 0.002, 60)];
            runs.extend((0..4).map(|_| run(0.0, 0.003, 60)));
            agent("lucky", runs)
        };
        let board = rank(&[lucky, skilled], &ScoreConfig::default());
        assert_eq!(board[0].rank_ordinal, 1, "leader is ordinal 1");
        assert_eq!(board[1].rank_ordinal, 0, "ineligible gets ordinal 0");
    }

    /// A field where every agent completed the identical cells must rank exactly
    /// as it did before the shared-cell restriction existed: the restriction is
    /// the identity there, down to the last bit of every statistic.
    #[test]
    fn homogeneous_field_is_unchanged_by_shared_run_set() {
        let skilled = agent("skilled", (0..5).map(|_| run(0.002, 0.0005, 60)).collect());
        let lucky = {
            let mut runs = vec![run(0.02, 0.002, 60)];
            runs.extend((0..4).map(|_| run(0.0, 0.003, 60)));
            agent("lucky", runs)
        };
        let steady = agent("steady", (0..5).map(|_| run(0.001, 0.001, 60)).collect());
        let field = [lucky, skilled, steady];
        let on = rank(&field, &ScoreConfig::default());
        let off = rank(
            &field,
            &ScoreConfig {
                shared_run_set: false,
                ..ScoreConfig::default()
            },
        );
        assert_eq!(on, off, "identical cells ⇒ identical board");
        assert!(on
            .iter()
            .all(|s| s.runs_scored == 5 && s.runs_submitted == 5));
    }

    /// The fairness property: an entrant whose runs cover only the easy cells is
    /// compared on the shared cells and gains no rank from the subset.
    #[test]
    fn easy_subset_entrant_is_compared_on_the_shared_cells() {
        // Cells 0–1 are easy (steady edge), cells 2–4 are hard (noisy, no edge).
        // The veteran completed all five; the entrant only the two easy ones, with
        // returns identical to the veteran's on those cells.
        let easy = || run(0.004, 0.0005, 60);
        let hard = || run(0.0, 0.004, 60);
        let veteran = agent("veteran", vec![easy(), easy(), hard(), hard(), hard()]);
        let entrant = agent("entrant", vec![easy(), easy()]);
        let field = [veteran, entrant];

        // Unrestricted, the subset pays: the entrant clears every gate while the
        // veteran's hard cells sink it.
        let off = rank(
            &field,
            &ScoreConfig {
                shared_run_set: false,
                ..ScoreConfig::default()
            },
        );
        assert_eq!(off[0].agent_id, "entrant");
        assert!(off[0].rank_eligible && !off[1].rank_eligible);

        // On the shared cells both are scored on exactly the two easy runs, so
        // their statistics coincide and the entrant holds no rank over the veteran.
        let on = rank(&field, &ScoreConfig::default());
        let get = |id: &str| on.iter().find(|s| s.agent_id == id).unwrap();
        let (v, e) = (get("veteran"), get("entrant"));
        assert_eq!(v.runs_scored, 2);
        assert_eq!(e.runs_scored, 2);
        assert_eq!(v.runs_submitted, 5);
        assert_eq!(e.runs_submitted, 2);
        assert_eq!(v.deflated_sharpe.to_bits(), e.deflated_sharpe.to_bits());
        assert_eq!(v.rank_eligible, e.rank_eligible);
        assert_eq!(v.tie_group, e.tie_group, "indistinguishable ⇒ one band");
        assert!(v.dsr_tied && e.dsr_tied);
        assert!(
            e.rank_ordinal == 0 || v.rank_ordinal <= e.rank_ordinal,
            "the entrant must not rank above the veteran"
        );
    }

    /// An empty submission is ineligible by construction and must not blank the
    /// shared set for everyone else.
    #[test]
    fn empty_submission_does_not_empty_the_shared_cells() {
        let skilled = agent("skilled", (0..5).map(|_| run(0.002, 0.0005, 60)).collect());
        let ghost = agent("ghost", Vec::new());
        let board = rank(&[ghost, skilled], &ScoreConfig::default());
        let get = |id: &str| board.iter().find(|s| s.agent_id == id).unwrap();
        assert_eq!(get("skilled").runs_scored, 5);
        assert!(get("skilled").rank_eligible);
        assert!(!get("ghost").rank_eligible);
    }

    /// Below the measurement floor the configured `trials_sr_std` applies and the
    /// board is byte-identical to scoring each agent alone with the same config.
    #[test]
    fn small_field_keeps_the_configured_sr_std_byte_identical() {
        let cfg = ScoreConfig::default();
        let field: Vec<AgentSubmission> = (0..4)
            .map(|i| {
                let m = 0.001 + 0.001 * i as f64;
                agent(
                    &format!("a{i}"),
                    (0..5).map(|_| run(m, 0.001, 60)).collect(),
                )
            })
            .collect();
        let board = rank(&field, &cfg);
        assert_eq!(board.len(), 4);
        for s in &board {
            assert_eq!(s.trials_sr_std_source, TrialsSrStdSource::Configured);
            assert_eq!(s.trials_sr_std.to_bits(), per_period_sr_std(&cfg).to_bits());
            assert_eq!(s.trials_sr_std_annualized, Some(cfg.trials_sr_std));
            let alone = score_agent(
                field.iter().find(|a| a.agent_id == s.agent_id).unwrap(),
                &cfg,
            );
            assert_eq!(s.deflated_sharpe.to_bits(), alone.deflated_sharpe.to_bits());
            assert_eq!(
                s.dsr_ci_low.map(f64::to_bits),
                alone.dsr_ci_low.map(f64::to_bits)
            );
        }
        // Pinning the measured path off reproduces the same board exactly.
        let pinned = rank(
            &field,
            &ScoreConfig {
                min_field_for_measured_sr_std: usize::MAX,
                ..cfg
            },
        );
        assert_eq!(board, pinned);
    }

    /// With enough agents the deflation uses the field's measured Sharpe
    /// dispersion, every score says so, and submission order cannot move it.
    #[test]
    fn large_field_measures_trials_sr_std_from_the_field() {
        let cfg = ScoreConfig::default();
        // Moderate Sharpes (roughly 0.1 to 0.7 per period) keep the PSR in its
        // sensitive range, so a change in the deflation bar shows in the DSR.
        let field: Vec<AgentSubmission> = (0..5)
            .map(|i| {
                let m = 0.0002 + 0.0003 * i as f64;
                // Each agent gets its own phase: five drifts on one shared
                // wiggle would be a single clone cluster under the collapse.
                let phase = 0.6 * i as f64;
                agent(
                    &format!("a{i}"),
                    (0..5)
                        .map(|_| {
                            let mut r = run(m, 0.003, 60);
                            r.returns = (0..60)
                                .map(|t| m + 0.003 * (t as f64 * 0.7 + phase).sin())
                                .collect();
                            r
                        })
                        .collect(),
                )
            })
            .collect();
        let board = rank(&field, &cfg);

        // Hand-computed reference: sample std of sorted pooled Sharpes.
        let mut sharpes: Vec<f64> = field
            .iter()
            .map(|a| {
                let pooled: Vec<f64> = a
                    .runs
                    .iter()
                    .flat_map(|r| r.returns.iter().copied())
                    .collect();
                sharpe_ratio(&pooled)
            })
            .collect();
        sharpes.sort_by(|a, b| a.partial_cmp(b).unwrap());
        let expected = std_dev(&sharpes);
        assert!(expected > 0.0 && expected.is_finite());

        let mut moved = false;
        for s in &board {
            assert_eq!(s.trials_sr_std_source, TrialsSrStdSource::Measured);
            assert_eq!(s.trials_sr_std.to_bits(), expected.to_bits());
            assert_eq!(s.trials_sr_std_annualized, None);
            let alone = score_agent(
                field.iter().find(|a| a.agent_id == s.agent_id).unwrap(),
                &cfg,
            );
            moved |= s.deflated_sharpe.to_bits() != alone.deflated_sharpe.to_bits();
        }
        assert!(
            moved,
            "measured dispersion must actually move the deflation"
        );

        let mut reversed = field.clone();
        reversed.reverse();
        let again = rank(&reversed, &cfg);
        assert_eq!(again[0].trials_sr_std.to_bits(), expected.to_bits());
    }

    /// A Sybil need not submit literal clones to compress a field measurement:
    /// many genuinely distinct streams can be engineered to have almost the
    /// same Sharpe. The precommitted floor makes that construction unable to
    /// relax deflation, while preserving the measured path when it is stricter.
    #[test]
    fn measured_dispersion_cannot_fall_below_the_precommitted_floor() {
        let cfg = ScoreConfig {
            // Disable clone collapse: this is deliberately a *dissimilar*
            // stream construction, not the near-copy attack covered elsewhere.
            dedup_clones_for_measured_sr_std: false,
            min_measured_trials_sr_std: 0.5,
            ..ScoreConfig::default()
        };
        let field: Vec<AgentSubmission> = (0..5)
            .map(|i| {
                // Cyclic shifts have exactly the same mean and variance, but
                // point in different directions and are not clone-connected.
                let phase = i as f64 * 36.0;
                let returns = (0..180)
                    .map(|t| {
                        0.001 + 0.0004 * (std::f64::consts::TAU * (t as f64 + phase) / 180.0).sin()
                    })
                    .collect();
                agent(
                    &format!("low-dispersion-{i}"),
                    vec![Run {
                        returns,
                        ..Run::default()
                    }],
                )
            })
            .collect();
        let board = rank(&field, &cfg);
        let floor = per_period_sr_std(&cfg);
        assert!(board.iter().all(|s| {
            s.trials_sr_std_source == TrialsSrStdSource::MeasuredFloored
                && s.trials_sr_std.to_bits() == floor.to_bits()
        }));
    }

    /// `n` agents with distinct drifts and distinct phases: no two are clone
    /// connected, and every pooled track has a Sharpe ratio. The measured
    /// dispersion of this field is what an entrant must not be able to move.
    fn dispersed_field(n: usize) -> Vec<AgentSubmission> {
        (0..n)
            .map(|i| {
                let m = 0.0002 + 0.0003 * i as f64;
                let phase = 0.6 * i as f64;
                agent(
                    &format!("a{i}"),
                    (0..5)
                        .map(|_| Run {
                            returns: (0..60)
                                .map(|t| m + 0.003 * (t as f64 * 0.7 + phase).sin())
                                .collect(),
                            ..Run::default()
                        })
                        .collect(),
                )
            })
            .collect()
    }

    /// An entrant whose pooled track is constant at `value`, so it has no
    /// Sharpe ratio. Same shape as a [`dispersed_field`] member.
    fn flat_entrant(id: &str, value: f64) -> AgentSubmission {
        agent(
            id,
            (0..5)
                .map(|_| Run {
                    returns: vec![value; 60],
                    ..Run::default()
                })
                .collect(),
        )
    }

    /// Everything on a score that the field-measured deflation bar determines,
    /// as bits, so an assert fails on 1-ULP drift.
    fn bar_dependent(s: &CompositeScore) -> Vec<String> {
        let bits = |v: Option<f64>| format!("{:?}", v.map(f64::to_bits));
        vec![
            format!("{}", s.trials_sr_std.to_bits()),
            format!("{:?}", s.trials_sr_std_source),
            bits(s.trials_sr_std_annualized),
            format!("{}", s.trials_sr_std_annualized_equivalent.to_bits()),
            format!("{}", s.deflation_bar_per_period.to_bits()),
            format!("{}", s.deflation_bar_annualized_equivalent.to_bits()),
            format!("{}", s.deflated_sharpe.to_bits()),
            format!("{}", s.composite.to_bits()),
            format!("{}", s.psr.to_bits()),
            bits(s.dsr_ci_low),
            bits(s.dsr_ci_high),
            bits(s.dsr_se),
            bits(s.dsr_per_cost),
            bits(s.dsr_percentile),
            bits(s.selection_median_dsr),
            bits(s.selection_gap),
            format!("{:?}", s.deflation_error),
            format!("{}", s.rank_eligible),
            format!("{}", s.rank_ordinal),
        ]
    }

    fn by_id<'a>(board: &'a [CompositeScore], id: &str) -> &'a CompositeScore {
        board
            .iter()
            .find(|s| s.agent_id == id)
            .expect("agent on the board")
    }

    /// A track with no Sharpe ratio must not vote on anybody else's deflation
    /// bar. It used to: `sharpe_ratio` hands an all-zero track the zero-variance
    /// sentinel 0.0, and a constant nonzero track the ~1e15 its rounded mean
    /// leaves, and both are finite, so both entered the field's dispersion
    /// sample. One constant 0.001 entrant beside five dispersed agents pushed
    /// the measured dispersion to 6.265e14 and every other agent's deflated
    /// Sharpe to 0; one all-zero entrant moved the dispersion from 0.17999 to
    /// 0.22405 and the leader's deflated Sharpe from 0.99978 to 0.96288.
    ///
    /// Isolated: the five dispersed agents are unchanged between the two boards,
    /// the field stays above the measurement floor with the entrant removed from
    /// the sample, and the bar is still measured, so the exclusion is the only
    /// thing that can move these bytes.
    #[test]
    fn an_undefined_sharpe_entrant_cannot_move_another_agents_bar() {
        let cfg = ScoreConfig::default();
        let field = dispersed_field(5);
        let baseline = rank(&field, &cfg);
        assert!(baseline
            .iter()
            .all(|s| s.trials_sr_std_source == TrialsSrStdSource::Measured));
        assert!(baseline.iter().any(|s| s.rank_eligible));

        for (label, value) in [("all zero", 0.0), ("constant nonzero", 0.001)] {
            let mut with_entrant = field.clone();
            with_entrant.push(flat_entrant("flat", value));
            let board = rank(&with_entrant, &cfg);
            assert_eq!(board.len(), 6, "{label}");
            for base in &baseline {
                let after = by_id(&board, &base.agent_id);
                assert_eq!(
                    bar_dependent(after),
                    bar_dependent(base),
                    "{label} moved {}",
                    base.agent_id
                );
            }
            assert!(
                board
                    .iter()
                    .any(|s| s.agent_id != "flat" && s.deflated_sharpe > 0.0),
                "{label} drove the whole field to a zero deflated Sharpe"
            );
        }
    }

    /// The excluded entrant is still scored and still refused on its own terms:
    /// exclusion is from the dispersion sample, not from the board.
    #[test]
    fn an_excluded_entrant_is_still_scored_and_refused_on_its_own_terms() {
        let cfg = ScoreConfig::default();
        let mut field = dispersed_field(5);
        field.push(flat_entrant("flat", 0.001));
        let board = rank(&field, &cfg);
        let flat = by_id(&board, "flat");
        assert_eq!(flat.deflation_error.as_deref(), Some(CONSTANT_TRACK));
        assert_eq!((flat.deflated_sharpe, flat.psr), (0.0, 0.0));
        assert!(!flat.rank_eligible && flat.runs_scored == 5);
        assert_eq!(
            flat.trials_sr_std.to_bits(),
            by_id(&board, "a0").trials_sr_std.to_bits(),
            "an excluded agent is deflated against the same field bar as everyone else"
        );
    }

    /// If removing the undefined-Sharpe tracks takes the field below the
    /// measurement floor, the panel falls back to the configured prior and the
    /// record says `Configured`, rather than measuring a dispersion from the
    /// rump field.
    ///
    /// Isolated: the same six submissions measure when the floor is lowered to
    /// the four that qualify, so field size after the exclusion, not the field
    /// itself, is what sends this board down the configured path.
    #[test]
    fn a_field_below_the_floor_after_exclusion_falls_back_to_the_configured_prior() {
        let cfg = ScoreConfig::default();
        let mut field = dispersed_field(4);
        field.push(flat_entrant("flat-zero", 0.0));
        field.push(flat_entrant("flat-nonzero", 0.001));
        let board = rank(&field, &cfg);
        assert_eq!(board.len(), 6);
        for s in &board {
            assert_eq!(s.trials_sr_std_source, TrialsSrStdSource::Configured);
            assert_eq!(s.trials_sr_std.to_bits(), per_period_sr_std(&cfg).to_bits());
            assert_eq!(s.trials_sr_std_annualized, Some(cfg.trials_sr_std));
        }
        let lowered = rank(
            &field,
            &ScoreConfig {
                min_field_for_measured_sr_std: 4,
                ..cfg.clone()
            },
        );
        assert!(lowered
            .iter()
            .all(|s| s.trials_sr_std_source != TrialsSrStdSource::Configured));
    }

    /// Control: on a field where every pooled track has a Sharpe ratio, the new
    /// qualification predicate selects the same agents and the same f64s the old
    /// `sharpe_ratio` / `is_finite` filter selected, so the measured bar and
    /// every figure read off it are the bytes they were. The two committed
    /// golden fields (`golden/*.scores.json`) are the file-level half of this
    /// control.
    #[test]
    fn a_field_with_no_undefined_sharpe_track_measures_the_same_bytes() {
        let cfg = ScoreConfig::default();
        let field = dispersed_field(6);
        let board = rank(&field, &cfg);
        // The pre-fix rule, reproduced: every pooled Sharpe, sorted, sample std.
        let mut sharpes: Vec<f64> = field
            .iter()
            .map(|a| sharpe_ratio(&pooled_returns(a, cfg.execution_seeds_per_window)))
            .collect();
        assert!(sharpes.iter().all(|sr| sr.is_finite()));
        sharpes.sort_by(|a, b| a.partial_cmp(b).expect("finite"));
        let expected = std_dev(&sharpes);
        for s in &board {
            assert_eq!(s.trials_sr_std_source, TrialsSrStdSource::Measured);
            assert_eq!(s.trials_sr_std.to_bits(), expected.to_bits());
            assert_eq!(s.deflation_error, None);
        }
    }

    /// The crowdedness neighbour: a constant nonzero stream is not a peer. Its
    /// deviations around its rounded mean are near 1e-19, so the Pearson
    /// denominator was a residual rather than zero and the stream counted as a
    /// correlated peer of every agent, at a noise correlation near 2e-17.
    ///
    /// Isolated: an all-zero entrant was already refused as a peer (its sum of
    /// squared deviations is exactly zero), so only the constant nonzero case
    /// can move these bytes.
    #[test]
    fn a_constant_entrant_is_not_a_crowdedness_peer() {
        let cfg = ScoreConfig::default();
        let field = dispersed_field(5);
        let baseline = rank(&field, &cfg);
        let mut with_entrant = field.clone();
        with_entrant.push(flat_entrant("flat", 0.001));
        let board = rank(&with_entrant, &cfg);
        for base in &baseline {
            let after = by_id(&board, &base.agent_id);
            assert_eq!(
                after.field_crowdedness.map(f64::to_bits),
                base.field_crowdedness.map(f64::to_bits),
                "{}",
                base.agent_id
            );
            assert_eq!(after.field_crowdedness_peers, base.field_crowdedness_peers);
        }
        let flat = by_id(&board, "flat");
        assert_eq!(
            (flat.field_crowdedness, flat.field_crowdedness_peers),
            (None, 0)
        );
    }

    /// The revealed-selection neighbour: a declared candidate with no Sharpe
    /// ratio is not an option. A constant nonzero candidate was valued at its
    /// ~1e15 sentinel, which dominated every real option and reported the
    /// submitted track as an economic-dominance violation.
    ///
    /// Isolated: the same submission with only the dispersed candidate scores
    /// the same, so the constant candidate is the only thing that moved.
    #[test]
    fn a_constant_candidate_is_not_a_revealed_selection_option() {
        let cfg = ScoreConfig::default();
        let dispersed_candidate: Vec<f64> = (0..30).map(|i| 0.0001 * (i % 3) as f64).collect();
        let mut sub = agent("skilled", (0..5).map(|_| run(0.002, 0.0005, 60)).collect());
        sub.candidates = vec![dispersed_candidate.clone(), vec![0.001; 30]];
        let mut control = sub.clone();
        control.candidates = vec![dispersed_candidate];

        let scored = score_agent(&sub, &cfg);
        let control = score_agent(&control, &cfg);
        assert_eq!(scored.econ_dominance_violations, Some(0));
        assert_eq!(
            scored.econ_rationality_score.map(f64::to_bits),
            control.econ_rationality_score.map(f64::to_bits)
        );
        assert_eq!(
            scored.econ_dominance_violations,
            control.econ_dominance_violations
        );
    }

    /// A deterministic, roughly Gaussian return series with *exactly* the
    /// requested per-period mean and sample standard deviation (a 64-bit LCG
    /// feeding a sum of twelve uniforms, then re-standardized), so a test can
    /// state an agent's per-period Sharpe to the digit without an RNG dependency.
    fn gaussian_like(n: usize, mean_ret: f64, sd: f64, seed: u64) -> Vec<f64> {
        let mut state = seed;
        let mut next = || {
            state = state
                .wrapping_mul(6_364_136_223_846_793_005)
                .wrapping_add(1_442_695_040_888_963_407);
            (state >> 11) as f64 / (1u64 << 53) as f64
        };
        let raw: Vec<f64> = (0..n)
            .map(|_| (0..12).map(|_| next()).sum::<f64>() - 6.0)
            .collect();
        let (m, s) = (mean(&raw), std_dev(&raw));
        raw.iter().map(|x| mean_ret + sd * (x - m) / s).collect()
    }

    fn pooled_of(sub: &AgentSubmission) -> Vec<f64> {
        sub.runs
            .iter()
            .flat_map(|r| r.returns.iter().copied())
            .collect()
    }

    #[test]
    fn execution_replicates_are_averaged_not_counted_as_extra_market_time() {
        // Two 3-bar windows, each run twice under stochastic execution. The
        // pooled inference track must retain six market bars rather than twelve
        // pseudo-independent seed outcomes.
        let sub = agent(
            "replicated",
            vec![
                run(0.01, 0.0, 3),
                run(0.03, 0.0, 3),
                run(-0.02, 0.0, 3),
                run(0.00, 0.0, 3),
            ],
        );
        let cfg = ScoreConfig {
            execution_seeds_per_window: 2,
            ..ScoreConfig::default()
        };
        let pooled = pooled_returns(&sub, cfg.execution_seeds_per_window);
        assert_eq!(pooled.len(), 6);
        assert_eq!(pooled, vec![0.02, 0.02, 0.02, -0.01, -0.01, -0.01]);
        let score = score_agent(&sub, &cfg);
        assert_eq!(score.pooled_observations, 6);
        assert_eq!(
            score.psr.to_bits(),
            probabilistic_sharpe_ratio(&pooled, 0.0).to_bits(),
            "PSR must see the de-duplicated time axis"
        );
    }

    #[test]
    fn one_execution_per_window_preserves_legacy_pooling() {
        let sub = agent("single", vec![run(0.01, 0.002, 4), run(-0.01, 0.001, 5)]);
        assert_eq!(
            pooled_returns(&sub, 1),
            pooled_of(&sub),
            "the default is byte-compatible for one execution per window"
        );
    }

    #[test]
    #[should_panic(expected = "cannot form complete")]
    fn incomplete_execution_replicate_block_is_rejected() {
        let sub = agent(
            "bad",
            vec![
                run(0.01, 0.001, 3),
                run(0.01, 0.001, 3),
                run(0.01, 0.001, 3),
            ],
        );
        let _ = pooled_returns(&sub, 2);
    }

    #[test]
    #[should_panic(expected = "equal return lengths")]
    fn unequal_execution_replicate_lengths_are_rejected() {
        let sub = agent("bad", vec![run(0.01, 0.001, 3), run(0.01, 0.001, 4)]);
        let _ = pooled_returns(&sub, 2);
    }

    /// The configured prior is annualized; the value the deflation actually sees
    /// is that prior divided by `sqrt(periods_per_year)`, exactly once.
    #[test]
    fn annualized_prior_is_converted_per_period_once() {
        let cfg = ScoreConfig {
            trials_sr_std: 0.5,
            periods_per_year: 8760.0,
            ..ScoreConfig::default()
        };
        let expected = 0.5 / 8760f64.sqrt();
        assert_eq!(per_period_sr_std(&cfg).to_bits(), expected.to_bits());

        // A moderate Sharpe (about 0.09 per period) keeps the DSR off its 0/1
        // saturation so the three candidate conversions are distinguishable.
        let sub = agent("a", (0..5).map(|_| run(0.0002, 0.003, 300)).collect());
        let s = score_agent(&sub, &cfg);
        assert_eq!(s.trials_sr_std_source, TrialsSrStdSource::Configured);
        assert_eq!(s.trials_sr_std.to_bits(), expected.to_bits());
        assert_eq!(s.trials_sr_std_annualized, Some(0.5));
        // The DSR was computed with the converted value: not with the raw prior,
        // and not with the prior converted twice.
        let pooled = pooled_of(&sub);
        let once = deflated_sharpe_ratio(&pooled, cfg.n_trials, expected).unwrap();
        let raw = deflated_sharpe_ratio(&pooled, cfg.n_trials, 0.5).unwrap();
        let twice =
            deflated_sharpe_ratio(&pooled, cfg.n_trials, expected / 8760f64.sqrt()).unwrap();
        assert_eq!(s.deflated_sharpe.to_bits(), once.to_bits());
        assert_ne!(s.deflated_sharpe.to_bits(), raw.to_bits());
        assert_ne!(s.deflated_sharpe.to_bits(), twice.to_bits());
    }

    /// Near-clone streams vote once on the measured dispersion: a field of five
    /// distinct agents plus twenty leveraged copies of one of them measures
    /// exactly what the five distinct agents measure, the copies are still on
    /// the board, and submission order cannot move the result. A field with no
    /// clones measures byte for byte as it does with the collapse off.
    #[test]
    fn clone_clusters_vote_once_on_the_measured_sr_std() {
        let cfg = ScoreConfig::default();
        let distinct: Vec<AgentSubmission> = (0..5)
            .map(|i| {
                agent(
                    &format!("a{i}"),
                    vec![Run {
                        returns: gaussian_like(120, 0.0002 + 0.0003 * i as f64, 0.003, 11 + i),
                        trace: Trace::default(),
                        confidences: vec![],
                        outcomes: vec![],
                        cost: 0.0,
                    }],
                )
            })
            .collect();
        let base = rank(&distinct, &cfg);
        assert_eq!(base[0].trials_sr_std_source, TrialsSrStdSource::Measured);
        let off = rank(
            &distinct,
            &ScoreConfig {
                dedup_clones_for_measured_sr_std: false,
                ..cfg.clone()
            },
        );
        assert_eq!(base, off, "no clones: the collapse is the identity");

        let mut flooded = distinct.clone();
        for k in 0..20 {
            let mut copy = distinct[2].clone();
            copy.agent_id = format!("copy{k:02}");
            let lever = 1.0 + 0.05 * k as f64;
            copy.runs[0].returns.iter_mut().for_each(|r| *r *= lever);
            flooded.push(copy);
        }
        let board = rank(&flooded, &cfg);
        assert_eq!(board.len(), 25, "clones are still scored");
        assert_eq!(
            board[0].trials_sr_std.to_bits(),
            base[0].trials_sr_std.to_bits(),
            "twenty copies of one stream are one vote"
        );
        let mut shuffled = flooded.clone();
        shuffled.rotate_left(7);
        shuffled.swap(0, 12);
        let again = rank(&shuffled, &cfg);
        assert_eq!(
            again[0].trials_sr_std.to_bits(),
            base[0].trials_sr_std.to_bits()
        );

        let exposed = rank(
            &flooded,
            &ScoreConfig {
                dedup_clones_for_measured_sr_std: false,
                ..cfg.clone()
            },
        );
        assert!(
            exposed[0].trials_sr_std < base[0].trials_sr_std,
            "without the collapse the copies shrink the dispersion"
        );
    }

    /// The measured path measures a dispersion of per-period Sharpes, so it is
    /// reported and used as-is: `periods_per_year` must not touch it.
    #[test]
    fn measured_sr_std_is_never_reconverted() {
        let field: Vec<AgentSubmission> = (0..5)
            .map(|i| {
                let m = 0.0002 + 0.0003 * i as f64;
                // Each agent gets its own phase: five drifts on one shared
                // wiggle would be a single clone cluster under the collapse.
                let phase = 0.6 * i as f64;
                agent(
                    &format!("a{i}"),
                    (0..5)
                        .map(|_| {
                            let mut r = run(m, 0.003, 60);
                            r.returns = (0..60)
                                .map(|t| m + 0.003 * (t as f64 * 0.7 + phase).sin())
                                .collect();
                            r
                        })
                        .collect(),
                )
            })
            .collect();
        let mut sharpes: Vec<f64> = field.iter().map(|a| sharpe_ratio(&pooled_of(a))).collect();
        sharpes.sort_by(|a, b| a.partial_cmp(b).unwrap());
        let raw_measured = std_dev(&sharpes);

        for ppy in [1.0, 252.0, 8760.0] {
            // This test isolates unit conversion of a measured value. Disable
            // the separate field-integrity floor, which is covered by its own
            // regression test above.
            let cfg = ScoreConfig {
                min_measured_trials_sr_std: 0.0,
                ..ScoreConfig::for_periods_per_year(ppy)
            };
            let board = rank(&field, &cfg);
            for s in &board {
                assert_eq!(s.trials_sr_std_source, TrialsSrStdSource::Measured);
                assert_eq!(s.trials_sr_std.to_bits(), raw_measured.to_bits());
                assert_eq!(s.trials_sr_std_annualized, None);
                let pooled = pooled_of(field.iter().find(|a| a.agent_id == s.agent_id).unwrap());
                let expected = deflated_sharpe_ratio(&pooled, cfg.n_trials, raw_measured).unwrap();
                assert_eq!(s.deflated_sharpe.to_bits(), expected.to_bits());
            }
        }
    }

    /// The regression the unit fix protects: a daily index-like track (per-period
    /// mean 0.0004, sd 0.011, a Sharpe of 0.036 per day or about 0.57 annualized)
    /// scored with a deflation prior it can legitimately clear is rank-eligible
    /// once the prior is read as annualized, and was not when the same number was
    /// applied per period (`periods_per_year = 1` reproduces the old units).
    ///
    /// The prior here is 0.1 annualized at fifty trials (a field of similar
    /// index strategies), not the 0.5 default: at 0.5 the expected best-of-fifty
    /// luck is an annualized Sharpe of about 1.14, which the index itself sits
    /// below, so no track length clears it. That is the correct verdict for that
    /// prior, and it is the reason the default must be read as annualized: per
    /// period, the same 0.5 demanded an annualized 18.
    #[test]
    fn daily_buy_and_hold_clears_the_corrected_bar() {
        let runs: Vec<Run> = (0..3)
            .map(|i| Run {
                returns: gaussian_like(2500, 0.0004, 0.011, 0x5B_A7 + i),
                ..Run::default()
            })
            .collect();
        let index = agent("buy-and-hold", runs);
        let cfg = ScoreConfig {
            n_trials: 50,
            trials_sr_std: 0.1,
            periods_per_year: 252.0,
            ..ScoreConfig::default()
        };
        let s = score_agent(&index, &cfg);
        assert!(s.psr > 0.99, "the index is clearly positive: {s:?}");
        assert!(
            s.rank_eligible,
            "an index-like daily track must clear an annualized 0.1 prior: {s:?}"
        );

        let old_units = ScoreConfig {
            periods_per_year: 1.0,
            ..cfg
        };
        let old = score_agent(&index, &old_units);
        assert!(
            !old.rank_eligible && old.deflated_sharpe < 0.05,
            "applied per period the same prior was unreachable: {old:?}"
        );
    }

    /// Pins the direction of the conversion: the same annualized prior spread
    /// over more periods per year is a smaller per-period dispersion, so the
    /// per-period deflation benchmark is lower on hourly bars than on daily.
    #[test]
    fn hourly_bar_is_stricter_per_period_than_daily_for_the_same_annualized_prior() {
        let daily = ScoreConfig::for_periods_per_year(252.0);
        let hourly = ScoreConfig::for_periods_per_year(8760.0);
        let star =
            |cfg: &ScoreConfig| expected_max_sharpe(per_period_sr_std(cfg), cfg.n_trials).unwrap();
        assert!(star(&hourly) > 0.0 && star(&daily) > 0.0);
        assert!(
            star(&hourly) < star(&daily),
            "hourly sr_star {} must be below daily {}",
            star(&hourly),
            star(&daily)
        );
        // And the annualized benchmark they imply is the same number.
        let ann_h = star(&hourly) * 8760f64.sqrt();
        let ann_d = star(&daily) * 252f64.sqrt();
        assert!((ann_h - ann_d).abs() < 1e-12, "{ann_h} vs {ann_d}");
    }

    /// With the default `per_run_min_annual_sharpe = 0.0` the per-run test is the
    /// one the benchmark always ran, `PSR(returns, 0) >= per_run_psr_bar`, on
    /// every timeframe.
    #[test]
    fn default_min_annual_sharpe_is_identical_to_the_old_per_run_test() {
        let mut runs = vec![run(0.02, 0.002, 60), run(0.0, 0.003, 60)];
        runs.extend((0..3).map(|_| run(0.002, 0.0005, 60)));
        let sub = agent("mixed", runs);
        let clean = agent("clean", (0..3).map(|_| run(0.002, 0.0005, 60)).collect());
        for ppy in [52.0, 252.0, 8760.0] {
            let cfg = ScoreConfig::for_periods_per_year(ppy);
            assert_eq!(per_run_psr_benchmark(&cfg).to_bits(), 0f64.to_bits());
            let old: Vec<bool> = sub
                .runs
                .iter()
                .map(|r| probabilistic_sharpe_ratio(&r.returns, 0.0) >= cfg.per_run_psr_bar)
                .collect();
            assert!(old.iter().any(|&p| p) && old.iter().any(|&p| !p));
            assert_eq!(
                score_agent(&sub, &cfg).passed_k,
                pass_k(&old, PassMode::All)
            );
            assert!(score_agent(&clean, &cfg).passed_k);
        }
        // A non-zero annualized minimum converts per period and raises the bar.
        let strict = ScoreConfig {
            per_run_min_annual_sharpe: 3.0,
            ..ScoreConfig::for_periods_per_year(252.0)
        };
        assert_eq!(
            per_run_psr_benchmark(&strict).to_bits(),
            (3.0 / 252f64.sqrt()).to_bits()
        );
        let weak = agent("weak", (0..3).map(|_| run(0.0005, 0.004, 60)).collect());
        assert!(score_agent(&weak, &ScoreConfig::for_periods_per_year(252.0)).passed_k);
        assert!(
            !score_agent(&weak, &strict).passed_k,
            "a minimum annualized Sharpe of 3.0 must fail a 0.0005/0.004 track"
        );
    }
    /// A mixed field: two agents that clear every run, one that fails a single
    /// run. A `Run` that fails the per-run PSR bar is the point of pass^k.
    fn field_with_one_single_run_failure() -> Vec<AgentSubmission> {
        let clean = |id: &str| agent(id, (0..6).map(|_| run(0.002, 0.0005, 60)).collect());
        let mut runs: Vec<Run> = (0..5).map(|_| run(0.002, 0.0005, 60)).collect();
        runs.push(run(-0.002, 0.0005, 60));
        vec![clean("a"), agent("one_bad_run", runs), clean("b")]
    }

    /// `pass_mode` defaults to `All`, and under it the eligibility vector of a
    /// mixed field is exactly what the hard-coded `PassMode::All` produced: an
    /// agent that fails a single run is ineligible, every clean agent is not.
    #[test]
    fn default_pass_mode_is_all_and_matches_the_old_gate() {
        let cfg = ScoreConfig::default();
        assert_eq!(cfg.pass_mode, PassMode::All);
        assert_eq!(cfg.mandate.max_run_drawdown, 1.0);

        let field = field_with_one_single_run_failure();
        let board = rank(&field, &cfg);
        let benchmark = per_run_psr_benchmark(&cfg);
        for s in &board {
            let sub = field.iter().find(|a| a.agent_id == s.agent_id).unwrap();
            let old_per_run: Vec<bool> = sub
                .runs
                .iter()
                .map(|r| probabilistic_sharpe_ratio(&r.returns, benchmark) >= cfg.per_run_psr_bar)
                .collect();
            let old_passed_k = pass_k(&old_per_run, PassMode::All);
            assert_eq!(s.passed_k, old_passed_k, "{}", s.agent_id);
            let old_eligible = s.deflated_sharpe >= cfg.dsr_bar
                && old_passed_k
                && s.process_ok
                && s.bootstrap_p < cfg.alpha
                && s.max_drawdown <= cfg.mandate.max_drawdown;
            assert_eq!(s.rank_eligible, old_eligible, "{}", s.agent_id);
        }
        let get = |id: &str| board.iter().find(|s| s.agent_id == id).unwrap();
        assert!(get("a").rank_eligible && get("b").rank_eligible);
        assert!(!get("one_bad_run").rank_eligible);
        assert!(!get("one_bad_run").passed_k);
    }

    /// A regime-dependent edge: profitable on five of six runs, losing on one.
    /// `All` refuses it (not profitable in every regime); `Any` admits it once it
    /// also clears the DSR, the bootstrap, the process check and both drawdown
    /// bounds, which is the "edge tested on the pooled track" half of the preset.
    #[test]
    fn any_mode_admits_a_regime_dependent_edge_the_all_mode_rejects() {
        let mut runs: Vec<Run> = (0..5).map(|_| run(0.003, 0.0005, 60)).collect();
        runs.push(run(-0.001, 0.0005, 60));
        let sub = agent("regime_edge", runs);

        let all = score_agent(&sub, &ScoreConfig::default());
        assert!(!all.passed_k && !all.rank_eligible, "{all:?}");

        let any = score_agent(&sub, &ScoreConfig::reliability_never_catastrophic(0.20));
        // Every other gate holds on its own, so pass^k is the only thing that moved.
        assert!(any.deflated_sharpe >= 0.95);
        assert!(any.bootstrap_p < 0.05 && any.process_ok && any.mandate_ok);
        assert!(any.worst_run_drawdown < 0.20 && any.max_drawdown < 0.20);
        assert!(any.passed_k && any.rank_eligible, "{any:?}");
    }

    /// The reason the per-run bound exists: a track whose pooled drawdown is
    /// inside the pooled cap can still contain one run that draws down past the
    /// per-run cap, because a strong earlier run lifts the pooled peak. The
    /// pooled bound misses it; the per-run bound must not.
    #[test]
    fn per_run_drawdown_bound_rejects_one_catastrophic_run_that_the_pooled_bound_misses() {
        // Five strong runs, then a run that falls 14% from its own start. The
        // pooled cap is a whole-track budget of 20%, which this track respects;
        // the per-run cap says no single regime may lose more than 10%, which
        // it does not.
        let mut runs: Vec<Run> = (0..5).map(|_| run(0.004, 0.0005, 60)).collect();
        let mut crash = run(0.004, 0.0005, 60);
        for r in &mut crash.returns[10..15] {
            *r = -0.03;
        }
        runs.push(crash);
        let sub = agent("one_blowup", runs);

        let loose_pooled = ScoreConfig {
            mandate: Mandate {
                max_drawdown: 0.20,
                max_run_drawdown: 1.0,
            },
            pass_mode: PassMode::Any,
            ..ScoreConfig::default()
        };
        let pooled_only = score_agent(&sub, &loose_pooled);
        assert!(pooled_only.max_drawdown <= 0.20, "{pooled_only:?}");
        assert!(
            pooled_only.mandate_ok && pooled_only.rank_eligible,
            "{pooled_only:?}"
        );

        let mut preset = ScoreConfig::reliability_never_catastrophic(0.10);
        preset.mandate.max_drawdown = 0.20;
        let bounded = score_agent(&sub, &preset);
        assert!(bounded.worst_run_drawdown > 0.10, "{bounded:?}");
        assert!(bounded.max_drawdown <= 0.20, "the pooled bound still holds");
        assert!(bounded.passed_k, "pass^k is not what rejects it");
        assert!(!bounded.mandate_ok && !bounded.rank_eligible, "{bounded:?}");
    }

    /// Eligibility under the preset is a superset of eligibility under the
    /// default on the same field: the preset relaxes pass^k, keeps every other
    /// gate, and the per-run bound is chosen loose enough that a default-eligible
    /// agent (which clears PSR 0.90 on every run) cannot trip it.
    ///
    /// Every agent submits six runs so the shared-cell restriction is the
    /// identity, and the field stays below the measured-deflation floor so the
    /// two boards differ only in the gates under test.
    #[test]
    fn never_catastrophic_preset_is_weaker_than_the_default() {
        let mut field = field_with_one_single_run_failure();
        field.pop();
        let mut runs: Vec<Run> = (0..5).map(|_| run(0.004, 0.0005, 60)).collect();
        let mut crash = run(0.004, 0.0005, 60);
        crash.returns[10] = -0.30;
        runs.push(crash);
        field.push(agent("blowup", runs));
        let mut lucky = vec![run(0.02, 0.002, 60)];
        lucky.extend((0..5).map(|_| run(0.0, 0.003, 60)));
        field.push(agent("lucky", lucky));
        assert!(field.iter().all(|a| a.runs.len() == 6));
        assert!(field.len() < ScoreConfig::default().min_field_for_measured_sr_std);

        let default = rank(&field, &ScoreConfig::default());
        let preset = rank(&field, &ScoreConfig::reliability_never_catastrophic(0.20));
        let eligible = |board: &[CompositeScore]| -> Vec<String> {
            let mut v: Vec<String> = board
                .iter()
                .filter(|s| s.rank_eligible)
                .map(|s| s.agent_id.clone())
                .collect();
            v.sort();
            v
        };
        let (d, p) = (eligible(&default), eligible(&preset));
        assert_eq!(d, vec!["a".to_string()], "{default:?}");
        assert!(
            d.iter().all(|id| p.contains(id)),
            "default {d:?} not within preset {p:?}"
        );
        assert!(p.contains(&"one_bad_run".to_string()) && !d.contains(&"one_bad_run".to_string()));
        assert!(
            !p.contains(&"blowup".to_string()),
            "a blow-up is refused under both"
        );
        // The cost of the weaker claim, stated rather than hidden: the one-hot-run
        // agent was refused by the default through pass^k alone, and its pooled
        // track clears the DSR and the bootstrap, so `Any` admits it. Reliability
        // is asked of the loss side only under this preset.
        assert!(
            p.contains(&"lucky".to_string()) && !d.contains(&"lucky".to_string()),
            "{preset:?}"
        );
    }

    /// A field for the relative verdict: a benchmark that is profitable in five
    /// windows and loses in a sixth (a bear window), and agents defined by how
    /// they sit against it cell by cell. Six runs each, so the shared-cell
    /// restriction is the identity; five agents, so deflation stays configured.
    fn relative_field() -> Vec<AgentSubmission> {
        let bench: Vec<Run> = (0..5)
            .map(|_| run(0.002, 0.0005, 60))
            .chain(std::iter::once(run(-0.003, 0.0005, 60)))
            .collect();
        // Beats the benchmark by a steady margin in every cell, including the
        // bear window, where it still loses money.
        let beats: Vec<Run> = bench
            .iter()
            .map(|b| {
                let mut r = b.clone();
                for (i, x) in r.returns.iter_mut().enumerate() {
                    *x += 0.001 + 0.0002 * (i as f64 * 0.7).sin();
                }
                r
            })
            .collect();
        // Beats it in five cells and trails it in the bear window.
        let mut five_of_six = beats.clone();
        for (i, x) in five_of_six[5].returns.iter_mut().enumerate() {
            *x = bench[5].returns[i] - 0.001;
        }
        // Profitable in every cell yet below the benchmark in every cell.
        let trails: Vec<Run> = bench
            .iter()
            .map(|b| {
                let mut r = b.clone();
                for x in r.returns.iter_mut() {
                    *x = x.abs() * 0.5 + 0.0005;
                }
                r
            })
            .collect();
        vec![
            agent("buy-and-hold", bench.clone()),
            agent("beats", beats),
            agent("five-of-six", five_of_six),
            agent("trails", trails),
            agent("clone", bench),
        ]
    }

    /// The default pass^k verdict does not read the benchmark id, but the
    /// field-wide RC/SPA tests do: they require a named fixed null rather than
    /// silently comparing agents to their own field average.
    #[test]
    fn fixed_significance_benchmark_is_separate_from_default_pass_verdict() {
        let field = relative_field();
        let default = rank(&field, &ScoreConfig::default());
        let renamed = rank(
            &field,
            &ScoreConfig {
                benchmark_agent_id: "no-such-agent".to_string(),
                ..ScoreConfig::default()
            },
        );
        assert_eq!(
            default.iter().map(|s| s.rank_eligible).collect::<Vec<_>>(),
            renamed.iter().map(|s| s.rank_eligible).collect::<Vec<_>>(),
            "changing the significance null must not change default pass^k eligibility"
        );
        assert!(default
            .iter()
            .all(|s| s.field_significance_benchmark == "buy-and-hold"));
        assert!(renamed
            .iter()
            .all(|s| s.field_significance_benchmark == "zero-return-cash"));
        assert_eq!(
            serde_json::from_str::<ScoreConfig>("{\"n_trials\":1,\"trials_sr_std\":0.5,\"dsr_bar\":0.9,\"per_run_psr_bar\":0.9,\"alpha\":0.05,\"bootstrap_seed\":1,\"n_boot\":10,\"block_prob\":0.1}")
                .unwrap()
                .benchmark_agent_id,
            "buy-and-hold"
        );
    }

    /// The relative verdict asks a different question of each cell, and the two
    /// verdicts disagree in both directions: an agent that beats the benchmark
    /// in every window while losing money in the bear one fails the default and
    /// passes relative; an agent profitable everywhere but below the benchmark
    /// everywhere passes the default and fails relative. The benchmark itself
    /// and a clone of it fail relative on the zero-excess rule, and one trailing
    /// cell is enough to fail.
    #[test]
    fn relative_verdict_tests_excess_over_the_same_cell() {
        let field = relative_field();
        let cfg = ScoreConfig::relative_to_benchmark("buy-and-hold");
        let default = rank(&field, &ScoreConfig::default());
        let relative = rank(&field, &cfg);
        let passed = |board: &[CompositeScore], id: &str| {
            board.iter().find(|s| s.agent_id == id).unwrap().passed_k
        };
        assert!(!passed(&default, "beats") && passed(&relative, "beats"));
        assert!(passed(&default, "trails") && !passed(&relative, "trails"));
        // The benchmark has a bear window, so it fails the default too; under
        // relative it and its clone fail for a different reason, zero excess.
        assert!(!passed(&default, "buy-and-hold") && !passed(&relative, "buy-and-hold"));
        assert!(!passed(&relative, "clone"));
        assert!(!passed(&relative, "five-of-six"));

        // The per-cell vector says which cells, not only whether all.
        let bench = &field[0];
        let five = per_run_passes(&field[2], Some(bench), &cfg);
        assert_eq!(five, vec![true, true, true, true, true, false]);
        let zero = per_run_passes(bench, Some(bench), &cfg);
        assert_eq!(zero, vec![false; 6]);
        // The zero-excess refusal is unconditional: even a bar of 0.5, which
        // `norm_cdf(0)` would reach, does not admit the benchmark.
        let lax = ScoreConfig {
            per_run_psr_bar: 0.5,
            ..cfg.clone()
        };
        assert_eq!(per_run_passes(bench, Some(bench), &lax), vec![false; 6]);

        // Only pass^k moves: every other statistic of every agent is the
        // default's, because it is computed on the agent's own raw returns.
        for d in &default {
            let r = relative.iter().find(|s| s.agent_id == d.agent_id).unwrap();
            assert_eq!(d.deflated_sharpe.to_bits(), r.deflated_sharpe.to_bits());
            assert_eq!(d.psr.to_bits(), r.psr.to_bits());
            assert_eq!(d.bootstrap_p.to_bits(), r.bootstrap_p.to_bits());
            assert_eq!(
                d.worst_run_drawdown.to_bits(),
                r.worst_run_drawdown.to_bits()
            );
            assert_eq!(d.process_ok, r.process_ok);
        }
    }

    /// No benchmark, no relative verdict: a field without the named agent, a
    /// single-agent `score_agent`, and a misaligned benchmark all fail every
    /// run rather than falling back to the absolute test.
    #[test]
    fn relative_verdict_without_a_benchmark_fails_every_run() {
        let field = relative_field();
        let cfg = ScoreConfig::relative_to_benchmark("absent");
        assert!(rank(&field, &cfg).iter().all(|s| !s.passed_k));
        let alone = score_agent(
            &field[1],
            &ScoreConfig::relative_to_benchmark("buy-and-hold"),
        );
        assert!(!alone.passed_k);
        let mut short = field[0].clone();
        short.runs[2].returns.pop();
        let v = per_run_passes(
            &field[1],
            Some(&short),
            &ScoreConfig::relative_to_benchmark("buy-and-hold"),
        );
        assert_eq!(v, vec![true, true, false, true, true, true]);
        let mut fewer = field[0].clone();
        fewer.runs.truncate(4);
        let v = per_run_passes(
            &field[1],
            Some(&fewer),
            &ScoreConfig::relative_to_benchmark("buy-and-hold"),
        );
        assert_eq!(v, vec![true, true, true, true, false, false]);
    }

    /// The preset changes exactly two fields of the default.
    #[test]
    fn relative_preset_differs_only_in_mode_and_benchmark_id() {
        let mut preset = serde_json::to_value(ScoreConfig::relative_to_benchmark("index")).unwrap();
        let default = serde_json::to_value(ScoreConfig::default()).unwrap();
        assert_eq!(preset["pass_mode"], "relative_to_benchmark");
        assert_eq!(preset["benchmark_agent_id"], "index");
        preset["pass_mode"] = default["pass_mode"].clone();
        preset["benchmark_agent_id"] = default["benchmark_agent_id"].clone();
        assert_eq!(preset, default);
    }

    /// Warn-severity events lower the reported graded process score and count,
    /// and change **nothing** about eligibility: the predicate the paper states
    /// (zero block-severity violations) is untouched by warns.
    #[test]
    fn warn_events_lower_process_score_and_count_but_not_eligibility() {
        let clean = agent("clean", (0..5).map(|_| run(0.002, 0.0005, 60)).collect());
        let mut warned_runs: Vec<Run> = (0..5).map(|_| run(0.002, 0.0005, 60)).collect();
        warned_runs[0]
            .trace
            .events
            .push(ProcessEvent::ConcentrationBreach);
        warned_runs[3]
            .trace
            .events
            .push(ProcessEvent::ConcentrationBreach);
        let warned = agent("warned", warned_runs);

        let cfg = ScoreConfig::default();
        let c = score_agent(&clean, &cfg);
        let w = score_agent(&warned, &cfg);

        assert_eq!(c.process_warnings, 0);
        assert_eq!(c.process_score, 1.0);
        assert_eq!(w.process_warnings, 2);
        assert!((w.process_score - 0.8).abs() < 1e-9);

        // Eligibility and every gate input are identical with and without warns.
        assert!(c.process_ok && w.process_ok);
        assert_eq!(c.rank_eligible, w.rank_eligible);
        assert!(w.rank_eligible);
        assert_eq!(c.deflated_sharpe.to_bits(), w.deflated_sharpe.to_bits());
        assert_eq!(c.composite.to_bits(), w.composite.to_bits());
    }

    /// A block-severity violation zeroes the graded scalar too (not just the gate).
    #[test]
    fn block_violation_zeroes_graded_process_score() {
        let mut runs: Vec<Run> = (0..3).map(|_| run(0.002, 0.0005, 60)).collect();
        runs[1].trace.events.push(ProcessEvent::DenylistBypass);
        runs[2].trace.events.push(ProcessEvent::ConcentrationBreach);
        let s = score_agent(&agent("blocked", runs), &ScoreConfig::default());
        assert_eq!(s.process_score, 0.0);
        assert_eq!(s.process_warnings, 1, "warns are still counted");
        assert!(!s.process_ok && !s.rank_eligible);
    }

    /// Within a DSR tie band, the cleaner process ranks first, regardless of
    /// submission order. This is ordering within statistical ties only: both
    /// agents stay eligible, tied, and in the same band.
    #[test]
    fn tie_band_orders_cleaner_process_first() {
        let cfg = ScoreConfig {
            n_trials: 2,
            trials_sr_std: 0.01,
            dsr_bar: 0.10,
            per_run_psr_bar: 0.05,
            alpha: 0.9,
            n_boot: 600,
            ..ScoreConfig::default()
        };
        let clean = agent("clean", (0..3).map(|_| run(0.01, 0.001, 60)).collect());
        let mut warned_runs: Vec<Run> = (0..3).map(|_| run(0.01, 0.001, 60)).collect();
        warned_runs[0]
            .trace
            .events
            .push(ProcessEvent::ConcentrationBreach);
        let warned = agent("warned", warned_runs);

        for field in [
            vec![clean.clone(), warned.clone()],
            vec![warned.clone(), clean.clone()],
        ] {
            let board = rank(&field, &cfg);
            assert_eq!(board[0].agent_id, "clean", "cleaner process leads the band");
            assert_eq!(board[1].agent_id, "warned");
            assert_eq!(board[0].rank_ordinal, 1);
            assert_eq!(board[1].rank_ordinal, 2);
            // Ordering within a statistical tie only, never eligibility.
            assert!(board[0].rank_eligible && board[1].rank_eligible);
            assert_eq!(board[0].tie_group, board[1].tie_group);
            assert!(board[0].dsr_tied && board[1].dsr_tied);
        }
    }

    /// The process tie-break never crosses bands: a separably stronger agent
    /// with a warn still ranks above a weaker clean agent in another band.
    #[test]
    fn process_tie_break_never_crosses_tie_bands() {
        let cfg = ScoreConfig {
            n_trials: 2,
            trials_sr_std: 0.01,
            dsr_bar: 0.10,
            per_run_psr_bar: 0.05,
            alpha: 0.9,
            n_boot: 600,
            ..ScoreConfig::default()
        };
        let mut strong_runs: Vec<Run> = (0..3).map(|_| run(0.01, 0.001, 60)).collect();
        strong_runs[0]
            .trace
            .events
            .push(ProcessEvent::ConcentrationBreach);
        let strong_warned = agent("strong_warned", strong_runs);
        let weak_clean = agent("weak_clean", (0..3).map(|_| run(0.001, 0.02, 60)).collect());

        let board = rank(&[weak_clean, strong_warned], &cfg);
        assert!(board.iter().all(|s| s.rank_eligible));
        assert_eq!(board[0].agent_id, "strong_warned");
        assert_ne!(board[0].tie_group, board[1].tie_group, "separable bands");
        assert!(board[0].process_score < board[1].process_score);
    }

    /// The econ-rationality axis is elicited from the declared candidate set and
    /// reported only.
    #[test]
    fn econ_rationality_reported_from_declared_candidates() {
        let cfg = ScoreConfig::default();
        let runs: Vec<Run> = (0..5).map(|_| run(0.002, 0.0005, 60)).collect();

        // No declared candidates: nothing elicitable.
        let none = score_agent(&agent("plain", runs.clone()), &cfg);
        assert!(none.econ_rationality_score.is_none());
        assert!(none.econ_dominance_violations.is_none());

        // A declared candidate with a strictly higher Sharpe than the submitted
        // pooled track: the recorded selection is dominated.
        let mut dominated = agent("dominated", runs.clone());
        dominated.candidates = vec![(0..300)
            .map(|i| 0.01 + 0.0005 * (i as f64 * 0.7).sin())
            .collect()];
        let d = score_agent(&dominated, &cfg);
        assert_eq!(d.econ_rationality_score, Some(0.0));
        assert_eq!(d.econ_dominance_violations, Some(1));

        // Submitting the best of one's declared set is rational.
        let mut rational = agent("rational", runs);
        rational.candidates = vec![(0..300)
            .map(|i| 0.0001 + 0.0005 * (i as f64 * 0.7).sin())
            .collect()];
        let r = score_agent(&rational, &cfg);
        assert_eq!(r.econ_rationality_score, Some(1.0));
        assert_eq!(r.econ_dominance_violations, Some(0));

        // Reported only: the elicited verdict never moves eligibility.
        assert_eq!(d.rank_eligible, r.rank_eligible);
    }

    /// Behavior-role attribution is reported on the score, deterministic, and
    /// keyed by the trace's order patterns.
    ///
    /// The three runs are read as three execution replicates of one market
    /// window, which is the only shape under which a behavior class is separable
    /// from its window. With the default one execution per window the same runs
    /// are three *different* windows and nothing is estimable, which the second
    /// half of this test pins.
    #[test]
    fn behavior_role_contributions_are_reported() {
        let mixed = || {
            let mut runs: Vec<Run> = (0..3).map(|_| run(0.002, 0.0005, 60)).collect();
            for r in &mut runs {
                r.trace.events.push(ProcessEvent::OrderPlaced {
                    risk_gate_passed: true,
                });
            }
            runs[2].trace.events.push(ProcessEvent::ConcentrationBreach);
            runs
        };
        let cfg = ScoreConfig {
            execution_seeds_per_window: 3,
            ..ScoreConfig::default()
        };
        let s = score_agent(&agent("mixed", mixed()), &cfg);
        let names: Vec<&str> = s
            .role_contributions
            .iter()
            .map(|c| c.role.as_str())
            .collect();
        assert_eq!(names, vec!["clean_active", "warned"]);
        // Every loading is estimated on the whole window, not a truncation of it.
        assert!(s.role_contributions.iter().all(|c| c.periods == 60));
        let again = score_agent(&agent("mixed", mixed()), &cfg);
        assert_eq!(s.role_contributions, again.role_contributions);

        // BM3: one execution per window means each run is its own market window,
        // so a behavior class is confounded with the window it occurred in and
        // no loading is reported.
        let per_window = score_agent(&agent("mixed", mixed()), &ScoreConfig::default());
        assert!(
            per_window.role_contributions.is_empty(),
            "{:?}",
            per_window.role_contributions
        );

        let empty = score_agent(&agent("none", Vec::new()), &ScoreConfig::default());
        assert!(empty.role_contributions.is_empty());
    }

    /// BM3, half 2: reported durability is dated by market window, so permuting
    /// the execution seeds inside a window cannot change it.
    ///
    /// Seed replicates are repeated draws of one window's dates, not successive
    /// periods of edge aging. Feeding per-run mean returns to the log-linear
    /// decay regression made the reported half-life a function of the order the
    /// seeds happened to execute in.
    #[test]
    fn durability_is_dated_by_window_not_by_seed_order() {
        // Three windows of two replicates. Window means decay; within each
        // window the two seeds differ sharply, so a per-run series is sensitive
        // to their order while a per-window series is not.
        let make = |m: f64, n: usize| run(m, 0.0005, n);
        let per_window_means = [(0.008, 0.004), (0.004, 0.002), (0.002, 0.001)];
        let ordered: Vec<Run> = per_window_means
            .iter()
            .flat_map(|(a, b)| [make(*a, 40), make(*b, 40)])
            .collect();
        let swapped: Vec<Run> = per_window_means
            .iter()
            .flat_map(|(a, b)| [make(*b, 40), make(*a, 40)])
            .collect();
        let cfg = ScoreConfig {
            execution_seeds_per_window: 2,
            ..ScoreConfig::default()
        };
        let a = score_agent(&agent("ordered", ordered), &cfg);
        let b = score_agent(&agent("swapped", swapped), &cfg);
        assert!(
            a.edge_half_life.is_some(),
            "a decaying track has a half-life"
        );
        assert_eq!(a.edge_half_life, b.edge_half_life);
    }

    /// BM3, half 2: the default one execution per window leaves the reported
    /// half-life exactly where it was, so no published number moves.
    #[test]
    fn durability_with_one_execution_per_window_is_the_per_run_series() {
        let runs: Vec<Run> = [0.008, 0.004, 0.002, 0.001]
            .iter()
            .map(|m| run(*m, 0.0005, 40))
            .collect();
        let per_run: Vec<f64> = runs.iter().map(|r| mean(&r.returns)).collect();
        let s = score_agent(&agent("decaying", runs), &ScoreConfig::default());
        assert_eq!(s.edge_half_life, crate::decay::edge_half_life(&per_run));
        assert!(s.edge_half_life.is_some());
    }

    /// Scores archived before the reported fields existed still parse, with the
    /// documented defaults.
    #[test]
    fn archived_scores_without_new_fields_deserialize_with_defaults() {
        let s = score_agent(
            &agent("archived", (0..3).map(|_| run(0.002, 0.0005, 60)).collect()),
            &ScoreConfig::default(),
        );
        let mut v = serde_json::to_value(&s).expect("serialize");
        let obj = v.as_object_mut().expect("object");
        for field in [
            "process_score",
            "process_warnings",
            "econ_rationality_score",
            "econ_dominance_violations",
            "role_contributions",
        ] {
            assert!(obj.remove(field).is_some(), "{field} should be present");
        }
        let parsed: CompositeScore = serde_json::from_value(v).expect("archived JSON parses");
        assert_eq!(parsed.process_score, 1.0);
        assert_eq!(parsed.process_warnings, 0);
        assert!(parsed.econ_rationality_score.is_none());
        assert!(parsed.econ_dominance_violations.is_none());
        assert!(parsed.role_contributions.is_empty());
    }

    /// `worst_run_drawdown` is the maximum of the per-run drawdowns, each from
    /// its own starting equity, and is not the pooled track's drawdown.
    #[test]
    fn worst_run_drawdown_is_the_max_over_runs_not_the_pooled_track() {
        // Two losing runs of four 5% losses each: every run draws down 18.5%
        // from its own start, while the pooled track, which strings them
        // together, draws down 33.7%. The per-run figure is the max over runs,
        // not the pooled number.
        let down = || Run {
            returns: vec![-0.05; 4],
            ..Run::default()
        };
        let up = Run {
            returns: vec![0.10; 10],
            ..Run::default()
        };
        let sub = agent("runs", vec![up.clone(), down(), down()]);
        let s = score_agent(&sub, &ScoreConfig::default());

        let expected = max_drawdown(&up.returns).max(max_drawdown(&down().returns));
        assert_eq!(s.worst_run_drawdown.to_bits(), expected.to_bits());
        assert!((s.worst_run_drawdown - (1.0 - 0.95f64.powi(4))).abs() < 1e-12);
        assert_eq!(
            s.max_drawdown.to_bits(),
            max_drawdown(&pooled_of(&sub)).to_bits()
        );
        assert!((s.max_drawdown - (1.0 - 0.95f64.powi(8))).abs() < 1e-12);
        assert!(s.max_drawdown > s.worst_run_drawdown);

        let empty = score_agent(&agent("none", Vec::new()), &ScoreConfig::default());
        assert_eq!(empty.worst_run_drawdown, 0.0);
    }

    /// The pooled cap does not imply the per-run cap. Execution seeds are
    /// averaged within a window before the pooled track is formed, so a trough
    /// inside one seed can be cancelled by the opposite move in its sibling and
    /// never appear as a pooled peak-to-trough pair at all.
    #[test]
    fn worst_run_drawdown_can_exceed_pooled_under_seed_averaging() {
        // One window, two anti-correlated execution seeds.
        let sub = agent(
            "anticorrelated",
            vec![
                Run {
                    returns: vec![0.1, -0.2],
                    ..Run::default()
                },
                Run {
                    returns: vec![-0.1, 0.2],
                    ..Run::default()
                },
            ],
        );
        let cfg = ScoreConfig {
            execution_seeds_per_window: 2,
            ..ScoreConfig::default()
        };
        assert_eq!(pooled_returns(&sub, 2), vec![0.0, 0.0]);

        let s = score_agent(&sub, &cfg);
        assert_eq!(s.max_drawdown, 0.0, "pooled track is flat: {s:?}");
        assert!(
            (s.worst_run_drawdown - 0.20).abs() < 1e-12,
            "seed one falls from 1.10 to 0.88: {}",
            s.worst_run_drawdown
        );
        assert!(
            s.worst_run_drawdown > s.max_drawdown,
            "the per-run bound is not implied by the pooled bound: {s:?}"
        );

        // And the gate acts on it: a 10% per-run cap refuses a track the pooled
        // cap of the same size admits.
        let bounded = score_agent(
            &sub,
            &ScoreConfig {
                mandate: Mandate {
                    max_drawdown: 0.10,
                    max_run_drawdown: 0.10,
                },
                ..cfg.clone()
            },
        );
        assert!(!bounded.mandate_ok);
        let pooled_only = score_agent(
            &sub,
            &ScoreConfig {
                mandate: Mandate {
                    max_drawdown: 0.10,
                    max_run_drawdown: 1.0,
                },
                ..cfg
            },
        );
        assert!(pooled_only.mandate_ok);
    }

    // ---- declared mandates -------------------------------------------------

    fn declare(pairs: &[(&str, DeclaredMandate)]) -> MandateDeclarations {
        pairs
            .iter()
            .map(|(id, m)| (id.to_string(), m.clone()))
            .collect()
    }

    /// Everything on a score except the five declared fields, for asserting the
    /// host-verdict columns are untouched by a declaration.
    fn without_declared(mut s: CompositeScore) -> CompositeScore {
        s.declared_mandate = None;
        s.verdict_applied = None;
        s.declared_passed_k = None;
        s.declared_mandate_eligible = None;
        s.declared_mandate_ordinal = None;
        s
    }

    /// A declaration is recorded on the score with the verdict it resolved to,
    /// an undeclared agent carries none of the five fields (absent from its
    /// JSON, not null), and the empty map reproduces `rank` exactly.
    #[test]
    fn declaration_is_recorded_and_absent_by_default() {
        let field = relative_field();
        let cfg = ScoreConfig::default();
        assert_eq!(
            rank(&field, &cfg),
            rank_declared(&field, &declare(&[]), &cfg)
        );

        let board = rank_declared(
            &field,
            &declare(&[
                ("beats", DeclaredMandate::OutperformBuyAndHold),
                (
                    "trails",
                    DeclaredMandate::DrawdownCapped {
                        max_per_run_drawdown: 0.2,
                    },
                ),
            ]),
            &cfg,
        );
        let get = |id: &str| board.iter().find(|s| s.agent_id == id).unwrap();
        assert_eq!(
            get("beats").declared_mandate,
            Some(DeclaredMandate::OutperformBuyAndHold)
        );
        assert_eq!(
            get("beats").verdict_applied,
            Some(MandateVerdict::RelativeTo {
                benchmark_id: "buy-and-hold".to_string()
            })
        );
        assert_eq!(
            get("trails").verdict_applied,
            Some(MandateVerdict::DrawdownCapped {
                max_per_run_drawdown: 0.2
            })
        );
        let json = serde_json::to_string(get("beats")).unwrap();
        assert!(json.contains("\"declared_mandate\":{\"kind\":\"outperform_buy_and_hold\"}"));
        assert!(json.contains(
            "\"verdict_applied\":{\"kind\":\"relative_to\",\"benchmark_id\":\"buy-and-hold\"}"
        ));
        for id in ["buy-and-hold", "five-of-six", "clone"] {
            let s = get(id);
            assert!(s.declared_mandate.is_none() && s.verdict_applied.is_none());
            assert!(s.declared_passed_k.is_none() && s.declared_mandate_eligible.is_none());
            let json = serde_json::to_string(s).unwrap();
            assert!(!json.contains("declared_") && !json.contains("verdict_applied"));
        }
        // The board row says which verdict was applied and how it went.
        assert_eq!(
            get("beats").mandate_verdict_label().as_deref(),
            Some(if get("beats").declared_mandate_eligible == Some(true) {
                "eligible under declared verdict (relative to buy-and-hold); host-board ineligible"
            } else {
                "ineligible under declared verdict (relative to buy-and-hold); host-board ineligible"
            })
        );
        assert!(get("clone").mandate_verdict_label().is_none());

        // The wire shape: the same object as a submission plus `declared_mandate`.
        let wire = r#"[{"agent_id":"a","runs":[{"returns":[0.01,0.02]}],
            "declared_mandate":{"kind":"drawdown_capped","max_per_run_drawdown":0.2}},
            {"agent_id":"b","runs":[{"returns":[0.01,0.02]}]}]"#;
        let parsed: Vec<DeclaredSubmission> = serde_json::from_str(wire).unwrap();
        let (subs, decls) = split_declarations(parsed);
        assert_eq!(subs.len(), 2);
        assert_eq!(subs[0].runs[0].returns, vec![0.01, 0.02]);
        assert_eq!(decls.len(), 1);
        assert_eq!(
            decls["a"],
            DeclaredMandate::DrawdownCapped {
                max_per_run_drawdown: 0.2
            }
        );
    }

    /// An OutperformBuyAndHold declaration is judged relative to itself: the
    /// verdict applied is the relative one, its excess series is identically
    /// zero, and it fails on the zero-excess rule. A clone under another id
    /// fails the same way; an agent that beats it in every cell passes the
    /// declared pass^k.
    #[test]
    fn buy_and_hold_under_long_only_beta_gets_the_relative_verdict_and_fails_it() {
        let field = relative_field();
        let board = rank_declared(
            &field,
            &declare(&[
                ("buy-and-hold", DeclaredMandate::OutperformBuyAndHold),
                ("clone", DeclaredMandate::OutperformBuyAndHold),
                ("beats", DeclaredMandate::OutperformBuyAndHold),
            ]),
            &ScoreConfig::default(),
        );
        let get = |id: &str| board.iter().find(|s| s.agent_id == id).unwrap();
        let relative = Some(MandateVerdict::RelativeTo {
            benchmark_id: "buy-and-hold".to_string(),
        });
        assert_eq!(get("buy-and-hold").verdict_applied, relative);
        assert_eq!(get("buy-and-hold").declared_passed_k, Some(false));
        assert_eq!(get("buy-and-hold").declared_mandate_eligible, Some(false));
        assert_eq!(
            get("buy-and-hold").mandate_verdict_label().as_deref(),
            Some(
                "ineligible under declared verdict (relative to buy-and-hold); host-board ineligible"
            )
        );
        assert_eq!(get("clone").declared_passed_k, Some(false));
        assert_eq!(get("beats").declared_passed_k, Some(true));
        // The host verdict on the same rows is what `rank` says.
        let plain = rank(&field, &ScoreConfig::default());
        for s in &board {
            let p = plain.iter().find(|x| x.agent_id == s.agent_id).unwrap();
            assert_eq!(&without_declared(s.clone()), p, "{}", s.agent_id);
        }
    }

    /// A declaration selects the reliability question and nothing else: under
    /// every declaration kind, every host-verdict column is byte-identical to
    /// `rank`, declared eligibility implies the DSR, bootstrap, process and
    /// host-mandate gates, and raising the DSR bar refuses every declaration.
    #[test]
    fn a_declaration_cannot_flip_dsr_eligibility_or_move_the_host_columns() {
        let field = field_with_one_single_run_failure();
        let kinds = [
            DeclaredMandate::AbsoluteReturn,
            DeclaredMandate::OutperformBuyAndHold,
            DeclaredMandate::RelativeTo {
                benchmark_id: "a".to_string(),
            },
            DeclaredMandate::DrawdownCapped {
                max_per_run_drawdown: 0.5,
            },
        ];
        let cfg = ScoreConfig::default();
        let plain = rank(&field, &cfg);
        for kind in &kinds {
            let decls: MandateDeclarations = field
                .iter()
                .map(|s| (s.agent_id.clone(), kind.clone()))
                .collect();
            let board = rank_declared(&field, &decls, &cfg);
            for s in &board {
                let p = plain.iter().find(|x| x.agent_id == s.agent_id).unwrap();
                assert_eq!(&without_declared(s.clone()), p, "{kind:?} {}", s.agent_id);
                if s.declared_mandate_eligible == Some(true) {
                    assert!(s.deflated_sharpe >= cfg.dsr_bar);
                    assert!(s.bootstrap_p < cfg.alpha);
                    assert!(s.process_ok && s.mandate_ok);
                }
            }
            // Under `AbsoluteReturn` the declared verdict is the host's default
            // verdict, so the two columns agree on every row.
            if *kind == DeclaredMandate::AbsoluteReturn {
                for s in &board {
                    assert_eq!(s.declared_mandate_eligible, Some(s.rank_eligible));
                    assert_eq!(s.declared_passed_k, Some(s.passed_k));
                }
            }
            // No declaration survives a DSR bar nobody clears.
            let strict = ScoreConfig {
                dsr_bar: 10.0,
                ..ScoreConfig::default()
            };
            for s in rank_declared(&field, &decls, &strict) {
                assert_eq!(s.declared_mandate_eligible, Some(false), "{kind:?}");
                assert!(!s.rank_eligible);
            }
        }
        // The one-bad-run agent is refused by the default (one losing window)
        // and passes its drawdown-capped declaration: one run clears the bar
        // and no run draws down past the declared bound. That is the case a
        // declaration exists for, and it is reported, not ranked.
        let capped = rank_declared(
            &field,
            &declare(&[(
                "one_bad_run",
                DeclaredMandate::DrawdownCapped {
                    max_per_run_drawdown: 0.5,
                },
            )]),
            &cfg,
        );
        let bad = capped.iter().find(|s| s.agent_id == "one_bad_run").unwrap();
        assert!(!bad.rank_eligible && !bad.passed_k);
        assert_eq!(bad.declared_passed_k, Some(true));
        assert_eq!(bad.declared_mandate_eligible, Some(true), "{bad:?}");
        assert_eq!(
            bad.mandate_verdict_label().as_deref(),
            Some(
                "eligible under declared verdict (drawdown capped at 0.50 per run); host-board ineligible"
            )
        );
    }

    /// A benchmark the field does not contain, a relative declaration scored
    /// without a field, and a drawdown bound outside (0, 1] all fail the
    /// declared verdict closed; none falls back to the absolute test.
    #[test]
    fn misdeclared_mandates_fail_closed() {
        let field = relative_field();
        let cfg = ScoreConfig::default();
        let board = rank_declared(
            &field,
            &declare(&[(
                "beats",
                DeclaredMandate::RelativeTo {
                    benchmark_id: "absent".to_string(),
                },
            )]),
            &cfg,
        );
        let beats = board.iter().find(|s| s.agent_id == "beats").unwrap();
        assert_eq!(beats.declared_passed_k, Some(false));
        assert_eq!(beats.declared_mandate_eligible, Some(false));
        // The same agent beats buy-and-hold in every cell when the benchmark is
        // named correctly, so the refusal above is the misdeclaration's.
        let ok = rank_declared(
            &field,
            &declare(&[("beats", DeclaredMandate::OutperformBuyAndHold)]),
            &cfg,
        );
        assert_eq!(
            ok.iter()
                .find(|s| s.agent_id == "beats")
                .unwrap()
                .declared_passed_k,
            Some(true)
        );

        // No field, no benchmark.
        let alone = score_agent_declared(
            &field[1],
            Some(&DeclaredMandate::OutperformBuyAndHold),
            &cfg,
        );
        assert_eq!(alone.declared_passed_k, None);
        assert_eq!(alone.declared_mandate_eligible, None);
        assert_eq!(
            score_agent_declared(&field[1], None, &cfg),
            score_agent(&field[1], &cfg)
        );

        // A clean agent passes a well-formed drawdown declaration and fails
        // every malformed one, on the bound alone.
        let clean = field_with_one_single_run_failure();
        let capped = |x: f64| {
            let board = rank_declared(
                &clean,
                &declare(&[(
                    "a",
                    DeclaredMandate::DrawdownCapped {
                        max_per_run_drawdown: x,
                    },
                )]),
                &cfg,
            );
            let a = board.iter().find(|s| s.agent_id == "a").unwrap().clone();
            (a.declared_passed_k, a.declared_mandate_eligible)
        };
        assert_eq!(capped(0.5), (Some(true), Some(true)));
        for bad in [0.0, -0.2, 1.5, f64::NAN, f64::INFINITY] {
            assert_eq!(capped(bad), (Some(true), Some(false)), "bound {bad}");
        }
    }

    /// Declared eligibility never moves the board. An agent that is
    /// host-ineligible and declared-eligible keeps ordinal 0 and its position;
    /// its declared ordinal counts only agents in its own mandate class, so two
    /// agents under different verdicts are each first in their class and never
    /// ordered against each other or against the host ordinal.
    #[test]
    fn declared_eligibility_is_ranked_within_its_mandate_class_only() {
        let field = field_with_one_single_run_failure();
        let cfg = ScoreConfig::default();
        let plain = rank(&field, &cfg);
        let board = rank_declared(
            &field,
            &declare(&[
                (
                    "one_bad_run",
                    DeclaredMandate::DrawdownCapped {
                        max_per_run_drawdown: 0.5,
                    },
                ),
                ("a", DeclaredMandate::AbsoluteReturn),
                ("b", DeclaredMandate::AbsoluteReturn),
            ]),
            &cfg,
        );
        let order = |b: &[CompositeScore]| b.iter().map(|s| s.agent_id.clone()).collect::<Vec<_>>();
        assert_eq!(order(&board), order(&plain));
        let get = |id: &str| board.iter().find(|s| s.agent_id == id).unwrap();
        let bad = get("one_bad_run");
        assert!(!bad.rank_eligible && bad.rank_ordinal == 0);
        assert_eq!(bad.declared_mandate_eligible, Some(true));
        assert_eq!(bad.declared_mandate_ordinal, Some(1));
        // The absolute-return class holds the two host-eligible agents, ordered
        // by DSR then id, and is a separate class from the drawdown-capped one.
        let (a, b) = (get("a"), get("b"));
        assert!(a.rank_eligible && b.rank_eligible);
        let ords: Vec<Option<usize>> = [a, b].iter().map(|s| s.declared_mandate_ordinal).collect();
        assert!(
            ords.contains(&Some(1)) && ords.contains(&Some(2)),
            "{ords:?}"
        );
        let (first, second) = if a.declared_mandate_ordinal == Some(1) {
            (a, b)
        } else {
            (b, a)
        };
        assert!(
            first.deflated_sharpe > second.deflated_sharpe
                || (first.deflated_sharpe == second.deflated_sharpe
                    && first.agent_id < second.agent_id)
        );
        // Host ordinals are unchanged by the declarations.
        for s in &board {
            let p = plain.iter().find(|x| x.agent_id == s.agent_id).unwrap();
            assert_eq!(s.rank_ordinal, p.rank_ordinal);
        }
    }
}