anamnesis-diary 0.6.1

A local-first instrument against self-deception: log what you believe and how sure, then face the real shape of your mind.
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
//! Proper scoring rules and calibration diagnostics.
//!
//! Everything in this module is pure: it takes a slice of resolved
//! [`Sample`]s — a probability you assigned and what actually happened — and
//! returns numbers. No I/O, no randomness, no hidden state. That purity is the
//! point: the conclusions a person reaches about their own judgement should be
//! reproducible and auditable, not the verdict of a black box.
//!
//! References (verified against the literature, see the project README):
//!   * Brier, G.W. (1950). *Verification of forecasts expressed in terms of
//!     probability.* Monthly Weather Review.
//!   * Murphy, A.H. (1973). *A new vector partition of the probability score.*
//!     The reliability–resolution–uncertainty decomposition implemented here.
//!   * Lichtenstein, Fischhoff & Phillips (1982). Calibration / the
//!     over/under-confidence gap (mean confidence minus proportion correct).

use std::collections::BTreeMap;

/// A resolved forecast: the probability assigned to an event, and whether the
/// event happened (`1.0`) or did not (`0.0`).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Sample {
    /// Forecaster's probability that the event is true, in `[0, 1]`.
    pub prob: f64,
    /// Ground truth: `1.0` if the event happened, `0.0` otherwise.
    pub outcome: f64,
}

impl Sample {
    pub fn new(prob: f64, happened: bool) -> Self {
        Sample {
            prob,
            outcome: if happened { 1.0 } else { 0.0 },
        }
    }
}

/// Mean **Brier score**: the mean squared error of probabilistic forecasts.
///
/// `0.0` is perfect. Always saying `0.5` on truly 50/50 events scores `0.25`.
/// Being confidently, maximally wrong every time scores `1.0`. Lower is better.
/// Returns `None` for an empty sample.
pub fn brier(samples: &[Sample]) -> Option<f64> {
    if samples.is_empty() {
        return None;
    }
    let sum: f64 = samples.iter().map(|s| (s.prob - s.outcome).powi(2)).sum();
    Some(sum / samples.len() as f64)
}

/// **Stake-weighted Brier**: the Brier score with each forecast weighted by how
/// much it *mattered*. `weights[i]` scales `samples[i]`; weights `≤ 0` drop out,
/// and a length mismatch or no positive weight yields `None`. With all weights
/// equal this reduces to [`brier`]. The point is to surface whether you are
/// miscalibrated on the calls that carry consequences, not merely on average.
pub fn brier_weighted(samples: &[Sample], weights: &[f64]) -> Option<f64> {
    if samples.is_empty() || samples.len() != weights.len() {
        return None;
    }
    let mut num = 0.0;
    let mut den = 0.0;
    for (s, &w) in samples.iter().zip(weights) {
        if w > 0.0 {
            num += w * (s.prob - s.outcome).powi(2);
            den += w;
        }
    }
    (den > 0.0).then_some(num / den)
}

/// Mean **logarithmic (Good) score**: the average negative log-likelihood of
/// the outcomes under your forecasts. Lower is better.
///
/// The log score is *strictly* proper and punishes confident errors far more
/// harshly than Brier does — one `p = 0.999` forecast on an event that does not
/// happen is brutal. Because a single confident miss would otherwise yield
/// `+∞`, probabilities are clamped into `[eps, 1 - eps]`. A reasonable `eps` is
/// `1e-6`; passing `0.0` recovers the unclamped score.
pub fn log_score(samples: &[Sample], eps: f64) -> Option<f64> {
    if samples.is_empty() {
        return None;
    }
    let sum: f64 = samples
        .iter()
        .map(|s| {
            let p = s.prob.clamp(eps, 1.0 - eps);
            -(s.outcome * p.ln() + (1.0 - s.outcome) * (1.0 - p).ln())
        })
        .sum();
    Some(sum / samples.len() as f64)
}

/// The **base rate**: the fraction of sampled events that actually happened.
/// This is the climatology a useful forecaster must beat.
pub fn base_rate(samples: &[Sample]) -> Option<f64> {
    if samples.is_empty() {
        return None;
    }
    Some(samples.iter().map(|s| s.outcome).sum::<f64>() / samples.len() as f64)
}

/// Murphy's three-way partition of the Brier score.
///
/// `brier == reliability - resolution + uncertainty`, exactly (see
/// [`decompose`]).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Decomposition {
    /// **Reliability** (calibration error). How far your stated probabilities
    /// drift from the frequencies that actually followed them. Lower is better;
    /// `0` means perfect calibration.
    pub reliability: f64,
    /// **Resolution** (discrimination). How much your forecasts move *with*
    /// reality away from the base rate. Higher is better; `0` means you said
    /// the same thing regardless of what was true.
    pub resolution: f64,
    /// **Uncertainty.** The irreducible variance of the outcomes themselves,
    /// `base_rate * (1 - base_rate)`. Nobody can score below this by skill
    /// alone; it is the difficulty of the questions you chose.
    pub uncertainty: f64,
    /// The Brier score reconstructed from the three parts above.
    pub brier: f64,
}

/// Decompose the Brier score into reliability, resolution and uncertainty.
///
/// Forecasts are grouped by their *exact* probability value, which makes the
/// identity `BS = REL - RES + UNC` hold to floating-point precision rather than
/// approximately. (Binning into ranges, as a reliability diagram does, would
/// introduce a within-bin term and only approximate equality.) This exactness
/// is asserted in the test suite.
pub fn decompose(samples: &[Sample]) -> Option<Decomposition> {
    if samples.is_empty() {
        return None;
    }
    let n = samples.len() as f64;
    let o_bar = base_rate(samples).unwrap();

    // Group by the exact bit pattern of the forecast probability. Each group
    // shares a single representative forecast value `f_k`.
    // value = (representative prob, sum of outcomes, count)
    let mut groups: BTreeMap<u64, (f64, f64, f64)> = BTreeMap::new();
    for s in samples {
        let e = groups.entry(s.prob.to_bits()).or_insert((s.prob, 0.0, 0.0));
        e.1 += s.outcome;
        e.2 += 1.0;
    }

    let mut reliability = 0.0;
    let mut resolution = 0.0;
    for (f_k, sum_o, n_k) in groups.values() {
        let o_k = sum_o / n_k; // observed frequency within this forecast value
        reliability += n_k * (f_k - o_k).powi(2);
        resolution += n_k * (o_k - o_bar).powi(2);
    }
    reliability /= n;
    resolution /= n;
    let uncertainty = o_bar * (1.0 - o_bar);

    Some(Decomposition {
        reliability,
        resolution,
        uncertainty,
        brier: reliability - resolution + uncertainty,
    })
}

/// **Brier skill score**: `1 - brier / uncertainty`.
///
/// `0` means you did exactly as well as always predicting the base rate.
/// Positive means skill; negative means you would have been better off
/// parroting climatology. Returns `None` when uncertainty is `0` (every event
/// resolved the same way, so there was nothing to be skillful about).
pub fn skill_score(samples: &[Sample]) -> Option<f64> {
    let d = decompose(samples)?;
    if d.uncertainty == 0.0 {
        return None;
    }
    Some(1.0 - d.brier / d.uncertainty)
}

/// One cell of a reliability diagram.
#[derive(Clone, Copy, Debug)]
pub struct Bin {
    /// Inclusive lower edge of the probability range.
    pub lo: f64,
    /// Exclusive upper edge (the final bin is closed on the right).
    pub hi: f64,
    /// How many forecasts fell in this bin.
    pub count: usize,
    /// Mean forecast probability among those forecasts.
    pub mean_pred: f64,
    /// Observed frequency of "true" among those forecasts. `NaN` when empty.
    pub observed: f64,
}

/// Bucket forecasts into `n_bins` equal-width bins over `[0, 1]` and report,
/// per bin, the mean predicted probability versus the observed frequency. This
/// is the data behind a reliability diagram: on a perfectly calibrated record
/// every populated bin has `mean_pred == observed`.
pub fn calibration_curve(samples: &[Sample], n_bins: usize) -> Vec<Bin> {
    let n_bins = n_bins.max(1);
    // (count, sum_pred, sum_outcome)
    let mut acc = vec![(0usize, 0.0f64, 0.0f64); n_bins];
    for s in samples {
        let mut idx = (s.prob * n_bins as f64).floor() as isize;
        idx = idx.clamp(0, n_bins as isize - 1); // p == 1.0 lands in the last bin
        let cell = &mut acc[idx as usize];
        cell.0 += 1;
        cell.1 += s.prob;
        cell.2 += s.outcome;
    }
    acc.into_iter()
        .enumerate()
        .map(|(i, (count, sum_pred, sum_out))| {
            let lo = i as f64 / n_bins as f64;
            let hi = (i + 1) as f64 / n_bins as f64;
            let (mean_pred, observed) = if count > 0 {
                (sum_pred / count as f64, sum_out / count as f64)
            } else {
                ((lo + hi) / 2.0, f64::NAN)
            };
            Bin {
                lo,
                hi,
                count,
                mean_pred,
                observed,
            }
        })
        .collect()
}

/// **Discrimination**, as the area under the ROC curve (AUC): the probability
/// that a randomly chosen event that *did* happen was given a higher forecast
/// than a randomly chosen event that did *not*. Ties contribute `0.5`.
///
/// `0.5` is no discriminating skill (you may still be perfectly calibrated!);
/// `1.0` is perfect separation. Returns `None` when every outcome is the same,
/// because AUC is undefined without both a positive and a negative case.
///
/// Calibration and discrimination are genuinely different virtues: a forecaster
/// who always reports the true base rate is perfectly calibrated yet useless
/// (AUC `0.5`). This metric measures the part calibration cannot see.
///
/// Computed in `O(n log n)` via the Wilcoxon–Mann–Whitney rank identity
/// `AUC = (R₊ − n₊(n₊+1)/2) / (n₊·n₋)`, where `R₊` is the sum of the ranks of
/// the positive cases using *average ranks* for ties. (A self-evidently correct
/// `O(n²)` pairwise version lives in the tests and is asserted to agree exactly,
/// ties included.)
pub fn auc(samples: &[Sample]) -> Option<f64> {
    let n_pos = samples.iter().filter(|s| s.outcome >= 0.5).count();
    let n_neg = samples.len() - n_pos;
    if n_pos == 0 || n_neg == 0 {
        return None;
    }

    // Rank by forecast probability, ascending, ranks 1..=N. total_cmp gives a
    // panic-free total order; tie groups (equal prob) share their average rank.
    let mut order: Vec<usize> = (0..samples.len()).collect();
    order.sort_by(|&a, &b| samples[a].prob.total_cmp(&samples[b].prob));
    let mut rank = vec![0.0f64; samples.len()];
    let mut i = 0;
    while i < order.len() {
        let mut j = i;
        while j + 1 < order.len() && samples[order[j + 1]].prob == samples[order[i]].prob {
            j += 1;
        }
        let avg = ((i + 1) + (j + 1)) as f64 / 2.0; // average of ranks (i+1)..=(j+1)
        for k in i..=j {
            rank[order[k]] = avg;
        }
        i = j + 1;
    }

    let r_pos: f64 = samples
        .iter()
        .zip(&rank)
        .filter(|(s, _)| s.outcome >= 0.5)
        .map(|(_, r)| *r)
        .sum();
    let (np, nn) = (n_pos as f64, n_neg as f64);
    Some((r_pos - np * (np + 1.0) / 2.0) / (np * nn))
}

/// The classic over/under-confidence statistic (Lichtenstein–Fischhoff).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Overconfidence {
    /// Mean *boldness*: the average of `max(p, 1 - p)` — how far, on average,
    /// you stood from a coin-flip.
    pub mean_confidence: f64,
    /// Proportion of the side you leaned toward that turned out correct. A
    /// forecast of exactly `0.5` is scored as half-right.
    pub accuracy: f64,
    /// `mean_confidence - accuracy`. Positive ⇒ overconfident (you were bolder
    /// than you were right). Negative ⇒ underconfident.
    pub gap: f64,
}

/// Compute the over/under-confidence gap: mean confidence minus the proportion
/// of leaned-toward sides that came true. This is the headline number behind
/// "most people are overconfident": across decades of studies the gap is
/// reliably positive.
pub fn overconfidence(samples: &[Sample]) -> Option<Overconfidence> {
    if samples.is_empty() {
        return None;
    }
    let n = samples.len() as f64;
    let mut conf = 0.0;
    let mut hits = 0.0;
    for s in samples {
        conf += s.prob.max(1.0 - s.prob);
        let hit = if (s.prob - 0.5).abs() < 1e-12 {
            0.5 // no side chosen; half credit
        } else if s.prob > 0.5 {
            s.outcome // leaned "yes"
        } else {
            1.0 - s.outcome // leaned "no"
        };
        hits += hit;
    }
    Some(Overconfidence {
        mean_confidence: conf / n,
        accuracy: hits / n,
        gap: (conf - hits) / n,
    })
}

/// Calibration-in-the-large: mean forecast minus base rate. A directional bias
/// detector — positive means you systematically said "more likely" than reality
/// delivered, independent of how bold any individual call was.
pub fn directional_bias(samples: &[Sample]) -> Option<f64> {
    Some(
        samples.iter().map(|s| s.prob).sum::<f64>() / samples.len().max(1) as f64
            - base_rate(samples)?,
    )
}

// ───────────────── selection / missingness diagnostics ──────────────────────

/// Mean **boldness** `mean(max(p, 1−p))` of a set of stated probabilities — how far
/// from a 50/50 shrug they sit, computed *without outcomes*. Because it needs no
/// resolution, it can be taken over your still-*open* claims as well as your graded
/// ones, which is what lets the report check whether the calls you actually resolved
/// are a fair sample of the calls you *made*. `None` for an empty slice.
pub fn mean_boldness(probs: &[f64]) -> Option<f64> {
    if probs.is_empty() {
        return None;
    }
    let sum: f64 = probs
        .iter()
        .map(|&p| {
            let p = p.clamp(0.0, 1.0);
            p.max(1.0 - p)
        })
        .sum();
    Some(sum / probs.len() as f64)
}

/// **Absolute standardized mean difference** between two samples — `|mean_a − mean_b|`
/// divided by their pooled standard deviation. The standard covariate-balance /
/// missing-not-at-random diagnostic: a value above `≈ 0.1` means the two groups
/// differ enough on this variable that their split is unlikely to be random. It is
/// an *effect size*, not a hypothesis test, so it does not false-alarm at small `n`
/// the way a t/KS test would. `None` when either group has fewer than two points or
/// there is no spread to standardize against.
pub fn asmd(a: &[f64], b: &[f64]) -> Option<f64> {
    if a.len() < 2 || b.len() < 2 {
        return None;
    }
    let mean = |xs: &[f64]| xs.iter().sum::<f64>() / xs.len() as f64;
    // Sample variance (Bessel's n−1 correction).
    let var = |xs: &[f64], m: f64| {
        xs.iter().map(|x| (x - m).powi(2)).sum::<f64>() / (xs.len() as f64 - 1.0)
    };
    let (ma, mb) = (mean(a), mean(b));
    let pooled_sd = ((var(a, ma) + var(b, mb)) / 2.0).sqrt();
    if pooled_sd < 1e-12 {
        return None; // no spread — standardization undefined
    }
    Some((ma - mb).abs() / pooled_sd)
}

// ───────────────────────── numeric / interval forecasts ─────────────────────

/// A resolved *numeric* forecast: a central credible interval `[low, high]`
/// stated at confidence `level` (e.g. `0.80` for an 80% interval), and the
/// value that actually occurred. This is the quantity-forecasting analogue of
/// [`Sample`].
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct NumericSample {
    pub low: f64,
    pub high: f64,
    /// Nominal coverage in `(0, 1)`.
    pub level: f64,
    pub value: f64,
}

impl NumericSample {
    pub fn width(&self) -> f64 {
        (self.high - self.low).max(0.0)
    }
    pub fn contains(&self) -> bool {
        self.value >= self.low && self.value <= self.high
    }
    /// `α = 1 − level`, clamped away from `0` so the penalty stays finite.
    pub fn alpha(&self) -> f64 {
        (1.0 - self.level).clamp(1e-9, 1.0)
    }
}

/// **Winkler interval score** for one numeric forecast. Lower is better.
///
/// Inside the interval the score is simply its width; outside, the width plus a
/// `2/α` penalty proportional to how far the truth fell beyond the nearer edge.
/// It is a strictly proper scoring rule for central prediction intervals, and it
/// captures the right trade-off: narrow intervals are rewarded, but only if they
/// keep catching the outcome.
pub fn winkler(s: &NumericSample) -> f64 {
    let width = s.high - s.low;
    let two_over_alpha = 2.0 / s.alpha();
    if s.value < s.low {
        width + two_over_alpha * (s.low - s.value)
    } else if s.value > s.high {
        width + two_over_alpha * (s.value - s.high)
    } else {
        width
    }
}

/// The Winkler score expressed as a **multiple of the interval's own width**.
///
/// The raw Winkler score carries the units of the quantity being predicted, so
/// averaging across claims lets the largest-magnitude question dominate the
/// headline: one estimate in milliseconds and one in dollars are added together
/// as if they were the same thing, and "your interval score is 4127" tells the
/// reader nothing except which claim had the biggest numbers.
///
/// Dividing by the width removes the units. `1.0` means the value landed inside
/// the interval; anything above 1 is the miss penalty, in units of your own
/// stated width. `None` for a zero-width interval, where the ratio is undefined.
pub fn winkler_ratio(s: &NumericSample) -> Option<f64> {
    let width = s.high - s.low;
    if width <= 0.0 {
        return None;
    }
    Some(winkler(s) / width)
}

/// Empirical **coverage**: the fraction of intervals that actually contained
/// their outcome. Compared with the nominal level, this is interval calibration:
/// 80% intervals that catch the truth far less than 80% of the time are too
/// narrow — the numeric face of overconfidence.
pub fn coverage(samples: &[NumericSample]) -> Option<f64> {
    if samples.is_empty() {
        return None;
    }
    Some(samples.iter().filter(|s| s.contains()).count() as f64 / samples.len() as f64)
}

/// **Conformal interval recalibration** — the multiplicative correction for your
/// credible intervals, the numeric analogue of [`fit_recalibration`].
///
/// For each forecast the *standardized residual* `r = |value − center| / half_width`
/// is how many half-widths the truth fell from the interval's midpoint; the interval
/// covered exactly when `r ≤ 1`. Scaling every half-width by a factor `m` makes an
/// interval cover iff `r ≤ m`, so the fraction covered after scaling is the fraction
/// of residuals `≤ m`. To hit a target coverage we therefore set `m` to the empirical
/// quantile of the residuals at that target — the split-conformal construction (the
/// `(1−α)`-quantile of the nonconformity scores), distribution-free and valid in
/// finite samples. The target is the mean nominal level across the pool, so `m > 1`
/// means "your intervals are too narrow — multiply their half-widths by `m`" and
/// `m < 1` means they are too wide.
///
/// Pooled and scale-only by design: it assumes a single common width error, which is
/// the honest amount of structure to fit from one agent's handful of intervals.
/// Zero-width intervals carry no scale information and are skipped. Returns `None`
/// with fewer than three usable samples, where the quantile would be meaningless.
pub fn conformal_width_factor(samples: &[NumericSample]) -> Option<f64> {
    let mut residuals: Vec<f64> = Vec::with_capacity(samples.len());
    let mut level_sum = 0.0;
    for s in samples {
        let hw = s.width() / 2.0;
        if hw <= 0.0 {
            continue; // degenerate point interval — no scale information
        }
        let center = (s.low + s.high) / 2.0;
        residuals.push((s.value - center).abs() / hw);
        level_sum += s.level;
    }
    if residuals.len() < 3 {
        return None;
    }
    let target = level_sum / residuals.len() as f64;
    residuals.sort_by(f64::total_cmp);
    Some(quantile_sorted(&residuals, target))
}

// ───────────────────────── small-sample uncertainty ─────────────────────────

/// **Wilson score interval** for a binomial proportion `successes / n`.
///
/// A confidence interval on a rate that, unlike the normal ("Wald") approximation,
/// stays inside `[0, 1]` and keeps sensible coverage at small `n` and extreme
/// proportions — exactly the regime a single agent or session lives in, where the
/// literature warns the central-limit approximation is unsafe. `z` is the
/// standard-normal quantile (≈ `1.96` for 95%). Returns `None` for `n == 0`.
pub fn wilson_interval(successes: f64, n: usize, z: f64) -> Option<(f64, f64)> {
    if n == 0 {
        return None;
    }
    let n = n as f64;
    let p = (successes / n).clamp(0.0, 1.0);
    let z2 = z * z;
    let denom = 1.0 + z2 / n;
    let center = (p + z2 / (2.0 * n)) / denom;
    let margin = (z / denom) * ((p * (1.0 - p) / n) + (z2 / (4.0 * n * n))).sqrt();
    Some(((center - margin).max(0.0), (center + margin).min(1.0)))
}

/// **Empirical-Bayes-style shrinkage** of a rate toward a prior mean.
///
/// `(successes + strength·prior_mean) / (n + strength)` — equivalently a
/// `Beta(strength·prior_mean, strength·(1−prior_mean))` prior updated by the
/// data. At small `n` the estimate is pulled toward `prior_mean` (borrowing
/// strength); as `n` grows it converges to the raw rate. This is what keeps a
/// single fluky resolution from dominating a per-kind calibration number — the
/// literature finds shrinkage beats both raw rates and fixed pseudocounts.
pub fn shrink_toward(successes: f64, n: usize, prior_mean: f64, strength: f64) -> f64 {
    (successes + strength * prior_mean) / (n as f64 + strength)
}

// ─────────────────────── anytime-valid calibration test ─────────────────────

/// Fixed symmetric grid of betting fractions λ used by the mixture e-process.
/// `|λ| < 1` guarantees every factor `1 + λ(y − p)` is non-negative (since
/// `y − p ∈ [−1, 1]`), so each `∏(1 + λ(yᵢ − pᵢ))` is a valid non-negative test
/// martingale; averaging over a symmetric grid gives two-sided power without any
/// data-dependent tuning of λ.
const EPROCESS_LAMBDAS: [f64; 10] = [-0.9, -0.7, -0.5, -0.3, -0.1, 0.1, 0.3, 0.5, 0.7, 0.9];

/// **Anytime-valid calibration e-value** — a betting / test-martingale statistic
/// for the null hypothesis "these forecasts are calibrated."
///
/// Under calibration each outcome behaves like a draw with the stated
/// probability, so `E[yᵢ − pᵢ | past] = 0` and, for each betting fraction λ, the
/// wealth `∏ᵢ (1 + λ(yᵢ − pᵢ))` is a non-negative martingale starting at `1`.
/// This returns the mean wealth over [`EPROCESS_LAMBDAS`], itself a valid
/// e-process. By Ville's inequality the value exceeds `1/α` with probability at
/// most `α` *under the null at any stopping time* — so, unlike a fixed-n test
/// (Spiegelhalter's Z, a t-test), it stays valid even though you peek at it every
/// session. Read it as evidence of *mis*calibration: `≈ 1` is none, `≥ 20` is
/// "significant at α = 0.05", and it grows without bound as miscalibration
/// accumulates. Samples are consumed in the given order, so pass them
/// chronologically (the order outcomes were learned). `None` for an empty record.
pub fn calibration_eprocess(samples: &[Sample]) -> Option<f64> {
    if samples.is_empty() {
        return None;
    }
    let mut wealth = [1.0f64; EPROCESS_LAMBDAS.len()];
    for s in samples {
        let z = s.outcome - s.prob; // mean zero under the calibration null
        for (w, &lam) in wealth.iter_mut().zip(EPROCESS_LAMBDAS.iter()) {
            *w *= 1.0 + lam * z;
        }
    }
    Some(wealth.iter().sum::<f64>() / EPROCESS_LAMBDAS.len() as f64)
}

/// Convert an e-value to an **anytime-valid p-value** via the canonical e→p
/// calibrator `1/e` (capped at `1`). Valid under optional stopping.
pub fn eprocess_pvalue(e: f64) -> f64 {
    (1.0 / e).min(1.0)
}

// ─────────────────────────── recalibration map ──────────────────────────────

fn sigmoid(x: f64) -> f64 {
    if x >= 0.0 {
        1.0 / (1.0 + (-x).exp())
    } else {
        let e = x.exp();
        e / (1.0 + e)
    }
}

fn logit(p: f64) -> f64 {
    (p / (1.0 - p)).ln()
}

/// A learned **recalibration map** `p ↦ σ(a + b·logit p)` — the post-hoc
/// correction that turns your stated probabilities into ones that match your
/// realised frequencies.
///
/// `a` is bias on the log-odds scale (`≠ 0` ⇒ over/under-confident on average);
/// `b` is the slope (`b < 1` ⇒ forecasts too extreme, `b > 1` ⇒ too timid).
/// Perfect calibration is `(a, b) = (0, 1)`, the identity. Apply it with
/// [`Recalibration::apply`].
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Recalibration {
    pub a: f64,
    pub b: f64,
    /// How many resolved samples the fit rests on — i.e. how far to trust it.
    pub n: usize,
}

impl Recalibration {
    /// The identity map — "no correction yet", the small-`n` fallback.
    pub fn identity(n: usize) -> Self {
        Recalibration { a: 0.0, b: 1.0, n }
    }

    /// Correct a single probability through the map.
    pub fn apply(&self, p: f64) -> f64 {
        sigmoid(self.a + self.b * logit(p.clamp(1e-6, 1.0 - 1e-6)))
    }
}

/// Which shape the correction map actually took.
///
/// Surfaced because a collapsed map is indistinguishable from a broken one at the
/// call site: once `b` hits `0`, `decide --prob 0.99` and `decide --prob 0.55`
/// return the same act, and a user who is not told why will file a bug. It is not
/// a bug — it is the fit reporting that the stated numbers carried no information
/// about the outcomes — but it has to say so out loud.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MapKind {
    /// No correction earned yet (or none applied): the stated probability is used
    /// exactly as given.
    Identity,
    /// A fitted `sigma(a + b*logit p)` with `b > 0` — the ordinary case, where
    /// your ranking is kept and only the level is moved.
    Logistic,
    /// The slope collapsed to `b = 0`. Your stated confidence did not track the
    /// outcomes, so every input maps to the same corrected number: your base rate.
    Constant,
}

impl MapKind {
    /// The stable wire name, for `--json` and the MCP tools.
    pub fn as_str(self) -> &'static str {
        match self {
            MapKind::Identity => "identity",
            MapKind::Logistic => "logistic",
            MapKind::Constant => "constant",
        }
    }
}

impl Recalibration {
    /// Which shape this map took — see [`MapKind`].
    pub fn kind(&self) -> MapKind {
        if self.b == 0.0 {
            MapKind::Constant
        } else if self.a == 0.0 && self.b == 1.0 {
            MapKind::Identity
        } else {
            MapKind::Logistic
        }
    }
}

/// Fit a **ridge-regularised logistic recalibration** `σ(a + b·logit p)` by
/// Newton–Raphson, penalising departure from the identity `(0, 1)` with strength
/// `ridge`.
///
/// The penalty is what makes the fit safe at small `n`: with few resolutions the
/// map barely leaves the identity (you have not *earned* a correction yet), and
/// it only develops real bias/slope as evidence accumulates — the same
/// borrow-strength logic as [`shrink_toward`]. The ridge also tames the separable
/// case (every bold call right), where the unpenalised MLE would diverge to
/// infinity. Returns `None` for an empty record.
pub fn fit_recalibration(samples: &[Sample], ridge: f64) -> Option<Recalibration> {
    if samples.is_empty() {
        return None;
    }
    let xs: Vec<f64> = samples
        .iter()
        .map(|s| logit(s.prob.clamp(1e-6, 1.0 - 1e-6)))
        .collect();
    // The penalised objective: NLL + (ridge/2)·[a² + (b−1)²]. Newton is only
    // trusted as far as this actually decreases.
    let objective = |a: f64, b: f64| -> f64 {
        let mut acc = 0.5 * ridge * (a * a + (b - 1.0).powi(2));
        for (x, s) in xs.iter().zip(samples) {
            let z = a + b * x;
            // softplus(z) − y·z, computed so that large |z| cannot overflow.
            let softplus = if z > 0.0 {
                z + (-z).exp().ln_1p()
            } else {
                z.exp().ln_1p()
            };
            acc += softplus - s.outcome * z;
        }
        acc
    };

    let (mut a, mut b) = (0.0f64, 1.0f64);
    let mut converged = false;
    for _ in 0..100 {
        // Gradient g and Hessian H of the objective above.
        let (mut ga, mut gb) = (ridge * a, ridge * (b - 1.0));
        let (mut haa, mut hab, mut hbb) = (ridge, 0.0, ridge);
        for (x, s) in xs.iter().zip(samples) {
            let mu = sigmoid(a + b * x);
            let w = mu * (1.0 - mu);
            let r = mu - s.outcome;
            ga += r;
            gb += r * x;
            haa += w;
            hab += w * x;
            hbb += w * x * x;
        }
        // At the b = 0 boundary, a positive gb means the objective wants to push
        // b further negative; the constraint holds it, and that is optimal.
        let gb_free = if b <= 0.0 && gb > 0.0 { 0.0 } else { gb };
        if ga.abs() < 1e-10 && gb_free.abs() < 1e-10 {
            converged = true;
            break;
        }
        let det = haa * hbb - hab * hab;
        if !(det.is_finite() && det > 1e-12) {
            break;
        }
        let da = (hbb * ga - hab * gb) / det;
        let db = (haa * gb - hab * ga) / det;

        // Backtracking line search. The undamped Newton step this used to take
        // DIVERGES whenever the fit wanders into the saturated region: there
        // every mu is ~0 or ~1, so the Hessian weights w = mu(1−mu) vanish while
        // the gradient does not, and the step overshoots further each time.
        //
        // Measured on 200 calls all stated at 0.9 that came true half the time —
        // an agent with a narrow confidence vocabulary, which the report's own
        // "confidence vocab" line exists to notice — it returned a = 66, b = 146,
        // a map that corrects 0.9 UP to 1.0 for a forecaster who is right half
        // the time. Exactly the direction of error this tool exists to catch.
        let f0 = objective(a, b);
        let mut step = 1.0;
        let mut moved = false;
        for _ in 0..40 {
            // Projected Newton: the slope is constrained to b >= 0, because a
            // recalibration map must be non-decreasing. Higher stated confidence
            // mapping to a LOWER corrected probability is not a correction, it is
            // an inversion, and handing one to `decide` would be worse than
            // handing it nothing.
            //
            // An unconstrained fit reaches b < 0 whenever the observed
            // frequencies do not rise with the forecast — which at small n is
            // usually noise. Measured on a 15-claim fixture where twelve 0.9s
            // failed and a lone 0.6 came true, it converged to b = -0.69.
            // Pinning b at 0 there collapses the map to a constant, which is
            // exactly what the isotonic fit does with the same data when
            // pool-adjacent-violators merges the whole range into one block.
            let (na, nb) = (a - step * da, (b - step * db).max(0.0));
            if na.is_finite() && nb.is_finite() && objective(na, nb) <= f0 {
                if (na - a).abs() < 1e-15 && (nb - b).abs() < 1e-15 {
                    break; // the projection pinned us; no progress available
                }
                a = na;
                b = nb;
                moved = true;
                break;
            }
            step *= 0.5;
        }
        if !moved {
            // No downhill step of any size: we are at the optimum to numerical
            // precision, or the problem is degenerate.
            converged = true;
            break;
        }
        if (step * da).abs() < 1e-10 && (step * db).abs() < 1e-10 {
            converged = true;
            break;
        }
    }

    // Refuse to hand back a correction the solver did not actually find. The
    // identity map says "no correction", which is the honest answer when the fit
    // will not settle — never a confidently wrong one.
    let candidate = Recalibration {
        a,
        b,
        n: samples.len(),
    };
    if converged && a.is_finite() && b.is_finite() && recalibration_is_sane(&candidate, samples) {
        Some(candidate)
    } else {
        Some(Recalibration::identity(samples.len()))
    }
}

/// Three cheap invariants a usable recalibration map must satisfy.
///
/// This is belt-and-braces on top of the line search, and it is here because of
/// how this function failed: a diverged fit does not error, it returns a
/// confident number pointing the wrong way, and the evidence gate had already
/// decided to trust it. Every other defect in this program fails passively; this
/// one pushed a 50%-accurate forecaster's stated 0.9 up to 1.0.
///
/// 1. The map must send `[0,1]` into `[0,1]` — free, given it is a sigmoid, but
///    it also catches a non-finite `a` or `b` slipping through.
/// 2. It must be **monotone non-decreasing**: correcting a higher stated
///    probability to a lower corrected one is never a calibration correction.
/// 3. It must agree in direction with the **isotonic (PAV) fit** that [`corp_brier`]
///    already computes. PAV cannot diverge by construction — it is the
///    least-squares monotone fit, not an iterative solve — so it is a free oracle
///    for what the correction ought to look like. If the parametric map says
///    "raise this" where the isotonic curve says "lower it", the parametric one
///    is wrong.
fn recalibration_is_sane(r: &Recalibration, samples: &[Sample]) -> bool {
    // 1 + 2: sample the map across the unit interval.
    let grid: [f64; 11] = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0];
    let mut prev = f64::NEG_INFINITY;
    for p in grid {
        let q = r.apply(p);
        if !q.is_finite() || !(0.0..=1.0).contains(&q) {
            return false;
        }
        if q + 1e-9 < prev {
            return false; // non-monotone
        }
        prev = q;
    }

    // 3: cross-check the direction against the isotonic fit on the same data.
    let Some(corp) = corp_brier(samples) else {
        return true;
    };
    let (mut checked, mut disagreements) = (0usize, 0usize);
    for (s, &iso) in samples.iter().zip(corp.recalibrated.iter()) {
        let parametric = r.apply(s.prob) - s.prob;
        let isotonic = iso - s.prob;
        // Only meaningful where both say something worth saying.
        if parametric.abs() < 0.02 || isotonic.abs() < 0.02 {
            continue;
        }
        checked += 1;
        if parametric.signum() != isotonic.signum() {
            disagreements += 1;
        }
    }
    // The isotonic fit is noisy at small n, so a handful of local disagreements
    // are expected; a majority of them means the parametric fit points the wrong
    // way overall, which is the failure being guarded against.
    checked == 0 || (disagreements * 2) <= checked
}

// ─────────────────────────── decision gate ──────────────────────────────────

/// What to do with a stated probability once the stakes are taken into account —
/// the *operational* end of calibration, where a number becomes an action.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Act {
    /// Corrected confidence clears the bar for the stakes — commit.
    Proceed,
    /// In the doubt zone — gather more evidence before you commit.
    Verify,
    /// More likely to fail than succeed *after correction* — replan or escalate
    /// rather than spend a verification cycle on a probable dead end.
    Abstain,
}

/// A recommendation for one prospective action: what to do, the corrected
/// probability it rests on, and how much room there was in the call.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Decision {
    pub act: Act,
    /// The probability the decision actually used: your stated `p` after the
    /// track-record correction (or the raw `p` when no correction was earned).
    pub adjusted_p: f64,
    /// Chow's break-even confidence to proceed without verifying,
    /// `1 − verify_cost/stake`. Rises toward `1` as the stakes grow.
    pub proceed_threshold: f64,
    /// `adjusted_p − proceed_threshold`; `≥ 0` ⇒ proceed. The room you had.
    pub margin: f64,
    /// Which correction was applied to get from the stated `p` to `adjusted_p`.
    /// [`MapKind::Constant`] is the one worth reading aloud: the act no longer
    /// depends on the number you passed in.
    pub map_kind: MapKind,
}

/// Within Chow's reject region, the boundary between *verify* and *abstain*: below
/// an even-odds corrected probability the action is more likely to fail than
/// succeed, so replanning beats verifying. Parameter-free by design.
const ABSTAIN_BELOW: f64 = 0.5;

/// **Decision gate** — turn a stated probability into an action under stakes.
///
/// This is the step the calibration literature finds agents skip: they can *state*
/// their uncertainty yet still barrel into an irreversible action. The gate closes
/// that loop in two principled moves:
///
/// 1. **Correct the number.** Verbalized confidence is the least reliable signal, so
///    the stated `p` is first pushed through the learned [`Recalibration`] map (pass
///    `Some` only once the e-process has *earned* it; `None` leaves `p` untouched) —
///    your best estimate of the true success probability given your track record.
/// 2. **Threshold by the stakes.** By Chow's optimal reject rule, proceeding is worth
///    it only when the expected cost of a wrong action, `(1 − p̂)·stake`, is below the
///    cost of a verification step — i.e. when `p̂ ≥ 1 − verify_cost/stake`. The
///    threshold climbs toward `1` as `stake` grows: the more irreversible the action,
///    the closer to certain you must be to skip the check. Below the threshold the
///    gate says *verify*, unless the corrected odds are worse than even, where it says
///    *abstain* (replan) instead.
///
/// `stake` is the cost of a wrong proceed relative to one verification (`1.0` =
/// ordinary; raise it for consequential or irreversible calls). `verify_cost` is the
/// cost of that check in the same unit. Pure: no I/O, no ledger — the caller supplies
/// the (evidence-gated) map.
pub fn decide(p: f64, recal: Option<Recalibration>, stake: f64, verify_cost: f64) -> Decision {
    let p = p.clamp(0.0, 1.0);
    let (adjusted_p, map_kind) = match recal {
        Some(r) => (r.apply(p), r.kind()),
        None => (p, MapKind::Identity),
    };
    let stake = stake.max(0.0);
    // Chow's reject threshold for a one-sided act/verify decision. With nothing at
    // stake there is nothing to verify against, so proceed.
    let proceed_threshold = if stake > 0.0 {
        (1.0 - verify_cost.max(0.0) / stake).clamp(0.0, 1.0)
    } else {
        0.0
    };
    let margin = adjusted_p - proceed_threshold;
    let act = if adjusted_p >= proceed_threshold {
        Act::Proceed
    } else if adjusted_p >= ABSTAIN_BELOW {
        Act::Verify
    } else {
        Act::Abstain
    };
    Decision {
        act,
        adjusted_p,
        proceed_threshold,
        margin,
        map_kind,
    }
}

// ───────────────────────── small-sample / over-time bands ───────────────────

/// A tiny, dependency-free SplitMix64 PRNG — enough for a reproducible bootstrap.
fn splitmix64(state: &mut u64) -> u64 {
    *state = state.wrapping_add(0x9E37_79B9_7F4A_7C15);
    let mut z = *state;
    z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
    z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
    z ^ (z >> 31)
}

/// Linear-interpolated quantile of an already-sorted slice.
fn quantile_sorted(sorted: &[f64], q: f64) -> f64 {
    let q = q.clamp(0.0, 1.0);
    let pos = q * (sorted.len() as f64 - 1.0);
    let lo = pos.floor() as usize;
    let hi = pos.ceil() as usize;
    let frac = pos - lo as f64;
    sorted[lo] * (1.0 - frac) + sorted[hi] * frac
}

/// **Bootstrap percentile interval** for the Brier score — an intuitive band on
/// "how far luck alone could move this number." Deterministic given `seed`, so the
/// report is reproducible run-to-run. `level` is the two-sided coverage (e.g.
/// `0.95`); `resamples` ≥ ~2000 is sensible. Returns `None` for fewer than two
/// samples (a one-sample band is meaningless).
///
/// Note: the percentile interval skews a touch *narrow* at very small `n`, so
/// treat it as a rough band — the rigorous, optional-stopping-valid calibration
/// call is [`calibration_eprocess`], not this.
pub fn brier_ci_bootstrap(
    samples: &[Sample],
    level: f64,
    resamples: usize,
    seed: u64,
) -> Option<(f64, f64)> {
    let n = samples.len();
    if n < 2 || resamples == 0 {
        return None;
    }
    let mut state = seed;
    let mut briers = Vec::with_capacity(resamples);
    for _ in 0..resamples {
        let mut sum = 0.0;
        for _ in 0..n {
            let idx = (splitmix64(&mut state) % n as u64) as usize;
            let s = &samples[idx];
            sum += (s.prob - s.outcome).powi(2);
        }
        briers.push(sum / n as f64);
    }
    briers.sort_by(f64::total_cmp);
    let alpha = (1.0 - level) / 2.0;
    Some((
        quantile_sorted(&briers, alpha),
        quantile_sorted(&briers, 1.0 - alpha),
    ))
}

/// **Recency-weighted (EWMA) Brier** over the samples in the given order, with the
/// given `half_life` in samples (the lag at which a forecast's weight halves).
/// Pass samples chronologically: this is the "how am I doing *lately*" number, to
/// be read against the lifetime Brier as a trend. `None` for an empty record.
///
/// Deliberately *not* a control-chart drift alarm: at the few-dozen-sample scale
/// an agent lives in, hard EWMA/CUSUM limits false-alarm. This is a descriptive
/// trend, not a significance test.
pub fn ewma_brier(samples: &[Sample], half_life: f64) -> Option<f64> {
    let first = samples.first()?;
    let lambda = 1.0 - 0.5_f64.powf(1.0 / half_life.max(1e-9));
    let mut ewma = (first.prob - first.outcome).powi(2);
    for s in &samples[1..] {
        let b = (s.prob - s.outcome).powi(2);
        ewma = lambda * b + (1.0 - lambda) * ewma;
    }
    Some(ewma)
}

/// How many **distinct forecast probabilities** appear. A coarse confidence
/// vocabulary (you only ever say 0.5/0.7/0.9) caps the resolution you can
/// achieve — the LLM-calibration literature finds verbalized confidence clusters
/// on a few round numbers. Grouped by exact bit pattern.
pub fn distinct_forecasts(samples: &[Sample]) -> usize {
    samples
        .iter()
        .map(|s| s.prob.to_bits())
        .collect::<std::collections::BTreeSet<_>>()
        .len()
}

// ───────────────────────── selective prediction ─────────────────────────────

/// The 0/1 *directional* error of one forecast: you lean "yes" when `p > 0.5`
/// and "no" when `p < 0.5`; the call is wrong when the leaned side did not happen.
/// An exact `0.5` picks no side and scores half-error.
fn directional_error(s: &Sample) -> f64 {
    if (s.prob - 0.5).abs() < 1e-12 {
        0.5
    } else if s.prob > 0.5 {
        1.0 - s.outcome // leaned yes → wrong if it did not happen
    } else {
        s.outcome // leaned no → wrong if it happened
    }
}

/// A risk–coverage curve: how your error rate falls as you abstain from your
/// least-confident calls.
#[derive(Clone, Debug)]
pub struct RiskCoverage {
    /// `(coverage, risk)` points, coverage ascending from `1/n` (act only on the
    /// single most-confident call) to `1.0` (act on everything).
    pub points: Vec<(f64, f64)>,
    /// Area under the risk–coverage curve (mean risk across coverage levels).
    /// **Lower is better**: your confident calls really are your reliable ones.
    pub aurcc: f64,
    /// Error rate at full coverage — acting on every call.
    pub risk_at_full: f64,
}

impl RiskCoverage {
    /// Risk (error rate) when acting only on the most-confident `target` fraction
    /// of calls — the smallest coverage point `≥ target`.
    pub fn risk_at(&self, target: f64) -> f64 {
        self.points
            .iter()
            .find(|(c, _)| *c >= target)
            .or_else(|| self.points.last())
            .map(|(_, r)| *r)
            .unwrap_or(0.0)
    }
}

/// **Selective prediction**: rank forecasts by *boldness* (`max(p, 1-p)`) and, for
/// each coverage level, report the directional error among the calls you would
/// keep. This answers "how good am I when I only commit to my surest calls?" — the
/// agent's version of knowing *when to act on its own judgement versus flag
/// uncertainty*. On a forecaster whose confidence means something, risk falls as
/// coverage shrinks; if it does not (or rises), the confidence ranking is noise.
/// Returns `None` for an empty record.
pub fn risk_coverage(samples: &[Sample]) -> Option<RiskCoverage> {
    if samples.is_empty() {
        return None;
    }
    let n = samples.len();
    let mut order: Vec<usize> = (0..n).collect();
    // Most confident first; total_cmp keeps it panic-free and ties stable-ish.
    order.sort_by(|&a, &b| {
        let ca = samples[a].prob.max(1.0 - samples[a].prob);
        let cb = samples[b].prob.max(1.0 - samples[b].prob);
        cb.total_cmp(&ca)
    });
    let mut points = Vec::with_capacity(n);
    let mut cum_err = 0.0;
    for (k, &i) in order.iter().enumerate() {
        cum_err += directional_error(&samples[i]);
        let coverage = (k + 1) as f64 / n as f64;
        points.push((coverage, cum_err / (k + 1) as f64));
    }
    let risk_at_full = points.last().map(|&(_, r)| r).unwrap_or(0.0);
    let aurcc = points.iter().map(|&(_, r)| r).sum::<f64>() / n as f64;
    Some(RiskCoverage {
        points,
        aurcc,
        risk_at_full,
    })
}

// ───────────────────────── elicitation aids ─────────────────────────────────

/// **Dialectical aggregation** of two of your own estimates — Herzog & Hertwig's
/// "crowd within" (2009). Make a first estimate, then a second that deliberately
/// assumes the first is wrong ("consider the opposite — give two reasons it might
/// be off"), and average them: the arithmetic mean recovers roughly half the
/// accuracy gain of consulting a *second person*. This is a pre-resolution input
/// aid, not a score; the inputs are clamped to `[0, 1]`.
pub fn dialectical_mean(p1: f64, p2: f64) -> f64 {
    (p1.clamp(0.0, 1.0) + p2.clamp(0.0, 1.0)) / 2.0
}

// ───────────────────────── CORP decomposition (P0-4) ────────────────────────

/// The **CORP** decomposition of the Brier score (Dimitriadis, Gneiting & Jordan,
/// PNAS 2021): *Consistent, Optimally binned, Reproducible, Pool-adjacent-violators*.
///
/// [`decompose`] groups forecasts by their exact value, which is what makes its
/// identity exact — but at an agent's sample sizes most exact-value groups hold
/// one or two claims, and a group of one always has observed frequency 0 or 1,
/// so its "calibration error" is the largest it could possibly be. Simulating a
/// *perfectly calibrated* forecaster using two-decimal probabilities, where the
/// true calibration error is zero:
///
/// | n | exact-value reliability | CORP MCB |
/// |---|---|---|
/// | 50 | 0.138 | 0.034 |
/// | 200 | 0.073 | 0.014 |
///
/// The shipped number told a well-calibrated user they had a calibration problem.
///
/// CORP replaces binning with isotonic regression (pool-adjacent-violators): the
/// best *non-decreasing* recalibration of the forecasts. Then
///
/// - `MCB` (miscalibration) `= S(forecast) − S(recalibrated)`
/// - `DSC` (discrimination) `= S(base rate) − S(recalibrated)`
/// - `UNC` (uncertainty) `= S(base rate)`
///
/// and `S = MCB − DSC + UNC` still holds exactly, with no bins and no tuning
/// parameter — the "exact decomposition" property survives intact. There is no
/// free lunch: MCB is optimistically biased because the isotonic fit is chosen on
/// the same data, which is exactly why [`mcb_null_quantile`] exists to say how
/// large it would be for someone with no calibration error at all.
#[derive(Clone, Debug, PartialEq)]
pub struct Corp {
    /// Miscalibration: how much score you would save by relabelling your
    /// probabilities with the frequencies that actually followed them.
    pub mcb: f64,
    /// Discrimination: how much your (recalibrated) forecasts beat the base
    /// rate. `0` means your confidence carries no information about which of
    /// your calls come true.
    pub dsc: f64,
    /// Uncertainty: the irreducible difficulty of the questions you chose.
    pub unc: f64,
    /// The Brier score of the forecasts as stated.
    pub score: f64,
    /// The PAV-recalibrated probability for each sample, in input order — the
    /// reliability curve, with no bin-width choice to argue about.
    pub recalibrated: Vec<f64>,
}

/// Compute the [`Corp`] decomposition. `None` for an empty sample.
pub fn corp_brier(samples: &[Sample]) -> Option<Corp> {
    let n = samples.len();
    if n == 0 {
        return None;
    }
    // 1) Sort by forecast, pooling exact ties into groups of (prob, Σy, count).
    let mut idx: Vec<usize> = (0..n).collect();
    idx.sort_by(|&a, &b| samples[a].prob.total_cmp(&samples[b].prob));
    let mut groups: Vec<(f64, f64, usize)> = Vec::new();
    for &i in &idx {
        let s = &samples[i];
        match groups.last_mut() {
            Some(g) if g.0 == s.prob => {
                g.1 += s.outcome;
                g.2 += 1;
            }
            _ => groups.push((s.prob, s.outcome, 1)),
        }
    }
    // 2) Pool adjacent violators. Blocks carry (Σy, Σcount, #groups merged).
    let mut blocks: Vec<(f64, usize, usize)> = Vec::with_capacity(groups.len());
    for &(_, sy, c) in &groups {
        blocks.push((sy, c, 1));
        while blocks.len() > 1 {
            let (s2, c2, g2) = blocks[blocks.len() - 1];
            let (s1, c1, _) = blocks[blocks.len() - 2];
            if s1 / c1 as f64 > s2 / c2 as f64 {
                blocks.pop();
                let last = blocks.last_mut().unwrap();
                last.0 += s2;
                last.1 += c2;
                last.2 += g2;
            } else {
                break;
            }
        }
    }
    // 3) Expand the fitted values back into the original sample order.
    let mut group_fit = Vec::with_capacity(groups.len());
    for &(sy, c, g) in &blocks {
        group_fit.extend(std::iter::repeat_n(sy / c as f64, g));
    }
    let mut recalibrated = vec![0.0; n];
    let mut k = 0usize;
    for (gi, &(_, _, c)) in groups.iter().enumerate() {
        for _ in 0..c {
            recalibrated[idx[k]] = group_fit[gi];
            k += 1;
        }
    }
    // 4) The three terms, each a Brier score against the same outcomes.
    let ybar = samples.iter().map(|s| s.outcome).sum::<f64>() / n as f64;
    let (mut score, mut s_cal, mut unc) = (0.0, 0.0, 0.0);
    for (i, s) in samples.iter().enumerate() {
        score += (s.prob - s.outcome).powi(2);
        s_cal += (recalibrated[i] - s.outcome).powi(2);
        unc += (ybar - s.outcome).powi(2);
    }
    let nf = n as f64;
    let (score, s_cal, unc) = (score / nf, s_cal / nf, unc / nf);
    Some(Corp {
        mcb: score - s_cal,
        dsc: unc - s_cal,
        unc,
        score,
        recalibrated,
    })
}

/// The **noise floor** for [`Corp::mcb`]: the `q`-quantile of the miscalibration
/// a *perfectly calibrated* forecaster would score while making exactly these
/// calls, at exactly this sample size.
///
/// This is the number that turns "your calibration error is 0.034" from a verdict
/// into evidence. MCB is fitted on the same data it scores, so it is never zero,
/// and how far above zero it sits depends on n and on the spread of the
/// forecasts — quantities the user cannot hold in their head. Drawing
/// `y ~ Bernoulli(p)` from the user's own forecasts and re-running CORP answers
/// it directly.
///
/// Deterministic: the same samples and seed always give the same floor, so a
/// report never changes underneath a user who re-runs it. `None` below two
/// samples.
pub fn mcb_null_quantile(samples: &[Sample], draws: usize, q: f64, seed: u64) -> Option<f64> {
    if samples.len() < 2 || draws == 0 {
        return None;
    }
    let mut state = seed;
    let mut sim: Vec<Sample> = samples.to_vec();
    let mut mcbs = Vec::with_capacity(draws);
    for _ in 0..draws {
        for (t, s) in sim.iter_mut().zip(samples) {
            let u = (splitmix64(&mut state) >> 11) as f64 / (1u64 << 53) as f64;
            t.outcome = if u < s.prob { 1.0 } else { 0.0 };
        }
        mcbs.push(corp_brier(&sim)?.mcb);
    }
    mcbs.sort_by(f64::total_cmp);
    Some(quantile_sorted(&mcbs, q))
}

// ──────────────────── multi-strategy e-process (P0-3a) ──────────────────────

/// Bets on the overall sign of `y − p`: the original single strategy. Detects a
/// forecaster who is too high (or too low) *on the whole*.
fn bet_bias(_p: f64) -> f64 {
    1.0
}

/// Bets on the *extremity* of the forecast rather than its direction: it flips
/// sign at `p = 0.5`, so being too sure when saying 0.9 and too sure when saying
/// 0.1 push the wealth the same way instead of cancelling.
fn bet_extremity(p: f64) -> f64 {
    if p < 0.5 {
        1.0
    } else if p > 0.5 {
        -1.0
    } else {
        0.0
    }
}

/// The same idea weighted by how extreme the forecast is, so a 0.99 counts for
/// more than a 0.51.
fn bet_extremity_scaled(p: f64) -> f64 {
    2.0 * (0.5 - p)
}

/// The betting strategies `h(p)`, each bounded by `1` in absolute value and each
/// a function of the **stated forecast only**.
///
/// That restriction is what keeps the guarantee: `p` is fixed before the outcome
/// is seen, so `E[h(p)(y − p) | past] = 0` under the calibration null and every
/// wealth process remains a non-negative martingale. Averaging e-processes
/// computed on the same data sequence is again an e-process, so mixing over
/// strategies costs validity nothing and buys power against patterns a single
/// strategy cannot see.
const STRATEGIES: [fn(f64) -> f64; 3] = [bet_bias, bet_extremity, bet_extremity_scaled];

/// Natural log of the mixture e-process over [`STRATEGIES`] × [`EPROCESS_LAMBDAS`].
///
/// Computed in log space because real miscalibration produces e-values with
/// dozens of digits, which overflow `f64` long before they stop being
/// meaningful. Every factor is at least `0.1`, so the logs stay finite.
///
/// This supersedes [`calibration_eprocess`], which bets only on the overall sign
/// of `y − p` and is therefore **blind to symmetric overconfidence**: a
/// forecaster who says 90% when the truth is 65% *and* says 10% when the truth is
/// 35% has errors that cancel exactly. Measured on such a ledger at n = 1000, the
/// single-strategy version returns 0.087 — no evidence at all — where this one
/// returns a number with 65 digits. That case is not exotic; it is what an agent
/// looks like the moment it starts logging "this will fail" at 0.15 alongside
/// "this will pass" at 0.85.
pub fn calibration_log_eprocess(samples: &[Sample]) -> Option<f64> {
    let steps: Vec<Step> = samples
        .iter()
        .map(|s| Step::graded(s.prob, s.outcome))
        .collect();
    calibration_log_eprocess_seq(&steps)
}

/// One step of the evidence sequence: what you said, and what happened — or
/// `None` when the claim is due but still ungraded.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Step {
    /// The stated probability, fixed before the outcome.
    pub prob: f64,
    /// `1.0`/`0.0` once graded; `None` while the claim is an open gap.
    pub outcome: Option<f64>,
}

impl Step {
    pub fn graded(prob: f64, outcome: f64) -> Self {
        Step {
            prob,
            outcome: Some(outcome),
        }
    }
    /// A due-but-ungraded claim — a gap in the record.
    pub fn gap(prob: f64) -> Self {
        Step {
            prob,
            outcome: None,
        }
    }
}

/// The mixture e-process over a sequence that may contain **gaps**.
///
/// A graded step contributes its ordinary factor `1 + λ·h(p)·(y − p)`. An
/// ungraded step contributes the smallest factor it could possibly have
/// contributed,
///
/// ```text
/// min over y in {0,1} of  1 + λ·h(p)·(y − p)
/// ```
///
/// taken **per mixture component**, since each `(strategy, λ)` pair is its own
/// wealth process.
///
/// # Why this is valid
///
/// The two candidate factors are `1 + λh(1−p)` (had it resolved YES) and
/// `1 − λhp` (had it resolved NO). Under the calibration null the outcome is YES
/// with probability exactly `p`, so their `p`-weighted average is
///
/// ```text
/// p(1 + λh(1−p)) + (1−p)(1 − λhp) = 1
/// ```
///
/// identically. A weighted average of two numbers is at least their minimum, so
/// **the min is ≤ 1**, and it is also ≤ the true factor whichever outcome the
/// claim would have had. The gap-filled wealth is therefore pointwise ≤ the
/// fully-graded martingale at every `n`, and is itself a non-negative
/// supermartingale starting at `1`. Ville's inequality covers supermartingales,
/// so the bound `P(∃k : M_k ≥ 1/α) ≤ α` carries over unchanged — and across
/// repeated views, whatever is ungraded at view time `t` still satisfies
/// `W'(t) ≤ M_n` for one fixed process `M`. The argument in `crate::evidence`
/// keeps its shape; this extends it by one sentence.
///
/// # Why it replaced stopping at the first gap
///
/// Stopping is the wrong response to gaps. Any prefix rule yields about
/// `(1−g)/g` claims for an ungraded rate `g`, so at 35% ungraded the sequence is
/// ~2 claims long no matter how much you have logged — and partitioning does not
/// rescue it, because K partitions give K short sequences and a K-fold mixture
/// penalty that cancels the gain. Measured at n = 300, alarm `e ≥ 20`, peeking
/// every 5:
///
/// | graded | rule | usable n | P(detect) | P(false alarm) |
/// |---|---|---|---|---|
/// | 100% | either | 300 | 1.000 | 0.013 |
/// | 90% | stop at gap | 10.1 | 0.047 | 0.000 |
/// | 90% | gap-filled | 270.1 | 1.000 | 0.000 |
/// | 65% | stop at gap | 2.0 | 0.000 | 0.000 |
/// | 65% | gap-filled | 194.7 | 1.000 | 0.000 |
///
/// False alarms cannot rise, because wealth only ever shrinks relative to the
/// graded process. The cost is real, though, and it is not free power: against a
/// *diffuse* alternative (per-claim discrepancy ≤ 0.135 rather than 0.25),
/// detection falls from 0.587 at full grading to 0.003 at 65%. Gaps are priced,
/// not forgiven.
///
/// Two properties worth keeping: with `|λ| ≤ 0.9` every factor is at least `0.1`,
/// so a gap costs wealth rather than zeroing the process; and the cost scales
/// with how bold the ungraded claim was — an ungraded `0.95` costs more than an
/// ungraded `0.55`, which is the right incentive.
///
/// An undisciplined user's e-value therefore drifts down, so gaps can *hide*
/// miscalibration. They could already do that by freezing the test under the old
/// stopping rule, and neither direction can manufacture a false alarm.
pub fn calibration_log_eprocess_seq(steps: &[Step]) -> Option<f64> {
    if steps.is_empty() {
        return None;
    }
    let mut logw = [[0.0f64; EPROCESS_LAMBDAS.len()]; STRATEGIES.len()];
    for st in steps {
        for (k, h) in STRATEGIES.iter().enumerate() {
            let hp = h(st.prob);
            for (lw, &lam) in logw[k].iter_mut().zip(EPROCESS_LAMBDAS.iter()) {
                *lw += match st.outcome {
                    // mean zero under the calibration null
                    Some(y) => (lam * hp * (y - st.prob)).ln_1p(),
                    None => {
                        let yes = 1.0 + lam * hp * (1.0 - st.prob);
                        let no = 1.0 + lam * hp * (0.0 - st.prob);
                        yes.min(no).ln()
                    }
                };
            }
        }
    }
    // log-sum-exp, then divide by the number of mixture components.
    let all: Vec<f64> = logw.iter().flatten().copied().collect();
    let max = all.iter().copied().fold(f64::NEG_INFINITY, f64::max);
    let lse = max + all.iter().map(|v| (v - max).exp()).sum::<f64>().ln();
    Some(lse - (all.len() as f64).ln())
}

/// [`calibration_log_eprocess_seq`] on the natural scale, capped like
/// [`calibration_eprocess_v2`].
pub fn calibration_eprocess_seq(steps: &[Step]) -> Option<f64> {
    calibration_log_eprocess_seq(steps).map(|l| l.min(EPROCESS_LOG_CAP).exp())
}

/// The evidence bar a recalibration map must clear before it is applied, and the
/// minimum record it must be fitted on.
///
/// These live here, in the pure core, rather than in the reporting layer, because
/// the CLI, the MCP tools, the report and the Python binding must all agree about
/// when a correction has been earned — and "defined once" is only true if there is
/// literally one definition.
pub const RECAL_MIN_E: f64 = 3.0;
pub const RECAL_MIN_N: usize = 6;

/// Fit a recalibration map and decide whether the evidence has **earned** it.
///
/// `fit_on` is every graded call (more data makes a better correction);
/// `evidence` is the outcome-independent sequence the e-process may consume (see
/// `crate::evidence`). Separating them matters: the map is a description, and may
/// use everything; the gate is a test, and may only use a sequence whose order
/// was fixed before the outcomes were known.
///
/// Returns the fitted map, whether to apply it, and the e-value behind that call.
/// The map is returned either way — `earned` is the part that says to trust it.
pub fn gate_recalibration(
    fit_on: &[Sample],
    evidence: &[Sample],
    ridge: f64,
) -> (Option<Recalibration>, bool, Option<f64>) {
    let steps: Vec<Step> = evidence
        .iter()
        .map(|s| Step::graded(s.prob, s.outcome))
        .collect();
    gate_recalibration_seq(fit_on, &steps, ridge)
}

/// [`gate_recalibration`] over a sequence that may contain gaps.
///
/// The minimum-`n` bar counts **graded** steps only: a gap carries no outcome, so
/// it is evidence about discipline, never about calibration, and must not buy a
/// correction the record has not earned.
pub fn gate_recalibration_seq(
    fit_on: &[Sample],
    evidence: &[Step],
    ridge: f64,
) -> (Option<Recalibration>, bool, Option<f64>) {
    let e = calibration_eprocess_seq(evidence);
    let recal = fit_recalibration(fit_on, ridge);
    let graded = evidence.iter().filter(|s| s.outcome.is_some()).count();
    let earned = recal.is_some() && e.is_some_and(|ev| ev >= RECAL_MIN_E) && graded >= RECAL_MIN_N;
    (recal, earned, e)
}

/// The largest log e-value worth printing. Above this the exact figure is
/// meaningless — it already says "certain" far more emphatically than any
/// decision needs — and `exp` would produce `inf`, which serialises to `null`.
pub const EPROCESS_LOG_CAP: f64 = 27.63; // ≈ ln(10^12)

/// **Sensitivity of the calibration test at this record**: of `sims` simulated forecasters
/// who made exactly these forecasts, in this order and with these gaps, but whose true
/// chance on each call was `0.5 + (1 − shrink)·(p − 0.5)`, the share the e-process flags
/// (final e-value at or above `alarm`). `shrink = 0.3` is a forecaster whose numbers are
/// 30% too far from 50/50.
///
/// A quiet test reads as a clean bill of health unless it says how loud a real error would
/// have been. Measured on the 0.4.2 binary by an outside review: 60 calls 30% too extreme
/// were caught in 0 of 40 runs. This is that measurement, on the reader's own forecasts.
/// Reproducible: the same `seed` gives the same rate. `None` when no step is graded or
/// `sims` is zero.
pub fn detection_rate(
    steps: &[Step],
    shrink: f64,
    alarm: f64,
    sims: usize,
    seed: u64,
) -> Option<f64> {
    if sims == 0 || !steps.iter().any(|s| s.outcome.is_some()) {
        return None;
    }
    let log_alarm = alarm.ln();
    let mut state = seed;
    let mut sim = steps.to_vec();
    let mut hits = 0usize;
    for _ in 0..sims {
        for (st, orig) in sim.iter_mut().zip(steps) {
            if orig.outcome.is_some() {
                let truth = (0.5 + (1.0 - shrink) * (orig.prob - 0.5)).clamp(0.0, 1.0);
                let u = (splitmix64(&mut state) >> 11) as f64 / (1u64 << 53) as f64;
                st.outcome = Some(if u < truth { 1.0 } else { 0.0 });
            }
        }
        if calibration_log_eprocess_seq(&sim).is_some_and(|l| l >= log_alarm) {
            hits += 1;
        }
    }
    Some(hits as f64 / sims as f64)
}

/// The mixture e-value on the natural scale, capped at `10^12` so the report
/// never has to print a 66-digit integer or the word `inf`.
///
/// Use [`calibration_log_eprocess`] when comparing magnitudes; use this when a
/// number has to be shown or compared against a threshold like 20.
pub fn calibration_eprocess_v2(samples: &[Sample]) -> Option<f64> {
    calibration_log_eprocess(samples).map(|l| l.min(EPROCESS_LOG_CAP).exp())
}

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

    fn approx(a: f64, b: f64) {
        assert!((a - b).abs() < 1e-9, "expected {a} ≈ {b}");
    }

    // ───────────────────────── CORP (P0-4) ─────────────────────────

    #[test]
    fn winkler_ratio_is_invariant_to_units() {
        // The same forecast and the same relative miss, in two units 1000x apart.
        // The raw score differs by 1000x; the ratio does not.
        let ns = |low, high, value| NumericSample {
            low,
            high,
            level: 0.8,
            value,
        };
        let small = ns(10.0, 20.0, 25.0);
        let large = ns(10_000.0, 20_000.0, 25_000.0);
        assert!((winkler(&large) - winkler(&small) * 1000.0).abs() < 1e-6);
        approx(
            winkler_ratio(&small).unwrap(),
            winkler_ratio(&large).unwrap(),
        );
        // A hit scores exactly 1.0: the width itself, and nothing more.
        approx(winkler_ratio(&ns(10.0, 20.0, 15.0)).unwrap(), 1.0);
        // A zero-width interval has no ratio to give.
        assert!(winkler_ratio(&ns(5.0, 5.0, 5.0)).is_none());
    }

    #[test]
    fn recalibration_does_not_diverge_on_a_narrow_vocabulary() {
        // 200 calls, all stated at 0.9, that came true half the time. Every mu
        // saturates, the Hessian weights vanish, and the undamped Newton step
        // used to oscillate off to a = 66, b = 146 — a map that "corrects" 0.9
        // UP to 1.0 for a forecaster who is right half the time.
        let mut state = 11u64;
        let samples: Vec<Sample> = (0..200)
            .map(|_| {
                let u = (splitmix64(&mut state) >> 11) as f64 / (1u64 << 53) as f64;
                Sample::new(0.9, u < 0.5)
            })
            .collect();
        let r = fit_recalibration(&samples, 1.5).unwrap();
        assert!(r.a.is_finite() && r.b.is_finite());
        let corrected = r.apply(0.9);
        assert!(
            corrected < 0.75,
            "0.9 must be corrected DOWN toward the true 0.5, got {corrected}"
        );
        assert!(
            (corrected - 0.5).abs() < 0.2,
            "and should land near the truth, got {corrected}"
        );
    }

    #[test]
    fn the_fitted_slope_is_never_negative() {
        // Twelve calls at 0.9 that all failed, plus one lucky 0.6. The observed
        // frequencies do not rise with the forecast, so an unconstrained fit
        // converges to b = -0.69 — a map that would correct a 0.9 to BELOW what
        // it corrects a 0.5 to. At n = 15 that is noise, and inverting the
        // ordering is not a calibration correction.
        let mut samples = vec![
            Sample::new(0.6, true),
            Sample::new(0.5, false),
            Sample::new(0.7, true),
        ];
        for _ in 0..12 {
            samples.push(Sample::new(0.9, false));
        }
        let r = fit_recalibration(&samples, 1.5).unwrap();
        assert!(r.b >= 0.0, "slope must not invert, got {}", r.b);
        // Pinned at zero it collapses to a constant — which is exactly what
        // pool-adjacent-violators does with the same data.
        assert!((r.apply(0.9) - r.apply(0.5)).abs() < 1e-9);
        // And it still does the job: a stated 0.9 is pulled a long way down.
        assert!(r.apply(0.9) < 0.5, "got {}", r.apply(0.9));
        // Crucially it is NOT the identity — falling back to "no correction"
        // here would make `decide` blind to the case it exists for.
        assert!(r.apply(0.9) < 0.89);
    }

    #[test]
    fn a_diverged_map_is_rejected_even_if_the_solver_claims_success() {
        // The invariants must hold independently of the line search, because the
        // failure mode is a confidently wrong answer rather than an error.
        let samples: Vec<Sample> = (0..50).map(|i| Sample::new(0.9, i % 2 == 0)).collect();

        // The exact map the old code returned on this shape of data.
        let diverged = Recalibration {
            a: 66.0,
            b: 146.017,
            n: samples.len(),
        };
        assert!(
            !recalibration_is_sane(&diverged, &samples),
            "a map that sends 0.9 to 1.0 for a 50%-accurate forecaster must be rejected"
        );

        // A map running backwards is rejected on monotonicity alone.
        let inverted = Recalibration {
            a: 0.0,
            b: -1.0,
            n: samples.len(),
        };
        assert!(!recalibration_is_sane(&inverted, &samples));

        // The identity always passes.
        assert!(recalibration_is_sane(
            &Recalibration::identity(samples.len()),
            &samples
        ));
    }

    #[test]
    fn gaps_cost_wealth_and_can_never_manufacture_an_alarm() {
        // The whole validity argument in one assertion: whatever the ungraded
        // claim would have turned out to be, pricing it at its worst case can
        // only lower the wealth relative to actually knowing.
        let probs = [0.9, 0.2, 0.55, 0.95, 0.1, 0.75];
        for &p in &probs {
            for &y in &[0.0, 1.0] {
                let graded = calibration_log_eprocess_seq(&[Step::graded(p, y)]).unwrap();
                let gap = calibration_log_eprocess_seq(&[Step::gap(p)]).unwrap();
                assert!(
                    gap <= graded + 1e-12,
                    "a gap at p={p} must not beat the graded outcome y={y}"
                );
                assert!(gap <= 1e-12, "and must never exceed 1 (log 0)");
            }
        }

        // Gaps are priced by boldness: an ungraded 0.95 costs more than a 0.55.
        let bold = calibration_log_eprocess_seq(&[Step::gap(0.95)]).unwrap();
        let timid = calibration_log_eprocess_seq(&[Step::gap(0.55)]).unwrap();
        assert!(
            bold < timid,
            "a bold ungraded call must cost more wealth than a cautious one"
        );

        // But a gap never zeroes the process: |lambda| <= 0.9 keeps every factor
        // at or above 0.1, so the record survives a backlog instead of dying.
        let many: Vec<Step> = (0..50).map(|_| Step::gap(0.99)).collect();
        let e = calibration_log_eprocess_seq(&many).unwrap();
        assert!(e.is_finite(), "50 bold gaps must not produce -inf");
        assert!(e >= 50.0 * (0.1f64).ln() - 1e-9);

        // An all-graded sequence is exactly the old computation.
        let samples = [
            Sample::new(0.9, true),
            Sample::new(0.2, false),
            Sample::new(0.6, true),
        ];
        let steps: Vec<Step> = samples
            .iter()
            .map(|s| Step::graded(s.prob, s.outcome))
            .collect();
        approx(
            calibration_log_eprocess_seq(&steps).unwrap(),
            calibration_log_eprocess(&samples).unwrap(),
        );
    }

    #[test]
    fn gap_filling_sees_what_stopping_at_the_first_gap_cannot() {
        // A symmetrically overconfident forecaster: 0.9 when the truth is 0.65,
        // 0.1 when it is 0.35. Every third claim is left ungraded, which is the
        // measured discipline of a real agent ledger.
        let mut steps = Vec::new();
        let mut graded_prefix = Vec::new();
        let mut seen_gap = false;
        for i in 0..300 {
            let p = if i % 2 == 0 { 0.9 } else { 0.1 };
            // deterministic stand-in for the 0.65/0.35 truth
            let y = if i % 2 == 0 {
                if i % 20 < 13 {
                    1.0
                } else {
                    0.0
                }
            } else if i % 20 < 7 {
                1.0
            } else {
                0.0
            };
            if i % 3 == 2 {
                steps.push(Step::gap(p));
                seen_gap = true;
            } else {
                steps.push(Step::graded(p, y));
                if !seen_gap {
                    graded_prefix.push(Sample {
                        prob: p,
                        outcome: y,
                    });
                }
            }
        }
        let stopping = calibration_log_eprocess(&graded_prefix).unwrap();
        let gapfilled = calibration_log_eprocess_seq(&steps).unwrap();
        assert!(
            graded_prefix.len() <= 3,
            "stopping at the first gap leaves almost nothing: {}",
            graded_prefix.len()
        );
        assert!(
            stopping < EPROCESS_LOG_CAP,
            "the truncated prefix cannot establish anything"
        );
        assert!(
            gapfilled > 20.0f64.ln(),
            "gap-filled must clear the alarm on 300 claims: log e = {gapfilled}"
        );
    }

    #[test]
    fn a_collapsed_map_says_it_collapsed() {
        // A forecaster whose stated confidence is anti-correlated with the truth.
        // The projected fit cannot use an inverted ranking, so it flattens to the
        // base rate — which is right, but makes every `decide` answer identical.
        let samples: Vec<Sample> = (0..60)
            .map(|i| Sample::new(if i % 2 == 0 { 0.9 } else { 0.1 }, i % 2 != 0))
            .collect();
        let r = fit_recalibration(&samples, 1.0).unwrap();
        assert_eq!(r.b, 0.0, "an inverted ranking must project to a flat map");
        assert_eq!(r.kind(), MapKind::Constant);

        // The point of naming it: the act no longer depends on the input.
        let hi = decide(0.99, Some(r), 10.0, 2.0);
        let lo = decide(0.55, Some(r), 10.0, 2.0);
        assert_eq!(hi.map_kind, MapKind::Constant);
        assert!(
            (hi.adjusted_p - lo.adjusted_p).abs() < 1e-12,
            "a constant map returns the same number for any stated p"
        );
        assert_eq!(hi.act, lo.act);

        // The ordinary cases still report themselves as what they are.
        assert_eq!(Recalibration::identity(10).kind(), MapKind::Identity);
        assert_eq!(decide(0.7, None, 1.0, 0.2).map_kind, MapKind::Identity);
        assert_eq!(
            Recalibration {
                a: 0.3,
                b: 0.8,
                n: 40
            }
            .kind(),
            MapKind::Logistic
        );
    }

    #[test]
    fn recalibration_still_recovers_a_known_slope() {
        // The well-conditioned case must be unaffected by the line search: an
        // agent whose truth is sigma(0.4 * logit p) should get a slope pulling
        // its stated numbers toward the middle.
        let mut state = 5u64;
        let samples: Vec<Sample> = (0..600)
            .map(|_| {
                let u = (splitmix64(&mut state) >> 11) as f64 / (1u64 << 53) as f64;
                let p = ((u * 0.9 + 0.05) * 100.0).round() / 100.0;
                let truth = sigmoid(0.4 * logit(p));
                let v = (splitmix64(&mut state) >> 11) as f64 / (1u64 << 53) as f64;
                Sample::new(p, v < truth)
            })
            .collect();
        let r = fit_recalibration(&samples, 1.5).unwrap();
        assert!(
            r.b < 1.0,
            "slope should say the forecasts run too extreme: {}",
            r.b
        );
        assert!(r.apply(0.9) < 0.9);
        assert!(r.apply(0.1) > 0.1);
    }

    #[test]
    fn corp_identity_holds_exactly() {
        // S = MCB - DSC + UNC, to the last bit, on messy real-shaped input.
        let mut state = 7u64;
        let samples: Vec<Sample> = (0..300)
            .map(|_| {
                let u = (splitmix64(&mut state) >> 11) as f64 / (1u64 << 53) as f64;
                let p = ((u * 0.96 + 0.02) * 100.0).round() / 100.0;
                let u = (splitmix64(&mut state) >> 11) as f64 / (1u64 << 53) as f64;
                Sample::new(p, u < p)
            })
            .collect();
        let c = corp_brier(&samples).unwrap();
        let residual = (c.score - (c.mcb - c.dsc + c.unc)).abs();
        assert!(residual < 1e-12, "identity residual {residual:e}");
    }

    #[test]
    fn corp_agrees_with_exact_decomposition_when_frequencies_are_monotone() {
        // When observed frequencies already rise with the forecast, isotonic
        // regression changes nothing, so MCB = REL and DSC = RES. This is what
        // keeps the old "exact decomposition" promise true where it was true.
        let samples = vec![
            Sample::new(0.2, false),
            Sample::new(0.2, false),
            Sample::new(0.2, true),
            Sample::new(0.5, false),
            Sample::new(0.5, true),
            Sample::new(0.9, true),
            Sample::new(0.9, true),
            Sample::new(0.9, false),
        ];
        let corp = corp_brier(&samples).unwrap();
        let old = decompose(&samples).unwrap();
        approx(corp.mcb, old.reliability);
        approx(corp.dsc, old.resolution);
        approx(corp.unc, old.uncertainty);
    }

    #[test]
    fn corp_reports_zero_discrimination_when_confidence_carries_no_information() {
        // 50 calls at 0.9 on coin flips + 50 at 0.6 on sure things. Higher
        // confidence went with a LOWER hit rate, so after isotonic regression
        // both groups collapse to one value: the forecasts order nothing.
        let mut samples: Vec<Sample> = Vec::new();
        for i in 0..50 {
            samples.push(Sample::new(0.9, i % 2 == 0));
        }
        for _ in 0..50 {
            samples.push(Sample::new(0.6, true));
        }
        let c = corp_brier(&samples).unwrap();
        assert!(
            c.dsc.abs() < 1e-12,
            "DSC should be exactly 0, got {}",
            c.dsc
        );
        // And the miscalibration is far above what luck alone would produce.
        let floor = mcb_null_quantile(&samples, 400, 0.95, 0xA11CE).unwrap();
        assert!(c.mcb > floor * 3.0, "mcb {} vs floor {floor}", c.mcb);
    }

    #[test]
    fn corp_is_quieter_than_exact_grouping_on_a_calibrated_forecaster() {
        // The defect that made this necessary: with two-decimal probabilities
        // most exact-value groups hold one claim, whose observed frequency is
        // always 0 or 1, so the old reliability term reports a large calibration
        // error for someone who has none.
        let mut state = 99u64;
        let samples: Vec<Sample> = (0..200)
            .map(|_| {
                let p = (((splitmix64(&mut state) >> 11) as f64 / (1u64 << 53) as f64) * 0.96
                    + 0.02)
                    * 100.0;
                let p = p.round() / 100.0;
                let u = (splitmix64(&mut state) >> 11) as f64 / (1u64 << 53) as f64;
                Sample::new(p, u < p)
            })
            .collect();
        let corp = corp_brier(&samples).unwrap();
        let old = decompose(&samples).unwrap();
        assert!(
            corp.mcb < old.reliability * 0.5,
            "CORP MCB {} should be far below exact-group REL {}",
            corp.mcb,
            old.reliability
        );
        // And it sits at or below its own noise floor: nothing to report.
        let floor = mcb_null_quantile(&samples, 400, 0.95, 0xA11CE).unwrap();
        assert!(corp.mcb <= floor, "mcb {} floor {floor}", corp.mcb);
    }

    #[test]
    fn mcb_null_quantile_is_deterministic() {
        let samples: Vec<Sample> = (0..50).map(|i| Sample::new(0.7, i % 3 != 0)).collect();
        let a = mcb_null_quantile(&samples, 200, 0.95, 1234).unwrap();
        let b = mcb_null_quantile(&samples, 200, 0.95, 1234).unwrap();
        assert_eq!(a, b, "the noise floor must not move under a re-run");
        assert!(mcb_null_quantile(&samples[..1], 200, 0.95, 1234).is_none());
    }

    // ─────────────────── multi-strategy e-process (P0-3a) ───────────────────

    #[test]
    fn eprocess_v2_detects_symmetric_overconfidence_that_v1_misses() {
        // Says 90% when the truth is 65%; says 10% when the truth is 35%. The
        // two errors cancel in the single-strategy statistic.
        let mut state = 5u64;
        let samples: Vec<Sample> = (0..200)
            .map(|i| {
                let p = if i % 2 == 0 { 0.9 } else { 0.1 };
                let truth = if i % 2 == 0 { 0.65 } else { 0.35 };
                let u = (splitmix64(&mut state) >> 11) as f64 / (1u64 << 53) as f64;
                Sample::new(p, u < truth)
            })
            .collect();
        let v1 = calibration_eprocess(&samples).unwrap();
        let v2 = calibration_eprocess_v2(&samples).unwrap();
        assert!(v1 < 20.0, "v1 was supposed to be blind here, got {v1}");
        assert!(v2 >= 20.0, "v2 must find it, got {v2}");
    }

    #[test]
    fn eprocess_v2_stays_quiet_on_a_calibrated_forecaster() {
        // The property that matters more than power: it must not cry wolf.
        let mut state = 31u64;
        let samples: Vec<Sample> = (0..500)
            .map(|_| {
                let p = (((splitmix64(&mut state) >> 11) as f64 / (1u64 << 53) as f64) * 0.9
                    + 0.05)
                    * 100.0;
                let p = p.round() / 100.0;
                let u = (splitmix64(&mut state) >> 11) as f64 / (1u64 << 53) as f64;
                Sample::new(p, u < p)
            })
            .collect();
        // Anytime-valid: check at EVERY prefix, which is the whole point.
        for k in 1..=samples.len() {
            let e = calibration_eprocess_v2(&samples[..k]).unwrap();
            assert!(e < 20.0, "false alarm at n={k}: e={e}");
        }
    }

    #[test]
    fn eprocess_v2_never_returns_infinity() {
        // Extreme, perfectly wrong forecasts: the log form must stay printable.
        let samples: Vec<Sample> = (0..2000).map(|_| Sample::new(0.99, false)).collect();
        let e = calibration_eprocess_v2(&samples).unwrap();
        assert!(e.is_finite(), "e must be finite, got {e}");
        assert!(e <= EPROCESS_LOG_CAP.exp() + 1.0);
        assert!(calibration_log_eprocess(&samples).unwrap() > 100.0);
    }

    #[test]
    fn shrinkage_pulls_small_n_toward_prior() {
        // 1/1 with a 0.5 prior, strength 4 → (1+2)/(1+4) = 0.6, not 1.0.
        approx(shrink_toward(1.0, 1, 0.5, 4.0), 0.6);
        // Large n barely moves: 80/100 shrunk toward 0.5 stays ≈ 0.79.
        let s = shrink_toward(80.0, 100, 0.5, 4.0);
        assert!(s > 0.78 && s < 0.80, "s={s}");
        // strength 0 recovers the raw rate.
        approx(shrink_toward(3.0, 4, 0.5, 0.0), 0.75);
    }

    #[test]
    fn wilson_interval_known_and_bounded() {
        // 1 of 2 at 95%: symmetric about 0.5 and wide, as small n demands.
        let (lo, hi) = wilson_interval(1.0, 2, 1.96).unwrap();
        assert!((lo - 0.0945).abs() < 1e-3, "lo={lo}");
        assert!((hi - 0.9055).abs() < 1e-3, "hi={hi}");
        // 0 of 5: clamps at 0 below, stays strictly inside (0,1) above.
        let (lo0, hi0) = wilson_interval(0.0, 5, 1.96).unwrap();
        assert_eq!(lo0, 0.0);
        assert!(hi0 > 0.0 && hi0 < 1.0, "hi0={hi0}");
        // The interval always brackets the point estimate.
        let (lo2, hi2) = wilson_interval(7.0, 10, 1.96).unwrap();
        assert!(lo2 < 0.7 && 0.7 < hi2, "[{lo2},{hi2}] should bracket 0.7");
        // n = 0 → undefined.
        assert!(wilson_interval(0.0, 0, 1.96).is_none());
    }

    #[test]
    fn brier_known_values() {
        // Perfect, confident, correct.
        approx(
            brier(&[Sample::new(1.0, true), Sample::new(0.0, false)]).unwrap(),
            0.0,
        );
        // Always 0.5: squared error 0.25 every time.
        approx(
            brier(&[Sample::new(0.5, true), Sample::new(0.5, false)]).unwrap(),
            0.25,
        );
        // Confidently, maximally wrong.
        approx(
            brier(&[Sample::new(0.0, true), Sample::new(1.0, false)]).unwrap(),
            1.0,
        );
        assert!(brier(&[]).is_none());
    }

    #[test]
    fn log_score_known_values() {
        // p = 0.5 every time ⇒ -ln(0.5) = ln 2.
        approx(
            log_score(&[Sample::new(0.5, true), Sample::new(0.5, false)], 0.0).unwrap(),
            std::f64::consts::LN_2,
        );
        // Perfect & confident with clamping ⇒ ~0.
        let s = log_score(&[Sample::new(1.0, true), Sample::new(0.0, false)], 1e-12).unwrap();
        assert!(s < 1e-9, "near-perfect log score should be tiny, got {s}");
    }

    #[test]
    fn decomposition_identity_holds_exactly() {
        // The whole reason for grouping by exact forecast value: REL - RES + UNC
        // must reproduce the empirical Brier to floating-point precision, for
        // arbitrary data. Exercise a deterministic but irregular spread.
        let mut samples = Vec::new();
        let probs = [0.05, 0.2, 0.35, 0.5, 0.65, 0.8, 0.95, 0.5, 0.8, 0.2];
        for (i, &p) in probs.iter().cycle().take(137).enumerate() {
            // pseudo-random-ish but deterministic outcome
            let happened = ((i * 2654435761usize) >> 13) & 1 == 0;
            samples.push(Sample::new(p, happened));
        }
        let d = decompose(&samples).unwrap();
        let b = brier(&samples).unwrap();
        approx(d.brier, b);
        approx(d.reliability - d.resolution + d.uncertainty, b);
        // Components are non-negative.
        assert!(d.reliability >= -1e-12);
        assert!(d.resolution >= -1e-12);
        assert!(d.uncertainty >= -1e-12);
    }

    #[test]
    fn perfect_calibration_has_zero_reliability() {
        // 100 forecasts at p=0.7, exactly 70 of which come true.
        let mut samples = Vec::new();
        for i in 0..100 {
            samples.push(Sample::new(0.7, i < 70));
        }
        let d = decompose(&samples).unwrap();
        approx(d.reliability, 0.0); // perfectly calibrated at this value
    }

    #[test]
    fn auc_separates_and_handles_degenerate() {
        // Perfect separation: every true got a higher prob than every false.
        let s = [
            Sample::new(0.9, true),
            Sample::new(0.8, true),
            Sample::new(0.2, false),
            Sample::new(0.1, false),
        ];
        approx(auc(&s).unwrap(), 1.0);
        // Reversed ranking ⇒ AUC 0.0.
        let r = [
            Sample::new(0.1, true),
            Sample::new(0.2, true),
            Sample::new(0.8, false),
            Sample::new(0.9, false),
        ];
        approx(auc(&r).unwrap(), 0.0);
        // All ties at 0.5 ⇒ AUC 0.5.
        let t = [Sample::new(0.5, true), Sample::new(0.5, false)];
        approx(auc(&t).unwrap(), 0.5);
        // No negatives ⇒ undefined.
        assert!(auc(&[Sample::new(0.6, true)]).is_none());
    }

    /// Self-evidently-correct `O(n²)` reference, kept only to validate the fast
    /// rank-based `auc`.
    fn auc_pairwise(samples: &[Sample]) -> Option<f64> {
        let pos: Vec<f64> = samples
            .iter()
            .filter(|s| s.outcome >= 0.5)
            .map(|s| s.prob)
            .collect();
        let neg: Vec<f64> = samples
            .iter()
            .filter(|s| s.outcome < 0.5)
            .map(|s| s.prob)
            .collect();
        if pos.is_empty() || neg.is_empty() {
            return None;
        }
        let mut wins = 0.0;
        for &p in &pos {
            for &q in &neg {
                if p > q {
                    wins += 1.0;
                } else if p == q {
                    wins += 0.5;
                }
            }
        }
        Some(wins / (pos.len() as f64 * neg.len() as f64))
    }

    #[test]
    fn auc_rank_matches_pairwise_reference_with_ties() {
        // Deterministic datasets deliberately full of tied probabilities, so the
        // average-rank tie handling is actually exercised against the oracle.
        let probs = [0.1, 0.1, 0.4, 0.5, 0.5, 0.5, 0.7, 0.7, 0.9, 0.95];
        for seed in 0u64..64 {
            let samples: Vec<Sample> = probs
                .iter()
                .enumerate()
                .map(|(i, &p)| Sample::new(p, ((seed >> (i % 6)) & 1) == 0))
                .collect();
            match (auc(&samples), auc_pairwise(&samples)) {
                (Some(a), Some(b)) => approx(a, b),
                (None, None) => {}
                (x, y) => panic!("AUC definedness disagrees: {x:?} vs {y:?}"),
            }
        }
    }

    #[test]
    fn overconfidence_detects_boldness_gap() {
        // Bold (0.9) but right only half the time ⇒ overconfident by ~0.4.
        let mut samples = Vec::new();
        for i in 0..100 {
            samples.push(Sample::new(0.9, i < 50));
        }
        let o = overconfidence(&samples).unwrap();
        approx(o.mean_confidence, 0.9);
        approx(o.accuracy, 0.5);
        approx(o.gap, 0.4);
        // A perfectly calibrated bold forecaster has gap ~0.
        let mut cal = Vec::new();
        for i in 0..100 {
            cal.push(Sample::new(0.9, i < 90));
        }
        approx(overconfidence(&cal).unwrap().gap, 0.0);
    }

    #[test]
    fn skill_score_zero_for_base_rate_forecaster() {
        // Always predicting the base rate (0.6) ⇒ no skill ⇒ BSS == 0.
        let mut samples = Vec::new();
        for i in 0..100 {
            samples.push(Sample::new(0.6, i < 60));
        }
        approx(skill_score(&samples).unwrap(), 0.0);
    }

    #[test]
    fn calibration_curve_bins_correctly() {
        let samples = [
            Sample::new(0.05, false),
            Sample::new(0.15, false),
            Sample::new(0.95, true),
            Sample::new(1.0, true), // must land in the last bin, not overflow
        ];
        let bins = calibration_curve(&samples, 10);
        assert_eq!(bins.len(), 10);
        assert_eq!(bins[0].count, 1);
        assert_eq!(bins[1].count, 1);
        assert_eq!(bins[9].count, 2); // 0.95 and 1.0
        approx(bins[9].observed, 1.0);
    }

    #[test]
    fn winkler_inside_is_width_outside_is_penalised() {
        let inside = NumericSample {
            low: 10.0,
            high: 20.0,
            level: 0.8,
            value: 15.0,
        };
        approx(winkler(&inside), 10.0); // just the width

        // width 10 + (2/0.2)*(10 - 5) = 10 + 10*5 = 60
        let below = NumericSample {
            low: 10.0,
            high: 20.0,
            level: 0.8,
            value: 5.0,
        };
        approx(winkler(&below), 60.0);
        let above = NumericSample {
            low: 10.0,
            high: 20.0,
            level: 0.8,
            value: 25.0,
        };
        approx(winkler(&above), 60.0);

        // A tighter nominal level (larger α) penalises a miss less.
        let loose = NumericSample {
            low: 10.0,
            high: 20.0,
            level: 0.5,
            value: 5.0,
        };
        // 10 + (2/0.5)*5 = 10 + 4*5 = 30
        approx(winkler(&loose), 30.0);
    }

    #[test]
    fn coverage_counts_contained_intervals() {
        let s = [
            NumericSample {
                low: 0.0,
                high: 10.0,
                level: 0.8,
                value: 5.0,
            }, // in
            NumericSample {
                low: 0.0,
                high: 10.0,
                level: 0.8,
                value: 50.0,
            }, // out
            NumericSample {
                low: 0.0,
                high: 10.0,
                level: 0.8,
                value: 0.0,
            }, // edge = in
        ];
        approx(coverage(&s).unwrap(), 2.0 / 3.0);
        assert!(coverage(&[]).is_none());
    }

    #[test]
    fn conformal_width_factor_scales_to_hit_nominal() {
        // Helper: an interval centred at 0 with half-width 1, so the standardized
        // residual equals |value|. level is the nominal coverage of the interval.
        let mk = |value: f64, level: f64| NumericSample {
            low: -1.0,
            high: 1.0,
            level,
            value,
        };

        // Residuals {0.2, 0.4, 0.6, 0.8}, target 0.5 → the 0.5-quantile is the
        // midpoint of 0.4 and 0.6 = 0.5. Scaling half-widths by 0.5 leaves exactly
        // the two residuals ≤ 0.5 covered = 50% = nominal. Intervals are too wide.
        let wide = [mk(0.2, 0.5), mk(0.4, 0.5), mk(0.6, 0.5), mk(0.8, 0.5)];
        approx(conformal_width_factor(&wide).unwrap(), 0.5);

        // Residuals {0.5, 0.9, 1.3, 1.7, 2.1}, target 0.8 → 0.8-quantile sits at
        // pos 3.2 between 1.7 and 2.1 = 1.78. m > 1: intervals are too narrow.
        let narrow = [
            mk(0.5, 0.8),
            mk(0.9, 0.8),
            mk(1.3, 0.8),
            mk(1.7, 0.8),
            mk(2.1, 0.8),
        ];
        let m = conformal_width_factor(&narrow).unwrap();
        assert!((m - 1.78).abs() < 1e-9, "m={m}");

        // Fewer than three usable samples, or only degenerate point intervals → None.
        assert!(conformal_width_factor(&wide[..2]).is_none());
        let points =
            [mk(0.0, 0.5), mk(0.0, 0.5), mk(0.0, 0.5)].map(|s| NumericSample { high: -1.0, ..s }); // width 0 ⇒ all skipped
        assert!(conformal_width_factor(&points).is_none());
    }

    #[test]
    fn decide_thresholds_on_chow_rule_and_stakes() {
        // Ordinary stake 1, a check costs 0.2 → break-even τ = 1 − 0.2/1 = 0.80.
        let d = decide(0.85, None, 1.0, 0.2);
        approx(d.proceed_threshold, 0.80);
        assert_eq!(d.act, Act::Proceed); // 0.85 ≥ 0.80
        approx(d.margin, 0.05);

        // Same call at 0.70 lands in the doubt zone → verify (0.5 ≤ 0.70 < 0.80).
        assert_eq!(decide(0.70, None, 1.0, 0.2).act, Act::Verify);

        // Raise the stakes and the bar climbs: τ = 1 − 0.2/4 = 0.95, so even 0.90
        // is no longer good enough to skip the check.
        let hi = decide(0.90, None, 4.0, 0.2);
        approx(hi.proceed_threshold, 0.95);
        assert_eq!(hi.act, Act::Verify);

        // Below even odds (after any correction) → abstain, not verify.
        assert_eq!(decide(0.40, None, 1.0, 0.2).act, Act::Abstain);
    }

    #[test]
    fn decide_applies_the_track_record_correction_first() {
        // A map that says "your 0.70s are really ~0.34" (overconfident history).
        let overconf = Recalibration {
            a: -1.5,
            b: 1.0,
            n: 12,
        };
        // Raw 0.70 on an ordinary call would only *verify*…
        assert_eq!(decide(0.70, None, 1.0, 0.2).act, Act::Verify);
        // …but corrected to 0.34 it drops below even odds → abstain. The gate acts
        // on the de-biased number, exactly the point.
        let d = decide(0.70, Some(overconf), 1.0, 0.2);
        assert!(d.adjusted_p < 0.5, "adjusted={}", d.adjusted_p);
        assert_eq!(d.act, Act::Abstain);
    }

    #[test]
    fn decide_degenerate_costs_are_sane() {
        // Nothing at stake → just proceed, even on a long shot.
        assert_eq!(decide(0.10, None, 0.0, 0.2).act, Act::Proceed);
        // A check costing as much as the worst case → never worth it, proceed.
        assert_eq!(decide(0.30, None, 1.0, 1.0).proceed_threshold, 0.0);
        assert_eq!(decide(0.30, None, 1.0, 1.0).act, Act::Proceed);
        // A free check → demand near-certainty; 0.99 still verifies.
        approx(decide(0.99, None, 1.0, 0.0).proceed_threshold, 1.0);
        assert_eq!(decide(0.99, None, 1.0, 0.0).act, Act::Verify);
    }

    #[test]
    fn mean_boldness_measures_distance_from_a_coin_flip() {
        // max(p,1−p) of 0.9, 0.5, 0.2 → 0.9, 0.5, 0.8 → mean 0.7333.
        approx(mean_boldness(&[0.9, 0.5, 0.2]).unwrap(), 2.2 / 3.0);
        approx(mean_boldness(&[0.5]).unwrap(), 0.5); // a pure shrug
        assert!(mean_boldness(&[]).is_none());
    }

    #[test]
    fn asmd_is_a_standardized_gap_robust_to_degeneracy() {
        // means 0.7 vs 0.8, each sd 0.2, pooled 0.2 → ASMD = 0.1/0.2 = 0.5.
        approx(asmd(&[0.5, 0.7, 0.9], &[0.6, 0.8, 1.0]).unwrap(), 0.5);
        // Identical groups → zero gap.
        approx(asmd(&[0.4, 0.6], &[0.4, 0.6]).unwrap(), 0.0);
        // No spread to standardize against, or a group too small → None, not NaN.
        assert!(asmd(&[0.5, 0.5], &[0.6, 0.6]).is_none());
        assert!(asmd(&[0.5], &[0.6, 0.8]).is_none());
    }

    #[test]
    fn eprocess_finds_no_evidence_on_calibrated_data() {
        // Alternating outcomes at p=0.5: calibration-in-the-large holds, and a
        // fixed (non-predictable) bettor cannot profit → wealth never grows.
        let s: Vec<Sample> = (0..60).map(|i| Sample::new(0.5, i % 2 == 0)).collect();
        let e = calibration_eprocess(&s).unwrap();
        assert!(
            e < 5.0,
            "calibrated data should not accumulate evidence, e={e}"
        );
        assert!(eprocess_pvalue(e) > 0.05);
    }

    #[test]
    fn eprocess_detects_gross_miscalibration() {
        // "10% sure" every time, but it always happens → wildly underconfident.
        let s: Vec<Sample> = (0..40).map(|_| Sample::new(0.1, true)).collect();
        let e = calibration_eprocess(&s).unwrap();
        assert!(
            e >= 20.0,
            "gross miscalibration should be significant, e={e}"
        );
        assert!(eprocess_pvalue(e) < 0.05);
    }

    #[test]
    fn eprocess_is_finite_at_extremes_and_none_when_empty() {
        assert!(calibration_eprocess(&[]).is_none());
        // p exactly 0/1 and wrong: factors stay non-negative, wealth finite.
        let s = vec![Sample::new(1.0, false), Sample::new(0.0, true)];
        let e = calibration_eprocess(&s).unwrap();
        assert!(e.is_finite() && e > 0.0, "e={e}");
    }

    #[test]
    fn recalibration_is_identity_on_calibrated_data() {
        // Forecasts that match realised frequencies ⇒ map ≈ identity.
        let mut s = Vec::new();
        for i in 0..100 {
            s.push(Sample::new(0.7, i < 70)); // 0.7 happens 70%
        }
        for i in 0..100 {
            s.push(Sample::new(0.3, i < 30)); // 0.3 happens 30%
        }
        let r = fit_recalibration(&s, 1.0).unwrap();
        assert!(
            (r.apply(0.7) - 0.7).abs() < 0.05,
            "apply(0.7)={}",
            r.apply(0.7)
        );
        assert!(
            (r.apply(0.3) - 0.3).abs() < 0.05,
            "apply(0.3)={}",
            r.apply(0.3)
        );
    }

    #[test]
    fn recalibration_corrects_underconfidence() {
        // Stated 0.6 but true rate 0.9; stated 0.4 but true rate 0.1 → too timid.
        let mut s = Vec::new();
        for i in 0..100 {
            s.push(Sample::new(0.6, i < 90));
        }
        for i in 0..100 {
            s.push(Sample::new(0.4, i < 10));
        }
        let r = fit_recalibration(&s, 1.0).unwrap();
        assert!(r.b > 1.0, "slope should exceed 1 (too timid), b={}", r.b);
        assert!(
            r.apply(0.6) > 0.75,
            "0.6 should be pushed up, got {}",
            r.apply(0.6)
        );
        assert!(
            r.apply(0.4) < 0.25,
            "0.4 should be pushed down, got {}",
            r.apply(0.4)
        );
    }

    #[test]
    fn recalibration_stays_near_identity_at_small_n() {
        // One lucky hit must not yield a confident correction.
        let r = fit_recalibration(&[Sample::new(0.6, true)], 2.0).unwrap();
        assert!(
            (r.apply(0.6) - 0.6).abs() < 0.12,
            "apply(0.6)={}",
            r.apply(0.6)
        );
    }

    #[test]
    fn recalibration_survives_perfect_separation() {
        // Unpenalised MLE would diverge; the ridge keeps it finite and monotone.
        let s = [
            Sample::new(0.2, false),
            Sample::new(0.3, false),
            Sample::new(0.7, true),
            Sample::new(0.8, true),
        ];
        let r = fit_recalibration(&s, 1.0).unwrap();
        assert!(r.a.is_finite() && r.b.is_finite(), "a={}, b={}", r.a, r.b);
        assert!(r.apply(0.8) > r.apply(0.2), "map should stay increasing");
        assert!(fit_recalibration(&[], 1.0).is_none());
    }

    #[test]
    fn bootstrap_ci_brackets_point_and_is_deterministic() {
        let s: Vec<Sample> = (0..40).map(|i| Sample::new(0.7, i % 10 < 7)).collect();
        let b = brier(&s).unwrap();
        let (lo, hi) = brier_ci_bootstrap(&s, 0.95, 2000, 42).unwrap();
        assert!(
            lo <= b && b <= hi,
            "CI [{lo},{hi}] should bracket point {b}"
        );
        assert!((0.0..=1.0).contains(&lo) && (0.0..=1.0).contains(&hi));
        // Same seed ⇒ identical interval (reproducible reports).
        assert_eq!((lo, hi), brier_ci_bootstrap(&s, 0.95, 2000, 42).unwrap());
        // One sample (or zero) is not enough for a band.
        assert!(brier_ci_bootstrap(&[Sample::new(0.5, true)], 0.95, 100, 1).is_none());
    }

    #[test]
    fn ewma_brier_rewards_recent_improvement() {
        // Wrong early (Brier 1.0), perfect late (Brier 0.0): recency < lifetime 0.5.
        let mut s = Vec::new();
        for _ in 0..10 {
            s.push(Sample::new(0.0, true));
        }
        for _ in 0..10 {
            s.push(Sample::new(1.0, true));
        }
        let life = brier(&s).unwrap();
        let recent = ewma_brier(&s, 5.0).unwrap();
        assert!(
            recent < life,
            "recency should reward recent gains: {recent} vs {life}"
        );
        // Constant performance ⇒ EWMA equals that Brier.
        let c: Vec<Sample> = (0..20).map(|_| Sample::new(0.5, true)).collect();
        approx(ewma_brier(&c, 5.0).unwrap(), 0.25);
        assert!(ewma_brier(&[], 5.0).is_none());
    }

    #[test]
    fn distinct_forecasts_counts_unique_values() {
        let s = [
            Sample::new(0.6, true),
            Sample::new(0.6, false),
            Sample::new(0.3, true),
        ];
        assert_eq!(distinct_forecasts(&s), 2);
        assert_eq!(distinct_forecasts(&[]), 0);
    }

    #[test]
    fn risk_coverage_rewards_a_good_confidence_ranking() {
        // The confident calls are right; the unsure ones are the errors.
        let mut s = Vec::new();
        for _ in 0..10 {
            s.push(Sample::new(0.95, true)); // confident & correct
        }
        for _ in 0..10 {
            s.push(Sample::new(0.55, false)); // unsure & wrong (leaned yes, didn't happen)
        }
        let rc = risk_coverage(&s).unwrap();
        approx(rc.risk_at_full, 0.5); // act on all → 10/20 wrong
        assert!(
            rc.risk_at(0.5) < 0.05,
            "the most-confident half should be near-perfect, got {}",
            rc.risk_at(0.5)
        );
        assert!(
            rc.aurcc < rc.risk_at_full,
            "being selective should beat acting on everything"
        );
    }

    #[test]
    fn risk_coverage_flags_inverted_confidence() {
        // Confidence is anti-informative: the bold calls are the wrong ones.
        let mut s = Vec::new();
        for _ in 0..10 {
            s.push(Sample::new(0.95, false)); // confident & wrong
        }
        for _ in 0..10 {
            s.push(Sample::new(0.55, true)); // unsure & right
        }
        let rc = risk_coverage(&s).unwrap();
        assert!(
            rc.risk_at(0.5) > rc.risk_at_full,
            "surest-half error should exceed overall when ranking is inverted"
        );
        assert!(risk_coverage(&[]).is_none());
    }

    #[test]
    fn dialectical_mean_averages_the_crowd_within() {
        approx(dialectical_mean(0.7, 0.5), 0.6);
        approx(dialectical_mean(0.9, 0.9), 0.9);
        approx(dialectical_mean(1.5, -0.2), 0.5); // clamps out-of-range inputs
    }

    #[test]
    fn weighted_brier_emphasises_high_stake_calls() {
        // A cheap perfect call and a costly blown one: unweighted Brier is 0.5…
        let s = [Sample::new(1.0, true), Sample::new(0.0, true)]; // briers 0 and 1
        approx(brier_weighted(&s, &[1.0, 1.0]).unwrap(), 0.5);
        // …but weight the blown call 9× and it rightly dominates.
        approx(brier_weighted(&s, &[1.0, 9.0]).unwrap(), 0.9);
        // Equal weights reproduce the plain Brier.
        approx(brier_weighted(&s, &[2.0, 2.0]).unwrap(), brier(&s).unwrap());
        // No positive weight, or a length mismatch ⇒ None.
        assert!(brier_weighted(&s, &[0.0, 0.0]).is_none());
        assert!(brier_weighted(&s, &[1.0]).is_none());
    }

    #[test]
    fn detection_rate_is_rare_for_a_calibrated_forecaster_and_grows_with_the_error() {
        let probs = [0.9, 0.8, 0.7, 0.95, 0.85, 0.6, 0.75, 0.9, 0.8, 0.65];
        let steps: Vec<Step> = (0..200).map(|i| Step::graded(probs[i % 10], 1.0)).collect();
        let calibrated = detection_rate(&steps, 0.0, 20.0, 400, 7).unwrap();
        // Ville: a calibrated forecaster reaches 20 at most one time in 20, at any n.
        assert!(calibrated <= 0.05 + 0.03, "calibrated flagged {calibrated}");
        let mild = detection_rate(&steps, 0.3, 20.0, 400, 7).unwrap();
        let strong = detection_rate(&steps, 0.6, 20.0, 400, 7).unwrap();
        assert!(
            calibrated < mild && mild < strong,
            "{calibrated} {mild} {strong}"
        );
        assert!(strong > 0.9, "strong {strong}");
        // reproducible
        assert_eq!(detection_rate(&steps, 0.3, 20.0, 400, 7).unwrap(), mild);
        // a gap stays a gap, and it can only lower the rate
        let mut gapped = steps.clone();
        for s in gapped.iter_mut().step_by(4) {
            *s = Step::gap(s.prob);
        }
        assert!(detection_rate(&gapped, 0.3, 20.0, 400, 7).unwrap() <= mild + 0.05);
        assert_eq!(detection_rate(&[Step::gap(0.9)], 0.3, 20.0, 10, 7), None);
        assert_eq!(detection_rate(&steps, 0.3, 20.0, 0, 7), None);
    }
}