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
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
//! Rendering the calibration report — the moment the ledger stops being a diary
//! and becomes a mirror.
//!
//! The metrics are computed exactly once into a serializable [`ReportData`]; the
//! human ([`render`]) and machine ([`render_json`]) views are two renderings of
//! that single source of truth, so they can never silently disagree. Every
//! metric that can be undefined is an `Option<f64>` — which serialises to JSON
//! `null` rather than a `NaN` that serde_json would quietly turn into `null`
//! anyway (and could never read back).

use std::collections::BTreeMap;
use std::fmt::Write as _;

use serde::Serialize;

use chrono::NaiveDate;

use crate::model::Ledger;
use crate::scoring::{self, NumericSample, Sample};
use crate::untrusted;

const LANE_W: usize = 34;

/// Coerce a possibly-NaN/Infinite float to `Some(finite)` or `None`.
fn finite(x: f64) -> Option<f64> {
    x.is_finite().then_some(x)
}

// ─────────────────────────── computed data ──────────────────────────────────

/// One bin of the reliability diagram, machine-readable.
#[derive(Serialize, Clone, Debug)]
pub struct BinData {
    pub lo: f64,
    pub hi: f64,
    pub count: usize,
    /// Mean forecast in the bin; `None` when the bin is empty.
    pub mean_pred: Option<f64>,
    /// Observed frequency of "true" in the bin; `None` when empty.
    pub observed: Option<f64>,
}

/// Per-tag slice of the binary record.
#[derive(Serialize, Clone, Debug)]
pub struct TagStat {
    pub tag: String,
    pub n: usize,
    pub brier: Option<f64>,
    pub confidence_gap: Option<f64>,
    /// Confidence gap with accuracy shrunk toward the overall rate — the
    /// small-n-robust number to trust when `n` is tiny.
    pub confidence_gap_shrunk: Option<f64>,
    /// Anytime-valid calibration e-value *within this slice* — the multicalibration
    /// view: which kind of prediction is *really* miscalibrated, not just by luck.
    /// Valid at tiny subgroup `n` (it cannot false-alarm), unlike a raw worst-group
    /// gap. `None` for the by-tag rows, where it is not surfaced.
    pub eprocess: Option<f64>,
}

/// Summary of the claims whose probability you revised before they resolved.
#[derive(Serialize, Clone, Debug)]
pub struct MindChange {
    pub revised: usize,
    pub brier_first: f64,
    pub brier_last: f64,
    /// `brier_first − brier_last`; positive ⇒ your revisions moved toward truth.
    pub improvement: f64,
}

/// Numeric / interval-forecast summary.
#[derive(Serialize, Clone, Debug)]
pub struct NumericData {
    pub count: usize,
    pub mean_winkler: f64,
    /// Mean Winkler score as a multiple of each interval's own width — unitless,
    /// so a question measured in dollars cannot dominate one in milliseconds.
    /// `1.0` = every value landed inside.
    pub mean_winkler_ratio: Option<f64>,
    /// The median of the same quantity, which one disastrous miss cannot move.
    pub median_winkler_ratio: Option<f64>,
    /// Average nominal level of your intervals (e.g. 0.80 for 80% intervals).
    pub nominal_coverage: f64,
    /// Fraction of intervals that actually contained the outcome.
    pub empirical_coverage: f64,
    /// `empirical − nominal`; negative ⇒ your intervals are too narrow
    /// (overconfident), positive ⇒ too wide.
    pub coverage_gap: f64,
    pub mean_width: f64,
    /// Jeffreys-shrunk coverage `(k+½)/(n+1)` — the de-noised coverage point that
    /// keeps a 0-of-3 or 3-of-3 fluke from reading as 0% or 100%.
    pub coverage_shrunk: f64,
    /// Anytime-valid e-value on interval coverage (the same betting test as the
    /// binary side, fed `prob = nominal level`, `outcome = contained`): is the
    /// miscoverage real, or too few intervals to tell?
    pub coverage_eprocess: Option<f64>,
    /// Conformal width multiplier: multiply your interval half-widths by this to
    /// hit your nominal coverage (`>1` widen, `<1` sharpen). `None` below three
    /// usable intervals. Acted on only once `coverage_eprocess` finds real evidence.
    pub width_factor: Option<f64>,
}

/// Prior strength pulling the recalibration map toward the identity — high enough
/// that a handful of resolutions barely move it (you must *earn* a correction).
pub(crate) const RECAL_RIDGE: f64 = 1.5;
/// Minimum e-value (at least *suggestive* evidence) and sample count before a
/// correction is offered — never recalibrate on noise. Shared by the report and
/// the MCP `recalibrate` tool so the two can never disagree.
pub(crate) use scoring::{RECAL_MIN_E, RECAL_MIN_N};

/// The recalibration map for the resolved binary claims matching `tag` (in
/// resolution order), together with whether the e-process has **earned** applying
/// it — real evidence (`≥ RECAL_MIN_E`) over enough samples (`≥ RECAL_MIN_N`). The
/// fitted map is returned regardless; `earned` says whether to trust it. Defined
/// once here, next to the gate constants, so the report, the MCP `recalibrate`/
/// `decide` tools, and the CLI can never disagree about when a correction is real.
pub fn earned_recalibration(
    ledger: &Ledger,
    tag: Option<&str>,
    today: NaiveDate,
) -> (Option<scoring::Recalibration>, bool, usize, Option<f64>) {
    // The gate must consume exactly the sequence the report's headline test does,
    // in the same outcome-independent order, or `decide` and `report` will
    // disagree about whether the evidence exists.
    let evidence = crate::evidence::binary_evidence(&ledger.claims, today, tag);
    // The map itself is fitted on every graded claim: more data makes a better
    // correction, and it is the *gate*, not the fit, that guards validity.
    let all: Vec<Sample> = ledger
        .claims
        .iter()
        .filter(|c| tag.is_none_or(|t| c.tags.iter().any(|x| x == t)))
        .filter_map(|c| c.sample())
        .collect();
    let n = evidence.samples.len();
    let (recal, earned, e) = scoring::gate_recalibration_seq(&all, &evidence.steps, RECAL_RIDGE);
    (recal, earned, n, e)
}

/// Bootstrap settings for the Brier band — a fixed seed makes the report
/// reproducible run-to-run (a band that jittered every run would unsettle).
const BRIER_CI_RESAMPLES: usize = 2000;
const BRIER_CI_SEED: u64 = 0xA11A_5EED_C0FF_EE00;
/// EWMA half-life (in resolutions) for the "lately" Brier, and the minimum record
/// before a recency trend is worth showing at all.
const EWMA_HALF_LIFE: f64 = 5.0;
const TREND_MIN_N: usize = 10;
/// Standardized-mean-difference threshold above which the graded and ungraded
/// forecasts count as drawn from different distributions (the conventional
/// covariate-balance / missing-not-at-random cutoff).
const SELECTION_ASMD_FLAG: f64 = 0.1;
/// Draws and seed for the MCB noise floor. Fixed, so the floor never moves under
/// a user who simply re-runs the report.
const MCB_NULL_DRAWS: usize = 400;
const MCB_NULL_SEED: u64 = 0xA11C_E5EE_D000_0001;

/// Below this many graded calls, no calibration verdict is possible at all.
pub const VERDICT_MIN_N: usize = 20;
/// And below this many, the report never says "well calibrated" — absence of
/// evidence at n = 25 is not evidence of calibration.
pub const VERDICT_CONFIDENT_N: usize = 50;
/// The e-value at which miscalibration counts as demonstrated: `1/20 = α 0.05`
/// by Ville's inequality, at any stopping time.
pub const EVIDENCE_ALARM: f64 = 20.0;

/// How much of the record has to carry a `kind:` tag before a per-type breakdown
/// is worth showing.
///
/// A breakdown over a self-selected slice is the same defect as a calibration
/// computed on a self-selected sample. Measured on a real 426-claim agent ledger,
/// **363 of 422 binary claims carried no `kind:` tag at all** — the per-kind
/// table, the per-kind e-values and the hook's "worst type" line all keyed off a
/// field 86% of the data did not have, so the machinery was inert in practice and
/// a new user's first report showed the same emptiness. Below this bar the
/// section collapses to one line saying what is missing and how to fill it.
pub const KIND_MIN_COVERAGE: f64 = 0.5;

/// How many times its own noise floor the calibration error has to reach before
/// the report says anything about it in prose.
///
/// Note what the floor *is*: the **95th percentile** of the null, i.e. a ceiling
/// only 1 calibrated forecaster in 20 exceeds — not what a calibrated forecaster
/// typically scores: measured, the median calibrated ratio is `0.70-0.80` across
/// n = 100..1000, never `1.0`. Describing it as a normal value makes every ratio
/// read as less severe than it is, which matters most in the 1.0–1.5 band where
/// most real miscalibration sits between n = 200 and n = 1000.
///
/// The floor is a **95th percentile**, so `mcb > floor` is a fixed-n test at
/// α = 0.05: about one calibrated forecaster in twenty crosses it on any given
/// look, and a well-calibrated user running `ana report` weekly will cross it
/// within months with near certainty. That is the peeking problem again, in the
/// one instrument with no anytime-valid protection — so the crossing is not
/// treated as an event. The **ratio** is printed instead, because reporting the
/// size is MCB's entire job, and prose is reserved for ratios large enough that
/// repeated looking will not produce them.
///
/// Measured at n = 200, 400 runs each (`validation/ratio.py`):
///
/// | cut | calibrated | diffuse (≤13.5 pts) | sharp (25 pts) |
/// |---|---|---|---|
/// | ≥ 1.00 | 0.060 | 0.507 | 1.000 |
/// | ≥ 1.25 | 0.010 | 0.205 | 0.998 |
/// | ≥ 1.50 | 0.000 | 0.055 | 0.993 |
pub const MCB_RATIO_NOTABLE: f64 = 1.5;

/// A breakdown needs at least two groups to be a breakdown, and few enough that
/// the multiplicity correction leaves any power.
///
/// Every per-group e-value pays a factor of `K` in its alarm threshold, so a
/// grouping with `K = 66` — which is what `session:` produces on a real agent
/// ledger, at 100% coverage — buys a 66-fold penalty and an unreadable table.
/// `who:` sits at the other end with `K = 1`, which is not a breakdown at all.
/// Bounding `K` excludes both without a hand-maintained list of "bookkeeping"
/// namespaces, and the bound is a property of the correction rather than a taste.
pub const GROUP_MIN_K: usize = 2;
pub const GROUP_MAX_K: usize = 12;

/// The calibration error as a multiple of its own noise floor, when both exist.
/// One definition, so the report, the cat and the plain view cannot disagree
/// about how big the error is.
fn mcb_ratio(d: &ReportData) -> Option<f64> {
    match (d.mcb, d.mcb_null_q95) {
        (Some(m), Some(f)) if f > 0.0 => Some(m / f),
        _ => None,
    }
}
/// How far a directional (yes/no) lean has to run before it is the headline
/// rather than a footnote.
const BIAS_DOMINATES: f64 = 0.1;
/// Below this, the confidence gap is too small to name a direction from — the
/// errors have cancelled, and the sign of what is left is noise.
const DIRECTION_MIN_GAP: f64 = 0.02;
/// Below this much discrimination, the forecasts do not order the outcomes at
/// all, and that fact outranks anything to be said about their level.
const DSC_UNINFORMATIVE: f64 = 1e-9;

/// The one calibration verdict.
///
/// Every shareable surface — the plain report and its cat, the badge SVG, the
/// HTML card, `--json`, the MCP `calibration` tool, the shell hooks, the `decide`
/// explanation — used to key off the **confidence gap**, and over- and
/// under-confidence cancel inside that single number. Measured consequence: a
/// ledger of 50 calls at 0.9 on coin flips plus 50 at 0.6 on sure things, whose
/// Brier skill is −0.520 and whose calibration error is the worst in the test
/// suite, produced a gap of −0.000000000000001 and was therefore announced as
/// `[DIALED IN] · well calibrated`, badged `Well calibrated`, and advised to
/// "keep doing what you're doing".
///
/// So the pass/fail decision is made **here, once**, from evidence (`mcb` against
/// its own noise floor, and the e-process) — never from the gap. The gap is
/// consulted only to name the *direction* of a failure already established.
#[derive(Serialize, Clone, Copy, Debug, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum Verdict {
    /// Too few graded calls to say anything.
    InsufficientData,
    /// More than one in ten of the settled claims were voided (at least
    /// [`crate::evidence::VOID_WITHHOLD_MIN`] of them), whenever the voids were made, so
    /// no reading can be trusted.
    ///
    /// Every score leaves voided claims out, which means a ledger can be made to
    /// look as good as its owner likes by voiding the misses. The tool cannot tell
    /// a bad question noticed late from a bad answer disowned, so past this share it
    /// declines to read the record at all. See [`crate::evidence::VoidAccount`].
    Withheld,
    /// No miscalibration has been demonstrated. Not the same as "calibrated":
    /// the test can miss patterns, and small records hide a lot.
    NoEvidenceOfMiscalibration,
    /// The forecasts carry no information about which calls come true: after
    /// isotonic recalibration they all collapse to one value.
    ///
    /// This outranks any statement about over- or under-confidence, including a
    /// demonstrated one. A forecaster whose confidence does not sort the outcomes
    /// has a ranking problem, and shading every number up or down cannot fix it —
    /// it just produces a well-calibrated constant. Fix the ranking first.
    CalibratedButUninformative,
    /// Demonstrably too sure of yourself.
    Overconfident,
    /// Demonstrably not sure enough.
    Underconfident,
    /// Miscalibrated with a directional lean toward YES.
    BiasedYes,
    /// Miscalibrated with a directional lean toward NO.
    BiasedNo,
    /// Demonstrably miscalibrated, with the errors running **both** ways at once
    /// — too sure at the top of the range and not sure enough at the bottom, or
    /// the reverse — so there is no single direction to shade toward.
    ///
    /// This state exists because of a measurement. The 50-coin-flips-at-0.9 plus
    /// 50-sure-things-at-0.6 ledger has a confidence gap of about −1e-15: naming
    /// a direction from it is naming the sign of floating-point noise, and the
    /// answer it happened to give ("underconfident") would have sent the reader
    /// to raise the very 0.9s that were the problem.
    MiscalibratedBothWays,
}

impl Verdict {
    /// Whether miscalibration has actually been demonstrated.
    pub fn is_miscalibrated(self) -> bool {
        matches!(
            self,
            Verdict::Overconfident
                | Verdict::Underconfident
                | Verdict::BiasedYes
                | Verdict::BiasedNo
                | Verdict::MiscalibratedBothWays
        )
    }

    /// A stable machine-readable slug, used by the hooks and the badge.
    pub fn slug(self) -> &'static str {
        match self {
            Verdict::InsufficientData => "insufficient_data",
            Verdict::Withheld => "withheld",
            Verdict::NoEvidenceOfMiscalibration => "no_evidence_of_miscalibration",
            Verdict::CalibratedButUninformative => "calibrated_but_uninformative",
            Verdict::Overconfident => "overconfident",
            Verdict::Underconfident => "underconfident",
            Verdict::BiasedYes => "biased_yes",
            Verdict::BiasedNo => "biased_no",
            Verdict::MiscalibratedBothWays => "miscalibrated_both_ways",
        }
    }

    /// The short label for the badge and the card.
    ///
    /// **Never the words "well calibrated."** Absence of evidence is not evidence
    /// of calibration, and the two instruments this report runs have opposite
    /// blind spots: the e-process is strong on sharp patterns and weak on gentle
    /// shrinkage toward 0.5, while MCB-against-its-floor measures the *size* of an
    /// error but cannot establish that it is real. Measured: a forecaster 11
    /// points overconfident at n = 160 had MCB 0.022 against a 0.011 floor — twice
    /// the noise — while the e-process sat at 16.5, under the alarm. That ledger
    /// was labelled "WELL CALIBRATED" on every surface until this was removed.
    pub fn label(self) -> &'static str {
        match self {
            Verdict::InsufficientData => "not enough data",
            Verdict::Withheld => "withheld",
            Verdict::NoEvidenceOfMiscalibration => "no miscalibration found",
            Verdict::CalibratedButUninformative => "uninformative",
            Verdict::Overconfident => "overconfident",
            Verdict::Underconfident => "underconfident",
            Verdict::BiasedYes => "leans yes",
            Verdict::BiasedNo => "leans no",
            Verdict::MiscalibratedBothWays => "miscalibrated",
        }
    }
}

/// The pseudo-namespace for bare tags — ones with no `prefix:`. A human ledger
/// tags `markets` and `tech`; an agent ledger tags `kind:tests-pass`. Both answer
/// "where in my record am I wrong", so both can drive the same breakdown.
pub const TOPIC_NS: &str = "topic";

/// The group keys a claim contributes under namespace `ns`.
///
/// The one definition of "which groups is this claim in". The descriptive
/// by-domain table and the tested breakdown both read it; they used to carry
/// separate copies of the bare-tag rule, which is how the same rows came to be
/// printed twice under two headings.
fn group_keys<'a>(c: &'a crate::model::Claim, ns: &'a str) -> impl Iterator<Item = &'a str> {
    c.tags.iter().filter_map(move |t| {
        if ns == TOPIC_NS {
            (!t.contains(':')).then_some(t.as_str())
        } else {
            t.strip_prefix(ns).and_then(|r| r.strip_prefix(':'))
        }
    })
}

/// A grouping, materialised once: its namespace, how much of the record it
/// covers, and the groups themselves, each holding its samples in evidence order
/// so a per-group e-value carries the same guarantee as the headline one.
///
/// The table, `K`, the multiplicity-corrected alarm and the hook's "worst group"
/// all read this one value. `K` is `groups.len()` and has no other definition, so
/// the correction and the display cannot come from two different groupings.
#[derive(Clone, Debug)]
struct Grouping {
    ns: String,
    coverage: f64,
    groups: BTreeMap<String, Vec<Sample>>,
    /// The partition this grouping induces on the graded claims, with the labels
    /// thrown away: each group as the sorted indices of its claims, and the groups
    /// sorted. Two namespaces that tag the same claims together have the same
    /// signature, whatever they call their groups.
    signature: Vec<Vec<usize>>,
}

impl Grouping {
    fn k(&self) -> usize {
        self.groups.len()
    }

    fn usable(&self) -> bool {
        self.coverage >= KIND_MIN_COVERAGE && (GROUP_MIN_K..=GROUP_MAX_K).contains(&self.k())
    }
}

/// Materialise the grouping namespace `ns` induces on `graded`, which must already
/// be in evidence order. `None` when no graded claim carries a tag in `ns`.
fn materialise(graded: &[&crate::model::Claim], ns: &str) -> Option<Grouping> {
    let mut groups: BTreeMap<String, Vec<Sample>> = BTreeMap::new();
    let mut members: BTreeMap<String, Vec<usize>> = BTreeMap::new();
    let mut covered = 0usize;
    for (i, c) in graded.iter().enumerate() {
        let Some(s) = c.evidence_sample() else {
            continue;
        };
        let mut any = false;
        for key in group_keys(c, ns) {
            any = true;
            groups.entry(key.to_string()).or_default().push(s);
            members.entry(key.to_string()).or_default().push(i);
        }
        covered += usize::from(any);
    }
    if groups.is_empty() {
        return None;
    }
    let mut signature: Vec<Vec<usize>> = members.into_values().collect();
    for m in &mut signature {
        m.sort_unstable();
        m.dedup();
    }
    signature.sort();
    Some(Grouping {
        ns: ns.to_string(),
        coverage: covered as f64 / graded.len() as f64,
        groups,
        signature,
    })
}

/// What the selector decided, and enough about the best candidate for a
/// collapsed section to say which bar it missed.
#[derive(Clone, Debug, Default)]
struct GroupingChoice {
    chosen: Option<Grouping>,
    /// Coverage and `K` of the chosen grouping, or of the best rejected one.
    coverage: f64,
    k: usize,
    /// The bare-tag partition over the same claims. When it equals the chosen
    /// partition, the descriptive by-domain table would repeat the breakdown.
    topic_signature: Option<Vec<Vec<usize>>>,
}

/// Which grouping this ledger can actually support.
///
/// `kind:` is preferred because it is the namespace the agent workflow writes and
/// the one the docs teach. When it is not there — measured on a real 426-claim
/// ledger, **363 of 422** binary claims carried no `kind:` tag — the breakdown
/// falls back to whichever namespace the ledger *does* populate, rather than
/// advertising a section it cannot fill.
///
/// Selection rule, in full:
///
/// 0. Candidates that induce the **same partition** of the record are one
///    candidate, represented by the first in preference order (`kind` first, then
///    namespace name ascending). `kind:alpha` alongside a bare `alpha` on every
///    claim is one grouping, not two; so are `area:` and `team:` when they always
///    agree. Duplicates have identical coverage and `K`, so this changes no
///    decision — it guarantees there is exactly one grouping to report, and one `K`.
/// 1. `kind:` when it meets both bars.
/// 2. Otherwise, among candidates meeting both bars, **highest coverage wins;
///    ties are broken by namespace name, ascending**.
/// 3. Otherwise nothing is selected and the section collapses, naming which bar
///    the best candidate missed.
///
/// The bars are coverage ≥ [`KIND_MIN_COVERAGE`] and
/// [`GROUP_MIN_K`] ≤ K ≤ [`GROUP_MAX_K`].
///
/// Selection depends on tagging behaviour, never on outcomes, so the evidence
/// ordering and its guarantee are untouched. It is spelled out and deterministic
/// so that no one has to wonder whether the grouping showing the best result is
/// the one that got picked.
fn pick_grouping(
    claims: &[crate::model::Claim],
    today: NaiveDate,
    tag: Option<&str>,
) -> GroupingChoice {
    let graded = crate::evidence::binary_evidence_claims(claims, today, tag);
    if graded.is_empty() {
        return GroupingChoice::default();
    }

    // Every namespace present, bare tags included, in the preference order the
    // rule fixes before any result is looked at: `kind` first, then by name.
    let mut namespaces: Vec<String> = graded
        .iter()
        .flat_map(|c| c.tags.iter())
        .map(|t| match t.split_once(':') {
            Some((ns, _)) => ns.to_string(),
            None => TOPIC_NS.to_string(),
        })
        .collect();
    namespaces.sort_by(|a, b| {
        (a.as_str() != "kind")
            .cmp(&(b.as_str() != "kind"))
            .then(a.cmp(b))
    });
    namespaces.dedup();

    // One representative per induced partition: the first in preference order.
    let mut candidates: Vec<Grouping> = Vec::new();
    let mut topic_signature = None;
    for ns in &namespaces {
        let Some(g) = materialise(&graded, ns) else {
            continue;
        };
        if ns.as_str() == TOPIC_NS {
            topic_signature = Some(g.signature.clone());
        }
        if candidates.iter().all(|c| c.signature != g.signature) {
            candidates.push(g);
        }
    }

    // Ranking by coverage, then name, serves both rule 2 and the collapsed
    // section's "best candidate".
    let mut ranked: Vec<&Grouping> = candidates.iter().collect();
    ranked.sort_by(|a, b| b.coverage.total_cmp(&a.coverage).then(a.ns.cmp(&b.ns)));

    let chosen = candidates
        .iter()
        .find(|g| g.ns == "kind" && g.usable())
        .or_else(|| ranked.iter().copied().find(|g| g.usable()))
        .cloned();

    match (chosen, ranked.first()) {
        (Some(g), _) => GroupingChoice {
            coverage: g.coverage,
            k: g.k(),
            chosen: Some(g),
            topic_signature,
        },
        (None, Some(best)) => GroupingChoice {
            chosen: None,
            coverage: best.coverage,
            k: best.k(),
            topic_signature,
        },
        (None, None) => GroupingChoice {
            topic_signature,
            ..GroupingChoice::default()
        },
    }
}

/// Decide the verdict from evidence alone.
///
/// Inputs: `n` graded calls, the CORP miscalibration and its noise floor, the
/// discrimination, the e-value, and — for *direction only* — the confidence gap
/// and directional bias.
#[allow(clippy::too_many_arguments)]
pub fn verdict_from(
    n: usize,
    mcb: Option<f64>,
    mcb_floor: Option<f64>,
    dsc: Option<f64>,
    eprocess: Option<f64>,
    confidence_gap: Option<f64>,
    directional_bias: Option<f64>,
    distinct_forecasts: usize,
    voids_withhold: bool,
) -> Verdict {
    // Before anything else, the number of calls included: the numbers below are computed
    // from a record the owner may have edited. Voiding the misses of a new ledger, whose
    // claims are not due yet, used to read "not enough data" over a Brier of 0.010.
    if voids_withhold {
        return Verdict::Withheld;
    }
    if n < VERDICT_MIN_N {
        return Verdict::InsufficientData;
    }
    let demonstrated = eprocess.is_some_and(|e| e >= EVIDENCE_ALARM);
    let above_floor = match (mcb, mcb_floor) {
        (Some(m), Some(f)) => m > f,
        (Some(m), None) => m > 0.0,
        _ => false,
    };

    // Ranking outranks calibration, whenever the forecasts sort nothing.
    //
    // On the 90%-coin-flips-plus-60%-sure-things ledger, DSC is exactly 0.0000:
    // the isotonic fit collapses every forecast to one value because higher
    // stated confidence went with a LOWER hit rate. The honest statement there is
    // not about confidence levels at all — it is that the ordering carries no
    // information, and advice about shading numbers up or down is premature. Fix
    // the ranking first; calibrating an uninformative forecast just produces a
    // well-calibrated constant.
    //
    // The guard on `distinct_forecasts` matters: with a single forecast value
    // DSC is zero by construction, because there is nothing to rank. Telling
    // someone who said 0.9 to everything and was right a third of the time to
    // "fix the ranking" would be useless — the finding there really is the level.
    if distinct_forecasts >= 2 && dsc.is_some_and(|d| d.abs() < DSC_UNINFORMATIVE) {
        return Verdict::CalibratedButUninformative;
    }

    if demonstrated && above_floor {
        // Real miscalibration. Now, and only now, look at the direction.
        let bias = directional_bias.unwrap_or(0.0);
        if bias.abs() >= BIAS_DOMINATES && bias.abs() > confidence_gap.map_or(0.0, f64::abs) {
            return if bias > 0.0 {
                Verdict::BiasedYes
            } else {
                Verdict::BiasedNo
            };
        }
        // A direction is only worth naming when there is one. Below this, the
        // over- and under-confident halves have cancelled and the sign of the
        // remainder is noise.
        let gap = confidence_gap.unwrap_or(0.0);
        if gap.abs() < DIRECTION_MIN_GAP {
            return Verdict::MiscalibratedBothWays;
        }
        return if gap > 0.0 {
            Verdict::Overconfident
        } else {
            Verdict::Underconfident
        };
    }

    // Nothing demonstrated, and the forecasts sort nothing: the textbook
    // calibrated-but-useless case, saying 0.5 to everything on a fair coin. It
    // reaches here rather than the check above because with a single forecast
    // value there was never anything to rank.
    //
    // Not when the level is visibly off, though: 50 calls at 0.9 that came true 80% of
    // the time also sort nothing (one value), and were told "right on average" with the
    // calibration error at 1.56x its floor. That is the level, not the ranking.
    let level_off =
        matches!((mcb, mcb_floor), (Some(m), Some(f)) if f > 0.0 && m / f >= MCB_RATIO_NOTABLE);
    if !level_off && dsc.is_some_and(|d| d.abs() < DSC_UNINFORMATIVE) {
        return Verdict::CalibratedButUninformative;
    }
    Verdict::NoEvidenceOfMiscalibration
}

/// A learned recalibration map, machine-readable: `p ↦ σ(a + b·logit p)` plus a
/// few worked corrections for the human view.
#[derive(Serialize, Clone, Debug)]
pub struct RecalData {
    /// Log-odds bias (`≠ 0` ⇒ over/under-confident on average).
    pub a: f64,
    /// Slope (`< 1` ⇒ too extreme, `> 1` ⇒ too timid).
    pub b: f64,
    pub n: usize,
    /// `(stated, recalibrated)` pairs — what your stated confidences *should* be.
    pub examples: Vec<(f64, f64)>,
}

/// Resolution-discipline / selection-bias diagnostic: is the calibration above
/// computed on a fair sample of your calls, or a self-selected one? Every metric
/// rests only on *resolved* claims; if resolution is non-random (you grade your wins
/// and let your misses rot), the numbers flatter you. This is the honesty check.
#[derive(Serialize, Clone, Debug)]
pub struct ResolutionDiscipline {
    /// Resolved / (resolved + open) across all matching claims. Low ⇒ the report
    /// rests on a self-selected subset.
    pub resolution_rate: f64,
    pub resolved: usize,
    pub open: usize,
    /// Open claims already past their `resolve_by` date — rotting in the drawer
    /// rather than legitimately pending.
    pub overdue: usize,
    /// Mean boldness of resolved vs. still-open binary forecasts — the confidence
    /// profile of what you graded vs. what you didn't. `None` when a side is empty.
    pub resolved_boldness: Option<f64>,
    pub open_boldness: Option<f64>,
    /// Resolutions that were graded from an observed fact rather than the
    /// forecaster's own word — a test run's exit status, say. "Why trust a
    /// self-graded ledger?" is the first fair objection, and this is the part of
    /// the answer that is a number.
    pub auto_graded: usize,
    /// Of `auto_graded`, those pinned with `--check` when they were logged, so the
    /// command was fixed before the outcome. The rest were graded by whichever plain
    /// test run the hook saw next.
    pub auto_pinned: usize,
    /// Standardized gap (ASMD) between those two boldness profiles — the
    /// missing-not-at-random diagnostic. `> 0.1` ⇒ your open and graded calls differ
    /// enough that the split is unlikely to be random. `None` below two per side.
    pub boldness_asmd: Option<f64>,
}

/// Selective-prediction summary: how your error falls when you act only on your
/// most-confident calls.
#[derive(Serialize, Clone, Debug)]
pub struct SelectiveData {
    /// Directional error acting on every call.
    pub risk_full: f64,
    /// Directional error acting only on your most-confident half.
    pub risk_half: f64,
    /// Area under the risk–coverage curve (lower ⇒ confidence ranks reliably).
    pub aurcc: f64,
}

/// One graded call, listed while there are too few for a verdict: a new user's first
/// result. The id, never the statement: this data also reaches a model through the MCP
/// `calibration` tool, and ledger text goes out only through `untrusted::line`.
#[derive(Serialize, Clone, Debug, PartialEq)]
pub struct GradedCall {
    pub id: String,
    pub prob: f64,
    pub came_true: bool,
    pub brier: f64,
}

/// How many graded calls the day-one list shows.
pub const SO_FAR_MAX: usize = 8;

/// The whole report as data — serialisable, and the single input to both views.
#[derive(Serialize, Clone, Debug)]
pub struct ReportData {
    pub tag: Option<String>,
    /// Resolved claims of **every** kind. Header arithmetic uses this, so that
    /// `resolved + open == total` actually holds: the header used to print a
    /// binary-only "resolved" beside an all-kinds "open", which is how the demo
    /// ledger came to announce `35 resolved · 6 open` for 50 claims.
    pub resolved: usize,
    /// Resolved binary claims — the `n` behind every probability metric.
    pub resolved_binary: usize,
    /// Resolved numeric (interval) claims — the `n` behind the interval metrics.
    pub resolved_numeric: usize,
    /// Open claims of every kind.
    pub open: usize,
    /// Every matching claim, resolved or not. Always `resolved + open`.
    pub total: usize,
    pub first_recorded: Option<String>,
    pub last_recorded: Option<String>,
    pub brier: Option<f64>,
    pub log_score: Option<f64>,
    pub brier_skill: Option<f64>,
    pub base_rate: Option<f64>,
    /// 95% Wilson interval on the base rate — how firmly this many resolutions
    /// pin the rate down (a wide interval means too few samples to trust).
    pub base_rate_ci: Option<(f64, f64)>,
    pub reliability: Option<f64>,
    pub resolution: Option<f64>,
    pub uncertainty: Option<f64>,
    pub auc: Option<f64>,
    pub confidence_gap: Option<f64>,
    pub mean_confidence: Option<f64>,
    pub accuracy: Option<f64>,
    pub directional_bias: Option<f64>,
    pub calibration: Vec<BinData>,
    pub by_tag: Vec<TagStat>,
    /// True when `by_tag` was emptied because the chosen breakdown induces the
    /// same partition of the record, so there is one table rather than the same
    /// rows twice under two headings.
    pub by_tag_merged_into_group: bool,
    /// Per-`kind:` breakdown — calibration by *type* of prediction
    /// (estimate / tests-pass / bug-hypothesis …): the agent-facing view.
    pub by_kind: Vec<TagStat>,
    /// Which tag namespace the breakdown is grouped by — `"kind"` when that covers
    /// the record, else the best-covered namespace, `"topic"` for bare tags.
    /// `None` when nothing reaches [`KIND_MIN_COVERAGE`] and the section collapses.
    pub group_by: Option<String>,
    /// Fraction of graded binary calls carrying a tag in the chosen namespace (or
    /// the best candidate's coverage when none qualified). The breakdown is
    /// suppressed below [`KIND_MIN_COVERAGE`] rather than describing a
    /// self-selected slice as if it were the record.
    pub group_coverage: f64,
    /// `K`, the number of groups. It sets the multiplicity-corrected alarm in
    /// [`Self::kind_alarm_threshold`], so it is reported rather than implied — a
    /// threshold nobody can see is a threshold nobody can check.
    pub group_k: usize,
    pub mind_changing: Option<MindChange>,
    pub numeric: Option<NumericData>,
    /// Anytime-valid calibration e-value — evidence that you are *mis*calibrated,
    /// valid no matter how often you check it. `≥ 20` ⇒ significant at α = 0.05.
    pub eprocess: Option<f64>,
    /// The e→p calibrated, optional-stopping-valid p-value (`1/eprocess`).
    pub eprocess_pvalue: Option<f64>,
    /// The learned correction to apply to your stated probabilities.
    pub recalibration: Option<RecalData>,
    /// Bootstrap percentile band on the Brier score — how far luck alone could
    /// move it. `None` for fewer than two resolutions.
    pub brier_ci: Option<(f64, f64)>,
    /// Recency-weighted (EWMA) Brier — "how am I doing *lately*", read against
    /// `brier`. Descriptive trend, not a significance test.
    pub recent_brier: Option<f64>,
    /// Distinct forecast probabilities used — a coarse vocabulary caps resolution.
    pub distinct_forecasts: usize,
    /// Selective-prediction summary — error among your surest calls vs all.
    pub selective: Option<SelectiveData>,
    /// Stake-weighted Brier — present only when stakes vary; compare with `brier`
    /// to see whether you are worse on the calls that actually matter.
    pub weighted_brier: Option<f64>,
    /// Resolution-discipline / selection-bias check — whether the metrics above rest
    /// on a fair sample of your calls or a self-selected one.
    pub resolution_discipline: Option<ResolutionDiscipline>,

    // ── P0-2: which forecast the headline score is computed on ──────────────
    /// Always `"first"`. The graded forecast is the one made *before* the answer
    /// was known; see [`crate::model::Claim::sample_final`] for why.
    pub score_basis: &'static str,
    /// The headline Brier, on first forecasts. Equal to `brier`.
    pub brier_first: Option<f64>,
    /// Brier on the final forecast — shown for comparison, never graded.
    pub brier_final: Option<f64>,
    /// Brier weighted by how long each forecast stood. Secondary metric.
    pub brier_time_avg: Option<f64>,
    /// Resolved claims carrying a forecast made too close to the answer to grade.
    pub late_updates: usize,

    // ── P0-4: the CORP decomposition ────────────────────────────────────────
    /// Miscalibration (CORP). Replaces `reliability` as the calibration number.
    pub mcb: Option<f64>,
    /// Discrimination (CORP). `0` ⇒ your confidence says nothing about which
    /// calls come true.
    pub dsc: Option<f64>,
    /// Uncertainty (CORP) — identical in meaning to `uncertainty`.
    pub unc: Option<f64>,
    /// The 95th percentile of `mcb` for a *calibrated* forecaster making exactly
    /// these calls: the noise floor below which `mcb` means nothing.
    pub mcb_null_q95: Option<f64>,

    // ── P0-3: what the evidence test actually consumed ──────────────────────
    /// Claims in the evidence sequence (due, graded, in deadline order).
    pub evidence_n: usize,
    /// Id of the first overdue, ungraded claim — the evidence pauses there.
    pub evidence_oldest_gap: Option<String>,
    /// Id of the first claim whose due date has passed and which is still
    /// How much wealth the ungraded backlog is costing, as a natural-log factor
    /// on the e-value. Gaps only ever shrink it, so this is a price, not a risk.
    pub evidence_gap_cost_log: Option<f64>,
    /// Whether the blocking claim has no `--by` date, in which case adding one is
    /// the other way to unblock the sequence.
    pub evidence_gap_without_deadline: bool,
    /// How many due claims are ungraded in total, not just the first. Reported
    /// beside `evidence_n` so "22 of 301" reads as a backlog with an exit rather
    /// than as a broken metric.
    pub evidence_ungraded_due: usize,
    /// Resolved claims not yet due, so not yet in the test: (count, first, last due date).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub evidence_pending: Option<(usize, NaiveDate, NaiveDate)>,
    /// Claims voided *after* they had already resolved — outcomes deleted from
    /// the record after being seen. They stay in the evidence sequence; this
    /// count exists so the edit is never silent.
    pub voided_after_resolution: usize,
    /// Every void in scope, and how many came after the claim was due or had
    /// resolved. Past one late void in ten, the verdict is withheld.
    pub voids: crate::evidence::VoidAccount,
    /// `ln` of the e-value, for comparing magnitudes past the display cap.
    pub eprocess_log: Option<f64>,
    /// The e-value a single per-kind subgroup must clear, after the union-bound
    /// correction for having searched `K` subgroups.
    pub kind_alarm_threshold: Option<f64>,

    // ── P0-5: the one verdict every surface must agree with ─────────────────
    /// The single calibration verdict. Every surface — text, cat, badge, card,
    /// JSON, hooks, `decide` — derives its wording from this and nothing else.
    pub verdict: Verdict,
    /// Under "no miscalibration found" only: the share of simulated forecasters with
    /// these forecasts, but [`SENSITIVITY_SHRINK`] too extreme, that the test would flag.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sensitivity: Option<f64>,
    /// Graded calls said at [`EASY_P`] or more (or its mirror), and the Brier of the rest
    /// when at least [`CONTESTED_MIN_N`] remain. A record padded with sure things scores
    /// well and says little: 40 trivially true calls at 0.97 drew "100/100".
    pub easy_calls: usize,
    /// The latest graded binary calls, newest first, while there are fewer than
    /// `VERDICT_MIN_N`; empty after that, when the verdict speaks for them.
    pub so_far: Vec<GradedCall>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub brier_contested: Option<f64>,
}

/// A forecast this sure is close to a free point: [`ReportData::easy_calls`].
pub const EASY_P: f64 = 0.95;
/// Fewest contested calls worth scoring on their own.
pub const CONTESTED_MIN_N: usize = 5;
/// From this share of easy calls up, the report says so.
pub const EASY_SHARE_NOTE: f64 = 0.3;

/// The error the sensitivity line is about: numbers 30% further from 50/50 than the truth.
pub const SENSITIVITY_SHRINK: f64 = 0.3;

/// The friendliest cat needs a test that would have caught an error of
/// [`SENSITIVITY_SHRINK`] at least this often.
pub const DIALED_MIN_SENSITIVITY: f64 = 0.8;

impl ReportData {
    /// Compute every metric once, for the binary and numeric claims that match
    /// the optional tag filter. `today` anchors the overdue check (real wall-clock
    /// in the CLI; a fixed date in tests).
    pub fn compute(
        ledger: &Ledger,
        tag_filter: Option<&str>,
        bins: usize,
        today: NaiveDate,
    ) -> ReportData {
        let tag_filter = tag_filter.map(|t| t.to_lowercase());
        let matches_tag = |c: &&crate::model::Claim| match &tag_filter {
            Some(t) => c.tags.iter().any(|x| x == t),
            None => true,
        };

        // Voided claims are excluded everywhere: from the scores, from the counts,
        // and from the resolution-discipline check. They stay in the ledger.
        let resolved_claims: Vec<&crate::model::Claim> = ledger
            .claims
            .iter()
            .filter(|c| c.is_resolved() && !c.is_void())
            .filter(matches_tag)
            .collect();
        let samples: Vec<Sample> = resolved_claims.iter().filter_map(|c| c.sample()).collect();
        let so_far: Vec<GradedCall> = if samples.len() < VERDICT_MIN_N {
            let mut graded: Vec<(&crate::model::Claim, Sample)> = resolved_claims
                .iter()
                .filter_map(|c| c.sample().map(|s| (*c, s)))
                .collect();
            graded.sort_by_key(|(c, _)| std::cmp::Reverse(c.resolution.as_ref().map(|r| r.at)));
            graded
                .into_iter()
                .take(SO_FAR_MAX)
                .map(|(c, s)| GradedCall {
                    id: c.id.clone(),
                    prob: s.prob,
                    came_true: s.outcome > 0.5,
                    brier: (s.prob - s.outcome).powi(2),
                })
                .collect()
        } else {
            Vec::new()
        };
        let is_easy = |s: &Sample| s.prob >= EASY_P || s.prob <= 1.0 - EASY_P;
        let easy_calls = samples.iter().filter(|s| is_easy(s)).count();
        let contested: Vec<Sample> = samples.iter().filter(|s| !is_easy(s)).cloned().collect();
        let brier_contested = (contested.len() >= CONTESTED_MIN_N)
            .then(|| scoring::brier(&contested))
            .flatten();
        let numeric_samples: Vec<NumericSample> = resolved_claims
            .iter()
            .filter_map(|c| c.numeric_sample())
            .collect();
        let open_claims: Vec<&crate::model::Claim> = ledger
            .claims
            .iter()
            .filter(|c| c.is_open() && !c.is_void())
            .filter(matches_tag)
            .collect();
        let open = open_claims.len();

        let (first_recorded, last_recorded) = {
            let dates: Vec<_> = resolved_claims
                .iter()
                .map(|c| c.created_at.date_naive())
                .collect();
            (
                dates.iter().min().map(|d| d.to_string()),
                dates.iter().max().map(|d| d.to_string()),
            )
        };

        // The evidence sequence: ordered by resolve-by date, which is fixed when
        // the claim is created. Sorting by resolution time instead looks
        // chronological but is outcome-dependent — YES answers arrive early and
        // NO answers wait for the deadline — and that made a perfectly calibrated
        // forecaster raise a false alarm in 100% of simulated runs when the
        // report was re-read as claims resolved. See `crate::evidence`.
        let evidence =
            crate::evidence::binary_evidence(&ledger.claims, today, tag_filter.as_deref());
        let chrono_samples: Vec<Sample> = evidence.samples.clone();
        let voids = crate::evidence::void_account(&ledger.claims, today, tag_filter.as_deref());
        let evidence_pending =
            crate::evidence::pending_due(&ledger.claims, today, tag_filter.as_deref());

        // The descriptive "lately" trend is not a test and carries no validity
        // claim, so it may keep using the order outcomes were learned in.
        let mut chrono: Vec<&crate::model::Claim> = resolved_claims.clone();
        chrono.sort_by_key(|c| c.resolution.as_ref().map(|r| r.at));
        let recent_samples: Vec<Sample> = chrono.iter().filter_map(|c| c.sample()).collect();

        let decomp = scoring::decompose(&samples);
        let over = scoring::overconfidence(&samples);
        let overall_acc = over.map(|o| o.accuracy); // shrinkage prior for per-slice gaps

        let calibration = scoring::calibration_curve(&samples, bins)
            .into_iter()
            .map(|b| BinData {
                lo: b.lo,
                hi: b.hi,
                count: b.count,
                mean_pred: (b.count > 0).then_some(b.mean_pred),
                observed: finite(b.observed),
            })
            .collect();

        // By tag (only when not already filtered to a single tag).
        let by_tag = if tag_filter.is_some() {
            Vec::new()
        } else {
            let mut map: BTreeMap<&str, Vec<Sample>> = BTreeMap::new();
            for c in &chrono {
                if let Some(s) = c.sample() {
                    // Bare tags, by the same definition the breakdown uses.
                    for t in group_keys(c, TOPIC_NS) {
                        map.entry(t).or_default().push(s);
                    }
                }
            }
            let mut rows: Vec<TagStat> = map
                .into_iter()
                .map(|(tag, s)| {
                    let oc = scoring::overconfidence(&s);
                    let gap_shrunk = match (oc, overall_acc) {
                        (Some(o), Some(pa)) => Some(
                            o.mean_confidence
                                - scoring::shrink_toward(
                                    o.accuracy * s.len() as f64,
                                    s.len(),
                                    pa,
                                    4.0,
                                ),
                        ),
                        _ => oc.map(|o| o.gap),
                    };
                    TagStat {
                        tag: tag.to_string(),
                        n: s.len(),
                        brier: scoring::brier(&s),
                        confidence_gap: oc.map(|o| o.gap),
                        confidence_gap_shrunk: gap_shrunk,
                        eprocess: None, // surfaced only for the per-kind view
                    }
                })
                .collect();
            rows.sort_by(|a, b| b.n.cmp(&a.n).then(a.tag.cmp(&b.tag)));
            rows
        };

        // The per-group breakdown, keyed off whichever grouping this ledger
        // actually populates. ONE selector call decides the namespace, builds the
        // groups and fixes K; the table, the alarm threshold and the hook all read
        // that one result, so K and the rows cannot come from different groupings.
        let choice = pick_grouping(&ledger.claims, today, tag_filter.as_deref());
        let group_by = choice.chosen.as_ref().map(|g| g.ns.clone());
        let group_coverage = choice.coverage;
        // The descriptive by-domain table is the bare-tag partition. When the tested
        // breakdown already induces that same partition — under any name, `kind:`
        // included — it would print the same rows under a second heading. Decided
        // here, by comparing partitions over the graded evidence claims, and not in
        // a renderer by comparing names.
        let by_tag_merged_into_group = matches!(
            (&choice.chosen, &choice.topic_signature),
            (Some(g), Some(t)) if &g.signature == t
        );
        let by_tag = if by_tag_merged_into_group {
            Vec::new()
        } else {
            by_tag
        };
        let by_kind = {
            let map: BTreeMap<&str, Vec<Sample>> = choice
                .chosen
                .as_ref()
                .map(|g| {
                    g.groups
                        .iter()
                        .map(|(k, s)| (k.as_str(), s.clone()))
                        .collect()
                })
                .unwrap_or_default();
            let mut rows: Vec<TagStat> = map
                .into_iter()
                .map(|(tag, s)| {
                    let oc = scoring::overconfidence(&s);
                    let gap_shrunk = match (oc, overall_acc) {
                        (Some(o), Some(pa)) => Some(
                            o.mean_confidence
                                - scoring::shrink_toward(
                                    o.accuracy * s.len() as f64,
                                    s.len(),
                                    pa,
                                    4.0,
                                ),
                        ),
                        _ => oc.map(|o| o.gap),
                    };
                    TagStat {
                        tag: tag.to_string(),
                        n: s.len(),
                        brier: scoring::brier(&s),
                        confidence_gap: oc.map(|o| o.gap),
                        confidence_gap_shrunk: gap_shrunk,
                        // Per-kind anytime-valid evidence, on the evidence
                        // sequence. Because K subgroups are searched at once,
                        // a single row must clear `EVIDENCE_ALARM × K` — a
                        // union bound on top of Ville — before it counts as a
                        // finding rather than a description.
                        eprocess: scoring::calibration_eprocess_v2(&s),
                    }
                })
                .collect();
            rows.sort_by(|a, b| b.n.cmp(&a.n).then(a.tag.cmp(&b.tag)));
            rows
        };

        // 95% Wilson interval on the base rate — surfaces small-n uncertainty.
        let base_rate_ci = {
            let k: f64 = samples.iter().map(|s| s.outcome).sum();
            scoring::wilson_interval(k, samples.len(), 1.96)
        };

        // Mind-changing (revised, resolved binary claims).
        let revised: Vec<&crate::model::Claim> = resolved_claims
            .iter()
            .copied()
            .filter(|c| c.was_revised() && c.sample().is_some())
            .collect();
        let mind_changing = if revised.is_empty() {
            None
        } else {
            let mut first = Vec::new();
            let mut last = Vec::new();
            for c in &revised {
                let happened = c.outcome().unwrap().happened();
                first.push(Sample::new(c.first_prob().unwrap(), happened));
                last.push(Sample::new(c.current_prob().unwrap(), happened));
            }
            let bf = scoring::brier(&first).unwrap();
            let bl = scoring::brier(&last).unwrap();
            Some(MindChange {
                revised: revised.len(),
                brier_first: bf,
                brier_last: bl,
                improvement: bf - bl,
            })
        };

        // Numeric / interval forecasts.
        let numeric = if numeric_samples.is_empty() {
            None
        } else {
            let n = numeric_samples.len() as f64;
            let mean_winkler = numeric_samples.iter().map(scoring::winkler).sum::<f64>() / n;
            // Unitless, skipping zero-width intervals where it is undefined.
            let mut ratios: Vec<f64> = numeric_samples
                .iter()
                .filter_map(scoring::winkler_ratio)
                .collect();
            ratios.sort_by(f64::total_cmp);
            let mean_winkler_ratio =
                (!ratios.is_empty()).then(|| ratios.iter().sum::<f64>() / ratios.len() as f64);
            let median_winkler_ratio = (!ratios.is_empty()).then(|| {
                let m = ratios.len() / 2;
                if ratios.len().is_multiple_of(2) {
                    (ratios[m - 1] + ratios[m]) / 2.0
                } else {
                    ratios[m]
                }
            });
            let nominal = numeric_samples.iter().map(|s| s.level).sum::<f64>() / n;
            let cov = scoring::coverage(&numeric_samples).unwrap_or(f64::NAN);
            let width = numeric_samples.iter().map(|s| s.width()).sum::<f64>() / n;
            // Jeffreys-shrunk coverage point: (k+½)/(n+1), de-noising tiny records.
            let contained = numeric_samples.iter().filter(|s| s.contains()).count() as f64;
            let coverage_shrunk =
                scoring::shrink_toward(contained, numeric_samples.len(), 0.5, 1.0);
            // Coverage is itself a calibration question: did each interval, at its
            // stated level, contain the truth? Reuse the binary e-process on
            // (prob = level, outcome = contained) for an anytime-valid coverage test.
            let coverage_samples: Vec<Sample> = numeric_samples
                .iter()
                .map(|s| Sample::new(s.level, s.contains()))
                .collect();
            Some(NumericData {
                count: numeric_samples.len(),
                mean_winkler,
                mean_winkler_ratio,
                median_winkler_ratio,
                nominal_coverage: nominal,
                empirical_coverage: cov,
                coverage_gap: cov - nominal,
                mean_width: width,
                coverage_shrunk,
                coverage_eprocess: scoring::calibration_eprocess_v2(&coverage_samples),
                width_factor: scoring::conformal_width_factor(&numeric_samples),
            })
        };

        // Anytime-valid calibration test, over the outcome-independent evidence
        // sequence, mixing betting strategies so that symmetric overconfidence
        // (too sure at 0.9 AND too sure at 0.1) cannot cancel itself out.
        // Gaps are priced at their worst case rather than halting the sequence:
        // stopping gave a 35%-ungraded ledger ~2 usable claims however much it
        // held. `gap_cost_log` is what that backlog is costing, in log e.
        let eprocess = scoring::calibration_eprocess_seq(&evidence.steps);
        let eprocess_log = scoring::calibration_log_eprocess_seq(&evidence.steps);
        let gap_cost_log = match (
            eprocess_log,
            scoring::calibration_log_eprocess(&chrono_samples),
        ) {
            (Some(with_gaps), Some(graded_only)) => Some(graded_only - with_gaps),
            _ => None,
        };
        let eprocess_pvalue = eprocess.map(scoring::eprocess_pvalue);

        // CORP decomposition and the noise floor its value has to clear.
        let corp = scoring::corp_brier(&samples);
        let mcb_null_q95 =
            scoring::mcb_null_quantile(&samples, MCB_NULL_DRAWS, 0.95, MCB_NULL_SEED);

        // P0-2: the headline is the FIRST forecast; these are the comparisons.
        let final_samples: Vec<Sample> = resolved_claims
            .iter()
            .filter_map(|c| c.sample_final())
            .collect();
        let brier_final = scoring::brier(&final_samples);
        let time_avg: Vec<f64> = resolved_claims
            .iter()
            .filter_map(|c| c.brier_time_averaged())
            .collect();
        let brier_time_avg =
            (!time_avg.is_empty()).then(|| time_avg.iter().sum::<f64>() / time_avg.len() as f64);
        let late_updates = resolved_claims
            .iter()
            .filter(|c| c.has_late_update())
            .count();

        // Learned recalibration map (ridge-shrunk toward identity for small n).
        let recalibration = scoring::fit_recalibration(&samples, RECAL_RIDGE).map(|r| RecalData {
            a: r.a,
            b: r.b,
            n: r.n,
            examples: [0.5, 0.6, 0.7, 0.8, 0.9]
                .iter()
                .map(|&p| (p, r.apply(p)))
                .collect(),
        });

        // Small-sample / over-time bands (chrono order reused from the e-process).
        let brier_ci =
            scoring::brier_ci_bootstrap(&samples, 0.95, BRIER_CI_RESAMPLES, BRIER_CI_SEED);
        let recent_brier = scoring::ewma_brier(&recent_samples, EWMA_HALF_LIFE);
        let distinct_forecasts = scoring::distinct_forecasts(&samples);
        let selective = scoring::risk_coverage(&samples).map(|rc| SelectiveData {
            risk_full: rc.risk_at_full,
            risk_half: rc.risk_at(0.5),
            aurcc: rc.aurcc,
        });

        // Stake-weighted Brier — only meaningful (and only shown) when stakes vary.
        let stakes: Vec<f64> = resolved_claims
            .iter()
            .filter_map(|c| c.sample().map(|_| c.stake))
            .collect();
        let weighted_brier = if stakes.iter().any(|&w| (w - 1.0).abs() > 1e-9) {
            scoring::brier_weighted(&samples, &stakes)
        } else {
            None
        };

        // Resolution discipline: is the calibration above a fair sample, or only the
        // calls I bothered to grade? Compares the confidence profile of resolved vs.
        // still-open binary forecasts (outcome-free, so the open side is usable).
        let resolution_discipline = {
            let total = resolved_claims.len() + open_claims.len();
            (total > 0).then(|| {
                let overdue = open_claims
                    .iter()
                    .filter(|c| matches!(c.resolve_by, Some(d) if d <= today))
                    .count();
                let resolved_probs: Vec<f64> = resolved_claims
                    .iter()
                    .filter_map(|c| c.current_prob())
                    .collect();
                let open_probs: Vec<f64> = open_claims
                    .iter()
                    .filter_map(|c| c.current_prob())
                    .collect();
                ResolutionDiscipline {
                    resolution_rate: resolved_claims.len() as f64 / total as f64,
                    resolved: resolved_claims.len(),
                    open: open_claims.len(),
                    overdue,
                    auto_graded: resolved_claims
                        .iter()
                        .filter(|c| {
                            c.resolution.as_ref().and_then(|r| r.resolved_by)
                                == Some(crate::model::ResolvedBy::Auto)
                        })
                        .count(),
                    auto_pinned: resolved_claims
                        .iter()
                        .filter(|c| {
                            c.check.is_some()
                                && c.resolution.as_ref().and_then(|r| r.resolved_by)
                                    == Some(crate::model::ResolvedBy::Auto)
                        })
                        .count(),
                    resolved_boldness: scoring::mean_boldness(&resolved_probs),
                    open_boldness: scoring::mean_boldness(&open_probs),
                    boldness_asmd: scoring::asmd(&resolved_probs, &open_probs),
                }
            })
        };

        let by_kind_len = by_kind.len();
        // K, defined once: the number of groups the chosen grouping produced or,
        // when none was chosen, the group count of the best rejected candidate.
        let group_k = if choice.chosen.is_some() {
            by_kind_len
        } else {
            choice.k
        };
        let by_kind_len_zero = by_kind_len == 0;

        let verdict = verdict_from(
            chrono_samples.len(),
            corp.as_ref().map(|c| c.mcb),
            mcb_null_q95,
            corp.as_ref().map(|c| c.dsc),
            eprocess,
            over.map(|o| o.gap),
            scoring::directional_bias(&samples),
            distinct_forecasts,
            voids.withholds_verdict(),
        );
        // How loud a real error would have been, said beside the one verdict that is a
        // silence. Only computed there, and kept cheap: about 400,000 simulated steps.
        let sensitivity = (verdict == Verdict::NoEvidenceOfMiscalibration)
            .then(|| {
                let n = evidence.steps.len().max(1);
                let sims = (400_000 / n).min(200);
                (sims >= 40)
                    .then(|| {
                        scoring::detection_rate(
                            &evidence.steps,
                            SENSITIVITY_SHRINK,
                            EVIDENCE_ALARM,
                            sims,
                            0x5EED_0A4A,
                        )
                    })
                    .flatten()
            })
            .flatten();
        ReportData {
            tag: tag_filter,
            resolved: resolved_claims.len(),
            resolved_binary: samples.len(),
            resolved_numeric: numeric_samples.len(),
            open,
            total: resolved_claims.len() + open,
            first_recorded,
            last_recorded,
            brier: scoring::brier(&samples),
            log_score: scoring::log_score(&samples, 1e-6),
            brier_skill: scoring::skill_score(&samples),
            base_rate: scoring::base_rate(&samples),
            base_rate_ci,
            reliability: decomp.map(|d| d.reliability),
            resolution: decomp.map(|d| d.resolution),
            uncertainty: decomp.map(|d| d.uncertainty),
            auc: scoring::auc(&samples),
            confidence_gap: over.map(|o| o.gap),
            mean_confidence: over.map(|o| o.mean_confidence),
            accuracy: over.map(|o| o.accuracy),
            directional_bias: scoring::directional_bias(&samples),
            calibration,
            by_tag,
            by_tag_merged_into_group,
            by_kind,
            group_by,
            group_coverage,
            group_k,
            mind_changing,
            numeric,
            eprocess,
            eprocess_pvalue,
            recalibration,
            brier_ci,
            recent_brier,
            distinct_forecasts,
            selective,
            weighted_brier,
            resolution_discipline,

            score_basis: "first",
            brier_first: scoring::brier(&samples),
            brier_final,
            brier_time_avg,
            late_updates,

            mcb: corp.as_ref().map(|c| c.mcb),
            dsc: corp.as_ref().map(|c| c.dsc),
            unc: corp.as_ref().map(|c| c.unc),
            mcb_null_q95,

            evidence_n: evidence.samples.len(),
            evidence_oldest_gap: evidence.oldest_gap.clone(),
            evidence_gap_cost_log: gap_cost_log,
            evidence_gap_without_deadline: evidence.oldest_gap_without_deadline,
            evidence_ungraded_due: evidence.ungraded_due,
            evidence_pending,
            voided_after_resolution: evidence.voided_after_resolution,
            voids,
            eprocess_log,
            kind_alarm_threshold: (!by_kind_len_zero)
                .then_some(EVIDENCE_ALARM * by_kind_len as f64),

            verdict,
            sensitivity,
            easy_calls,
            so_far,
            brier_contested,
        }
    }

    /// True when there is nothing resolved (binary or numeric) to reflect.
    fn is_empty(&self) -> bool {
        self.resolved_binary == 0 && self.numeric.is_none()
    }
}

// ─────────────────────────── machine view ───────────────────────────────────

/// Pretty-printed JSON of the full [`ReportData`]. The agent-facing surface.
pub fn render_json(
    ledger: &Ledger,
    tag_filter: Option<&str>,
    bins: usize,
    today: NaiveDate,
) -> String {
    let data = ReportData::compute(ledger, tag_filter, bins, today);
    serde_json::to_string_pretty(&data).unwrap_or_else(|e| format!("{{\"error\":\"{e}\"}}"))
}

// ─────────────────────────── human view ─────────────────────────────────────

/// Place a predicted marker `P` and an observed marker `O` on a `[0,1]` lane;
/// `X` when they coincide. The visual gap between them *is* the calibration
/// error for that bin.
fn lane(pred: f64, obs: Option<f64>) -> String {
    let pos = |v: f64| -> usize { (v.clamp(0.0, 1.0) * (LANE_W as f64 - 1.0)).round() as usize };
    let mut cells = vec![b'-'; LANE_W];
    let pp = pos(pred);
    match obs {
        None => cells[pp] = b'P',
        Some(o) => {
            let op = pos(o);
            if pp == op {
                cells[pp] = b'X';
            } else {
                cells[pp] = b'P';
                cells[op] = b'O';
            }
        }
    }
    String::from_utf8(cells).unwrap()
}

/// Gloss for the confidence-gap line only.
///
/// The gap is an *aggregate* of bold-versus-right, and aggregates cancel, so this
/// describes the number on that one line and is never allowed to become a
/// verdict. It also has to agree with the verdict: naming a direction in capitals
/// while the verdict above says nothing has been demonstrated leaves the reader
/// to pick which of the two to believe.
/// Below this many graded calls the rich report prints the scores but not the band,
/// the decomposition, the gap or the diagram: at two calls they read as findings
/// ("Brier skill −3.000", a band of [1.000, 1.000]) and are noise.
pub const DETAIL_MIN_N: usize = 10;

/// A signed reading that prints no sign for what rounds to zero, so "+0.000 (toward NO)"
/// cannot happen.
fn signed(x: f64) -> String {
    if x.abs() < 0.0005 {
        "0.000".to_string()
    } else {
        format!("{x:+.3}")
    }
}

fn gap_gloss(gap: f64, v: Verdict) -> String {
    let direction = if gap > 0.05 {
        "bolder than you are right"
    } else if gap < -0.05 {
        "less sure than you turn out to be"
    } else {
        "boldness and accuracy match on average"
    };
    if v.is_miscalibrated() {
        match () {
            _ if gap > 0.05 => format!("OVERCONFIDENT — {direction}"),
            _ if gap < -0.05 => format!("UNDERCONFIDENT — {direction}"),
            _ => format!("{direction} (the errors cancel here — see the verdict above)"),
        }
    } else if v == Verdict::InsufficientData && gap.abs() > 0.05 {
        format!(
            "{direction}; whether that is more than luck is not tested yet — see the verdict above"
        )
    } else if gap.abs() > 0.05 {
        format!("{direction}, but not by more than luck could manage at this sample size — see the verdict above")
    } else {
        format!("{direction} (an average: errors in opposite directions cancel here)")
    }
}

/// Render the full human-readable report.
pub fn render(ledger: &Ledger, tag_filter: Option<&str>, bins: usize, today: NaiveDate) -> String {
    let d = ReportData::compute(ledger, tag_filter, bins, today);
    let mut out = String::new();

    let title = match &d.tag {
        Some(t) => format!("ANAMNESIS — the shape of your judgement  [tag: {t}]"),
        None => "ANAMNESIS — the shape of your judgement".to_string(),
    };
    let _ = writeln!(out, "\n{title}");
    let _ = writeln!(out, "{}", "=".repeat(title.len()));

    if d.is_empty() {
        let scope = d
            .tag
            .as_ref()
            .map(|t| format!(" tagged '{t}'"))
            .unwrap_or_default();
        let _ = writeln!(
            out,
            "\nNo resolved claims yet{scope}. {} still open.\n\nRecord beliefs with `ana add`, and `ana resolve` them once reality speaks.\nThe mirror needs something to reflect.",
            d.open
        );
        return out;
    }

    let split = if d.resolved_numeric > 0 && d.resolved_binary > 0 {
        format!(
            " ({} yes/no · {} numeric)",
            d.resolved_binary, d.resolved_numeric
        )
    } else {
        String::new()
    };
    let _ = writeln!(
        out,
        "\n{} of {} resolved{split}  ·  {} open  ·  first recorded {}  ·  latest {}",
        d.resolved,
        d.total,
        d.open,
        d.first_recorded.as_deref().unwrap_or("—"),
        d.last_recorded.as_deref().unwrap_or("—"),
    );

    // Resolution discipline — the honesty caveat, up top because it qualifies
    // everything below: do these numbers rest on a fair sample of your calls, or
    // only the ones you bothered to grade?
    if let Some(rd) = &d.resolution_discipline {
        let overdue_tail = if rd.overdue > 0 {
            format!("  ·  {} overdue", rd.overdue)
        } else {
            String::new()
        };
        let _ = writeln!(
            out,
            "\n  Resolution discipline   {:.0}% graded ({} of {}){overdue_tail}",
            rd.resolution_rate * 100.0,
            rd.resolved,
            rd.resolved + rd.open,
        );
        if rd.overdue > 0 {
            let _ = writeln!(
                out,
                "    ⚠ {} claim(s) past due and ungraded — resolve them; until you do, the numbers below rest on a self-selected sample.",
                rd.overdue
            );
        }
        if d.voids.total > 0 {
            let _ = writeln!(
                out,
                "    Voided: {} of {} settled claim(s) ({}), {} of them after they came due or had resolved. A void can hide a miss whenever it was made; past one in ten, no verdict is read.",
                d.voids.total, d.voids.settled, pct(d.voids.void_rate().unwrap_or(0.0)), d.voids.late
            );
        }
        if d.voids.reworded > 0 {
            let _ = writeln!(
                out,
                "    Reworded: {} settled claim(s) had their statement changed after they were logged (`ana show <id>` lists each change). A reword can turn a miss into a hit; it counts toward the same one-in-ten line as a void.",
                d.voids.reworded
            );
        }
        if d.voided_after_resolution > 0 {
            let _ = writeln!(
                out,
                "    ⚠ {} claim(s) were voided AFTER they had already resolved — an outcome removed from the record after it was seen. They are still counted in the evidence test below; voiding a claim you did not like is how this instrument would be defeated.",
                d.voided_after_resolution
            );
        }
        if rd.auto_graded > 0 {
            let _ = writeln!(
                out,
                "    {} of them ({:.0}%) were graded from a test run's exit status: {} by the command pinned when they were logged, {} by the next plain test run the hook saw. The grade is not yours, though the choice of command was.",
                rd.auto_graded,
                100.0 * rd.auto_graded as f64 / rd.resolved.max(1) as f64,
                rd.auto_pinned,
                rd.auto_graded - rd.auto_pinned
            );
        }
        // Missing-not-at-random check: are the calls you left open a different breed
        // from the ones you graded? If so, the calibration sample is skewed.
        if let (Some(rb), Some(ob), Some(asmd)) =
            (rd.resolved_boldness, rd.open_boldness, rd.boldness_asmd)
        {
            if asmd > SELECTION_ASMD_FLAG {
                let (dir, caveat) = if ob > rb {
                    (
                        "BOLDER",
                        "the confident end, where overconfidence hides, is under-graded — the gap above may understate it",
                    )
                } else {
                    (
                        "more CAUTIOUS",
                        "your graded sample leans bold relative to what you actually predicted",
                    )
                };
                let _ = writeln!(
                    out,
                    "    Your ungraded calls are {dir} than your graded ones (boldness {ob:.2} vs {rb:.2}, ASMD {asmd:.2}) — {caveat}.",
                );
            }
        }
    }

    // Binary section -------------------------------------------------------
    if d.resolved_binary > 0 {
        // The verdict, first, before any number it is derived from — one line, the
        // same line every other surface prints.
        let _ = writeln!(
            out,
            "\n  VERDICT          {}",
            d.verdict.label().to_uppercase()
        );
        if let Some(note) = sensitivity_note(&d) {
            let _ = writeln!(out, "                   {note}.");
        }
        if d.verdict == Verdict::InsufficientData {
            if let Some(note) = pending_due_note(&d) {
                let _ = writeln!(out, "                   {note}.");
            }
        }
        if d.verdict == Verdict::Withheld {
            let _ = writeln!(
                out,
                "                   {} of the {} settled claims {}. Every score here leaves voided claims out and scores a reworded one as reworded, and the misses are the ones that get edited, so none of them is read.",
                d.voids.edited().0, d.voids.settled, d.voids.edited().1
            );
        }
        // Under a withheld verdict no reading is printed (invariant 9): every one of them
        // leaves voided claims out, and a flattering Brier under "no verdict" is still read.
        if d.verdict != Verdict::Withheld {
            let detail = d.resolved_binary >= DETAIL_MIN_N;
            if let (Some(brier), Some(logs), Some(base)) = (d.brier, d.log_score, d.base_rate) {
                let _ = writeln!(out, "\n  Brier score      {brier:.3}   (0 = perfect · 0.25 = always 50/50 · lower better)");
                let _ = writeln!(
                out,
                "                   scored on your FIRST forecast — the belief you recorded before the answer was known"
            );
                if let Some(bf) = d.brier_final {
                    if (bf - brier).abs() > 0.0005 {
                        let _ = writeln!(
                        out,
                        "                   on your final forecast it would be {bf:.3} (shown, not graded)"
                    );
                    }
                }
                if let (Some((lo, hi)), true) = (d.brier_ci, detail) {
                    let _ = writeln!(
                    out,
                    "                   95% bootstrap band [{lo:.3}, {hi:.3}] — how far luck alone could move it"
                );
                }
                if let Some(wb) = d.weighted_brier {
                    let cmp = if wb > brier + 0.01 {
                        "WORSE on the calls that matter"
                    } else if wb < brier - 0.01 {
                        "better on the calls that matter"
                    } else {
                        "about the same across stakes"
                    };
                    let _ = writeln!(
                        out,
                        "  Stake-weighted   {wb:.3}   vs {brier:.3} flat → {cmp}"
                    );
                }
                let _ = writeln!(
                    out,
                    "  Log score        {logs:.3}   (lower better; punishes confident misses)"
                );
                if let (Some(bss), true) = (d.brier_skill, detail) {
                    let tail = if bss > 0.0 {
                        "you beat always-guess-the-base-rate"
                    } else if bss < 0.0 {
                        "you did WORSE than always guessing the base rate"
                    } else {
                        "no better than guessing the base rate"
                    };
                    let _ = writeln!(out, "  Brier skill      {bss:+.3}   ({tail})");
                }
                // Recency trend — descriptive only (small-n control charts false-alarm).
                if let Some(recent) = d.recent_brier {
                    if d.resolved_binary >= TREND_MIN_N {
                        let delta = brier - recent; // > 0 ⇒ recent lower ⇒ improving
                        let lean = if delta > 0.02 {
                            "improving"
                        } else if delta < -0.02 {
                            "slipping"
                        } else {
                            "steady"
                        };
                        let _ = writeln!(
                        out,
                        "  Lately           {recent:.3}   recent Brier vs {brier:.3} lifetime → {lean}  (last ~5 weighted; directional, not significant)"
                    );
                    }
                }
                let ci = d
                    .base_rate_ci
                    .map(|(lo, hi)| format!("   95% CI {lo:.2}–{hi:.2}"))
                    .unwrap_or_default();
                let _ = writeln!(
                    out,
                    "  Base rate        {base:.3}   (fraction of your claims that came true){ci}"
                );
                if let Some(note) = easy_note(&d) {
                    let _ = writeln!(out, "  Easy calls       {note}");
                }
            }

            if !detail {
                let _ = writeln!(
                out,
                "\n  ({} graded call(s). Below {DETAIL_MIN_N}, the band, the decomposition, the confidence gap and the diagram would describe noise, so they are left out.)",
                d.resolved_binary
            );
            }
            if !d.so_far.is_empty() && d.verdict != Verdict::Withheld {
                let _ = writeln!(
                    out,
                    "\n  Graded so far    (newest first; `ana show <id>` for the claim)"
                );
                for g in &d.so_far {
                    let _ = writeln!(
                        out,
                        "    [{}]  said {:>3.0}%  →  {:<16} Brier {:.3}{}",
                        g.id,
                        g.prob * 100.0,
                        if g.came_true {
                            "came true"
                        } else {
                            "did not happen"
                        },
                        g.brier,
                        if g.brier >= 0.64 {
                            "   ← a sure call that missed costs the most"
                        } else {
                            ""
                        }
                    );
                }
            }
            if let (Some(mcb), Some(dsc), Some(unc), true) = (d.mcb, d.dsc, d.unc, detail) {
                let _ = writeln!(
                    out,
                    "\n  Decomposition  (Brier = Miscalibration − Discrimination + Uncertainty)"
                );
                // The floor is what makes the calibration error readable. MCB is fitted
                // on the same data it scores, so it is never zero even for a perfect
                // forecaster; this says how large it would be for one.
                match d.mcb_null_q95 {
                    // One number, always in the same shape: the size, the floor it is
                    // measured against, and their ratio. No threshold to cross, because
                    // the floor is a 95th percentile and crossing it is what a
                    // calibrated forecaster does one look in twenty.
                    Some(floor) if floor > 0.0 => {
                        let _ = writeln!(
                        out,
                        "    miscalibration {mcb:.3}   calibration error      ↓ lower is better\n                   {:.2}x the {floor:.3} that only 1 calibrated forecaster in 20 exceeds on these same calls",
                        mcb / floor
                    );
                    }
                    // A zero floor means every calibrated resample scored zero
                    // miscalibration — too few calls for the comparison to mean
                    // anything, so no ratio is offered.
                    Some(_) => {
                        let _ = writeln!(
                        out,
                        "    miscalibration {mcb:.3}   calibration error      ↓ lower is better\n                   too few graded calls for a meaningful noise floor yet"
                    );
                    }
                    None => {
                        let _ = writeln!(
                        out,
                        "    miscalibration {mcb:.3}   calibration error      ↓ lower is better"
                    );
                    }
                }
                let dsc_note = if unc.abs() < 1e-12 {
                    "   — n/a: every call resolved the same way, so there is nothing to sort"
                } else if dsc.abs() < 1e-9 {
                    "   — your confidence carries NO information about which calls come true"
                } else {
                    ""
                };
                let _ = writeln!(
                out,
                "    discrimination {dsc:.3}   sorting power          ↑ higher is better{dsc_note}"
            );
                let _ = writeln!(
                    out,
                    "    uncertainty    {unc:.3}   irreducible difficulty of your questions"
                );
                let _ = writeln!(out, "    check          {mcb:.3} − {dsc:.3} + {unc:.3} = {:.3}  (= Brier, exactly — no bins, no tuning)", mcb - dsc + unc);
            }

            match d.auc {
                Some(a) => {
                    let _ = writeln!(out, "\n  Discrimination   AUC {a:.3}   (0.5 = can't tell true from false · 1.0 = perfect)");
                }
                None => {
                    let _ = writeln!(
                        out,
                        "\n  Discrimination   n/a   (every claim resolved the same way)"
                    );
                }
            }

            if let (Some(gap), Some(conf), Some(acc), true) =
                (d.confidence_gap, d.mean_confidence, d.accuracy, detail)
            {
                // The gloss is subordinate to the verdict. This line used to shout
                // "OVERCONFIDENT" from a gap of +0.12 while the verdict above said no
                // miscalibration had been demonstrated — the reader is left to guess
                // which of the two to believe, which is the whole defect P0-5 fixed.
                let _ = writeln!(
                    out,
                    "\n  Confidence gap   {}   {}",
                    signed(gap),
                    gap_gloss(gap, d.verdict)
                );
                let _ = writeln!(
                    out,
                    "                   mean boldness {conf:.3}  vs  accuracy {acc:.3}"
                );
                if let Some(bias) = d.directional_bias {
                    let dir = if bias >= 0.0005 {
                        " (toward YES)"
                    } else if bias <= -0.0005 {
                        " (toward NO)"
                    } else {
                        ""
                    };
                    let _ = writeln!(
                        out,
                        "                   directional bias {}{dir}",
                        signed(bias)
                    );
                }
            }

            // Confidence vocabulary — a handful of distinct values caps your resolution.
            if d.distinct_forecasts > 0 && detail {
                let _ = writeln!(
                    out,
                    "\n  Confidence vocab {:>4} distinct level(s) across {} call(s){}",
                    d.distinct_forecasts,
                    d.resolved_binary,
                    if d.distinct_forecasts <= 3 && d.resolved_binary >= 6 {
                        " — coarse; more gradations would sharpen you"
                    } else {
                        ""
                    }
                );
            }

            // Selective prediction — error among your surest calls vs all (when to act).
            if let Some(sel) = &d.selective {
                if d.resolved_binary >= 6 {
                    let verdict = if sel.risk_full < 0.005 {
                        "no misses to separate"
                    } else if sel.risk_half < sel.risk_full - 0.05 {
                        "your confidence ranks your calls — trust the bold ones"
                    } else if sel.risk_half > sel.risk_full + 0.05 {
                        "INVERTED — your most-confident calls are your worst"
                    } else {
                        "confidence barely separates winners from losers"
                    };
                    let _ = writeln!(
                    out,
                    "\n  Selective        act on all {:.0}% error · surest half {:.0}% → {verdict}",
                    sel.risk_full * 100.0,
                    sel.risk_half * 100.0
                );
                }
            }

            // Anytime-valid significance: is the miscalibration above real, or noise?
            // Three states, each said plainly. "Too few resolutions to tell" printed
            // at n = 1000 read as a bug, because it was one.
            if let Some(e) = d.eprocess {
                let p = d.eprocess_pvalue.unwrap_or(1.0);
                let n = d.evidence_n;
                let shown = if d
                    .eprocess_log
                    .is_some_and(|l| l >= scoring::EPROCESS_LOG_CAP)
                {
                    "> 10^12".to_string()
                } else if e < 0.1 {
                    // A well-priced backlog drives the e-value well below 1, where
                    // one decimal place prints "0.0" and reads as a broken metric.
                    format!("{e:.3}")
                } else {
                    format!("{e:.1}")
                };
                let line = if e >= EVIDENCE_ALARM {
                    "miscalibration is REAL — significant even though you peek every session (α=.05)"
                    .to_string()
                } else if n < VERDICT_MIN_N {
                    format!(
                    "not enough graded calls yet — {n} in the test, about {} more to reach a usable {VERDICT_MIN_N}",
                    VERDICT_MIN_N.saturating_sub(n)
                )
                } else if e >= RECAL_MIN_E {
                    "suggestive, not yet conclusive — keep logging".to_string()
                } else {
                    "no evidence of miscalibration in {n} graded calls — the test can still miss patterns; read the calibration error above for the SIZE of any error"
                    .replace("{n}", &n.to_string())
                };
                let _ = writeln!(
                    out,
                    "\n  Is it real?      e-value {shown:>8}   (anytime-valid p ≤ {p:.3})"
                );
                let _ = writeln!(out, "                   {line}");
            } else if d.resolved_binary > 0 {
                let _ = writeln!(out, "\n  Is it real?      no evidence sequence yet");
            }

            // The two instruments have opposite blind spots, and saying so is the
            // honest answer to "why are there two numbers". The e-process is strong on
            // sharp patterns and weak on gentle shrinkage toward 0.5; MCB against its
            // floor measures the SIZE of an error but, being a single-look comparison,
            // cannot establish that it is real. When they disagree, say which is which
            // rather than letting the quiet one speak for both.
            if d.resolved_binary > 0 && d.verdict == Verdict::NoEvidenceOfMiscalibration {
                let notable = mcb_ratio(&d).is_some_and(|r| r >= MCB_RATIO_NOTABLE);
                if notable {
                    let _ = writeln!(
                    out,
                    "                   but your calibration error is {:.2}x its noise floor. the two checks disagree, and they fail in opposite directions:",
                    mcb_ratio(&d).unwrap_or(1.0)
                );
                    let _ = writeln!(
                    out,
                    "                   the e-process is strong on sharp patterns and weak on a gentle drift toward 50/50; the error above measures SIZE but one reading of it is a single look, not an anytime-valid test"
                );
                    let _ = writeln!(
                    out,
                    "                   treat this as worth watching, not as settled either way — keep logging"
                );
                }
            }

            // What the backlog is costing. It no longer halts the test, so this is a
            // price to be read, not a wall to be cleared.
            if d.resolved_binary > 0 && d.evidence_ungraded_due > 0 {
                let _ = writeln!(
                out,
                "                   {} of {} graded calls counted, {} ungraded priced in at their worst case (`ana list --due`)",
                d.evidence_n, d.resolved_binary, d.evidence_ungraded_due
            );
                if let Some(cost) = d.evidence_gap_cost_log {
                    if cost > 0.0 {
                        let _ = writeln!(
                        out,
                        "                   that backlog is costing you a factor of {:.3} on the evidence — grading it is how you get it back",
                        cost.min(scoring::EPROCESS_LOG_CAP).exp()
                    );
                    }
                }
                if let Some(id) = &d.evidence_oldest_gap {
                    let fix = if d.evidence_gap_without_deadline {
                        "resolve it, or give it a --by date"
                    } else {
                        "resolve it, or void it if it was never answerable"
                    };
                    let _ = writeln!(
                    out,
                    "                   oldest is [{id}] — {fix}. an ungraded bold call costs more than a cautious one",
                );
                }
            }

            // The learned correction — only once it is both trustworthy (n) and worth
            // mentioning (meaningfully off the identity).
            if let Some(r) = &d.recalibration {
                // Only offer a correction once the e-process finds at least suggestive
                // evidence — never invite acting on a map fit to noise.
                let has_evidence = d.eprocess.is_some_and(|e| e >= RECAL_MIN_E);
                if has_evidence
                    && r.n >= RECAL_MIN_N
                    && ((r.b - 1.0).abs() > 0.10 || r.a.abs() > 0.10)
                {
                    // The Cox calibration slope (b) and intercept (a), read aloud:
                    // b<1 ⇒ forecasts too extreme; the intercept is a level-independent
                    // bias — a>0 means your stated numbers should be higher (you
                    // under-state), a<0 lower (you over-state).
                    let shape = if r.b < 1.0 {
                        "you run too extreme"
                    } else {
                        "you are too timid"
                    };
                    let bias = if r.a > 0.10 {
                        "; under-stating on average"
                    } else if r.a < -0.10 {
                        "; over-stating on average"
                    } else {
                        ""
                    };
                    let _ = writeln!(
                    out,
                    "\n  Recalibration    stated → what it should be   (Cox slope b={:.2}: {shape}{bias})",
                    r.b
                );
                    let cells: Vec<String> = r
                        .examples
                        .iter()
                        .map(|(p, q)| format!("{p:.2}→{q:.2}"))
                        .collect();
                    let _ = writeln!(out, "    {}", cells.join("    "));
                }
            }

            if detail {
                let _ = writeln!(
                    out,
                    "\n  Reliability diagram   P = your avg forecast · O = what actually happened"
                );
                let _ = writeln!(
                    out,
                    "    range        n    0{}1",
                    " ".repeat(LANE_W.saturating_sub(2))
                );
                for b in &d.calibration {
                    if b.count == 0 {
                        continue;
                    }
                    let mean_pred = b.mean_pred.unwrap_or((b.lo + b.hi) / 2.0);
                    let tail = match b.observed {
                        None => String::new(),
                        Some(obs) => {
                            let gap = mean_pred - obs;
                            let mark = if gap.abs() < 0.05 {
                                "ok"
                            } else if gap > 0.0 {
                                "over"
                            } else {
                                "under"
                            };
                            format!("  pred {mean_pred:.2} → obs {obs:.2}  {mark}")
                        }
                    };
                    let _ = writeln!(
                        out,
                        "    {:.2}-{:.2}  {:>4}   |{}|{}",
                        b.lo,
                        b.hi,
                        b.count,
                        lane(mean_pred, b.observed),
                        tail
                    );
                }
            } // detail

            // Emptied at compute time when the breakdown below induces the same
            // partition, so the two can never print the same rows twice.
            if !d.by_tag.is_empty() {
                let _ = writeln!(out, "\n  By domain");
                let _ = writeln!(
                    out,
                    "    {:<14} {:>4}  {:>7}  {:>9}",
                    "tag", "n", "brier", "conf-gap"
                );
                for t in &d.by_tag {
                    let br = t
                        .brier
                        .map(|x| format!("{x:.3}"))
                        .unwrap_or_else(|| "  —".into());
                    let g = t
                        .confidence_gap
                        .map(|x| format!("{x:+.3}"))
                        .unwrap_or_else(|| "   —".into());
                    let _ = writeln!(
                        out,
                        "    {:<14} {:>4}  {:>7}  {:>9}",
                        untrusted::tag(&t.tag),
                        t.n,
                        br,
                        g
                    );
                }
            }

            // A breakdown over a self-selected slice is the same defect as a score
            // over a self-selected sample, so it stays collapsed until the tag
            // actually covers the record.
            if d.group_by.is_none() && d.resolved_binary > 0 {
                if d.group_coverage < KIND_MIN_COVERAGE {
                    let _ = writeln!(
                    out,
                    "\n  By group             hidden: your best-covered tag reaches only {:.0}% of your graded",
                    d.group_coverage * 100.0
                );
                    let _ = writeln!(
                    out,
                    "                       calls, so a breakdown would describe a self-selected slice."
                );
                    let _ = writeln!(
                    out,
                    "                       tag as you log — `--tags kind:<type>` (tests-pass, estimate,"
                );
                    let _ = writeln!(
                    out,
                    "                       bug-hypothesis, approach, compat) or any topic tag — and this"
                );
                    let _ = writeln!(
                        out,
                        "                       fills in at {:.0}% coverage.",
                        KIND_MIN_COVERAGE * 100.0
                    );
                } else {
                    let _ = writeln!(
                    out,
                    "\n  By group             hidden: your tags cover the record but split it into {} group{}.",
                    d.group_k,
                    if d.group_k == 1 { "" } else { "s" }
                );
                    let _ = writeln!(
                    out,
                    "                       every group pays a factor of K in its alarm, so {}-{} is the usable",
                    GROUP_MIN_K, GROUP_MAX_K
                );
                    let _ = writeln!(
                    out,
                    "                       range — a per-session or per-user tag is bookkeeping, not a grouping."
                );
                    let _ = writeln!(
                    out,
                    "                       add a `kind:` tag (tests-pass, estimate, bug-hypothesis, approach,"
                );
                    let _ = writeln!(
                        out,
                        "                       compat) and the breakdown keys off that instead."
                    );
                }
            } else if !d.by_kind.is_empty() {
                let _ = writeln!(
                out,
                "\n  By {:<17}(K={} groups · {:.0}% covered · gap~ shrunk toward your overall rate)",
                untrusted::tag(d.group_by.as_deref().unwrap_or("group")),
                d.group_k,
                d.group_coverage * 100.0
            );
                let _ = writeln!(
                    out,
                    "    {:<16} {:>4}  {:>7}  {:>8}  {:>8}",
                    untrusted::tag(d.group_by.as_deref().unwrap_or("group")),
                    "n",
                    "brier",
                    "gap",
                    "gap~"
                );
                for t in &d.by_kind {
                    let br = t
                        .brier
                        .map(|x| format!("{x:.3}"))
                        .unwrap_or_else(|| "  —".into());
                    let g = t
                        .confidence_gap
                        .map(|x| format!("{x:+.3}"))
                        .unwrap_or_else(|| "   —".into());
                    let gs = t
                        .confidence_gap_shrunk
                        .map(|x| format!("{x:+.3}"))
                        .unwrap_or_else(|| "   —".into());
                    let _ = writeln!(
                        out,
                        "    {:<16} {:>4}  {:>7}  {:>8}  {:>8}",
                        untrusted::tag(&t.tag),
                        t.n,
                        br,
                        g,
                        gs
                    );
                }
                // Multicalibration verdict. The per-kind e-process is anytime-valid, so
                // the worst kind that clears the evidence bar is *genuinely* miscalibrated
                // — not the small-subgroup fluke that derails a raw worst-group gap. Stay
                // silent otherwise; the overall "Is it real?" line already covers that.
                // Searching K subgroups for the worst one is K tests, not one. Ville
                // plus a union bound says a single row has to clear
                // `EVIDENCE_ALARM × K` before it is a finding; below that the
                // per-kind numbers are descriptive only, and are labelled as such.
                let k_threshold = d.kind_alarm_threshold.unwrap_or(EVIDENCE_ALARM);
                if let Some((t, e)) = d
                    .by_kind
                    .iter()
                    .filter_map(|t| t.eprocess.map(|e| (t, e)))
                    .filter(|&(_, e)| e >= k_threshold)
                    .max_by(|a, b| a.1.total_cmp(&b.1))
                {
                    let dir = match t.confidence_gap {
                        Some(g) if g > 0.0 => "overconfident",
                        Some(_) => "underconfident",
                        None => "miscalibrated",
                    };
                    let _ = writeln!(
                        out,
                        "    → '{}' is really {dir} (e={:.0}) — trust your '{}' calls least.",
                        untrusted::tag(&t.tag),
                        e,
                        untrusted::tag(&t.tag)
                    );
                }
            }

            if let Some(mc) = &d.mind_changing {
                let _ = writeln!(
                    out,
                    "\n  Mind-changing    {} claim(s) you revised",
                    mc.revised
                );
                let _ = writeln!(
                out,
                "    Brier of first guess {:.3}  (GRADED)  →  Brier of final guess {:.3}  (not graded)   ({:+.3})",
                mc.brier_first, mc.brier_last, mc.improvement
            );
                // Deliberately neutral. Praising a movement toward the truth rewards
                // the one thing this tool exists to catch: ten claims logged at 0.5,
                // updated to 0.99 and then resolved YES used to score a Brier of
                // 0.000 and be congratulated for changing their mind well. Moving
                // toward the answer is only a virtue if you did not already know it,
                // and the ledger cannot tell the difference — so it does not judge.
                let _ = writeln!(
                out,
                "    Only the first figure is scored. A revision may be genuine learning or may be hindsight; the ledger cannot tell, so it grades the belief you recorded before the answer was known."
            );
                if d.late_updates > 0 {
                    let _ = writeln!(
                    out,
                    "    {} claim(s) were revised after their due date or within a day of the answer — those revisions carry no weight anywhere.",
                    d.late_updates
                );
                }
                if let Some(ta) = d.brier_time_avg {
                    let _ = writeln!(
                    out,
                    "    Time-averaged Brier {ta:.3} — each forecast weighted by how long it stood, the way Metaculus rewards updating early (secondary: it can still be farmed by updating the moment you know)."
                );
                }
            }
        } // readings
    }

    // Numeric section ------------------------------------------------------
    if let Some(num) = &d.numeric {
        let _ = writeln!(
            out,
            "\n  Numeric forecasts   {} resolved interval(s)",
            num.count
        );
        let _ = writeln!(
            out,
            "    interval score       {}\n                         (1.00 = the value landed inside; above that is the miss penalty, in multiples of your own stated width)",
            match (num.mean_winkler_ratio, num.median_winkler_ratio) {
                (Some(mean), Some(med)) => format!("mean {mean:.2} · median {med:.2}"),
                _ => format!("{:.3} raw Winkler (units vary)", num.mean_winkler),
            }
        );
        let _ = writeln!(out, "    mean interval width  {:.3}", num.mean_width);
        let _ = writeln!(
            out,
            "    coverage             {:.0}% actual  vs  {:.0}% intended   ({:+.0} pts)",
            num.empirical_coverage * 100.0,
            num.nominal_coverage * 100.0,
            num.coverage_gap * 100.0
        );
        let line = if num.coverage_gap < -0.05 {
            "    Your intervals are TOO NARROW — overconfident about numbers, just like probabilities."
        } else if num.coverage_gap > 0.05 {
            "    Your intervals are too WIDE — you could afford to be sharper."
        } else {
            "    Your intervals are about the right width. Well judged."
        };
        let _ = writeln!(out, "{line}");
        // The conformal width correction — gated on the coverage e-process finding
        // real evidence (mirrors the binary recalibration gate), so the agent is
        // never told to resize intervals on the strength of a couple of misses.
        if let (Some(m), Some(e)) = (num.width_factor, num.coverage_eprocess) {
            if e >= RECAL_MIN_E && (m - 1.0).abs() > 0.10 {
                let verb = if m > 1.0 { "WIDEN" } else { "SHARPEN" };
                let _ = writeln!(
                    out,
                    "    Recalibration: {verb} — multiply your interval half-widths by {m:.2} (coverage e={e:.0})."
                );
            }
        }
    }

    let _ = writeln!(
        out,
        "\n  \"The first principle is that you must not fool yourself —\n   and you are the easiest person to fool.\"  — R. Feynman\n"
    );
    out
}

// ──────────────────── plain-English view (text + HTML card) ──────────────────
//
// Two more renderings of the same `ReportData`: the numbers translated into what
// they *mean* for a person who shouldn't need to know what a Brier score is. The
// prose is built once in `plain_summary`, so the text view (`render_plain`) and
// the offline HTML card (`render_html`) can never drift apart — the same
// compute-once-render-many discipline as the rest of this file.

/// Whole-percent string: `0.833 → "83%"`.
fn pct(x: f64) -> String {
    format!("{:.0}%", (x * 100.0).round())
}

/// Word-wrap `text` to `width` columns, prefixing every line with `indent`.
fn wrap(text: &str, width: usize, indent: &str) -> String {
    let mut lines: Vec<String> = Vec::new();
    let mut cur = String::new();
    for word in text.split_whitespace() {
        if !cur.is_empty() && cur.chars().count() + 1 + word.chars().count() > width {
            lines.push(std::mem::take(&mut cur));
        }
        if !cur.is_empty() {
            cur.push(' ');
        }
        cur.push_str(word);
    }
    if !cur.is_empty() {
        lines.push(cur);
    }
    lines
        .into_iter()
        .map(|l| format!("{indent}{l}"))
        .collect::<Vec<_>>()
        .join("\n")
}

/// Escape the HTML-significant characters (the report's prose is ours, but a tag
/// name could in principle reach the card, so be safe).
fn esc(s: &str) -> String {
    s.replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
}

/// One plain-language insight: a plain question, a plain answer, and the technical
/// term it maps to — named, not hidden, so the plain view is a *bridge* to the
/// rich report rather than a dumbing-down.
struct Insight {
    label: &'static str,
    answer: String,
    jargon: &'static str,
}

/// The whole report distilled to plain language — the single source of prose for
/// both the text view and the HTML card.
struct PlainSummary {
    headline: String,
    verdict_word: String,
    /// Severity/colour hint: `"good" | "over" | "under" | "unknown"`.
    verdict_class: &'static str,
    insights: Vec<Insight>,
    actions: Vec<String>,
    footer: String,
}

/// Why resolved calls may be missing from the sequential test, when some are.
///
/// The test reads claims in due-date order, which is what keeps it valid however often
/// you look, so a call joins it once its due date has passed, however early you
/// resolved it. A person who logs 30 calls and resolves them the same week saw "not
/// enough data" with 30 resolved, and no way to know why.
/// Whether at least [`EASY_SHARE_NOTE`] of the graded calls were near-certain.
fn easy_heavy(d: &ReportData) -> bool {
    d.resolved_binary > 0 && d.easy_calls as f64 >= EASY_SHARE_NOTE * d.resolved_binary as f64
}

/// Whether the record leans on near-certain calls, in one sentence.
fn easy_note(d: &ReportData) -> Option<String> {
    let n = d.resolved_binary;
    if !easy_heavy(d) {
        return None;
    }
    let rest = match d.brier_contested {
        Some(b) => format!("; on the other {} it is {b:.3}", n - d.easy_calls),
        None => format!("; too few others ({}) to score apart", n - d.easy_calls),
    };
    Some(format!(
        "{} of your {n} graded calls ({:.0}%) were said at {:.0}% or more either way. Sure things lower a Brier score without showing much judgement{rest}",
        d.easy_calls,
        100.0 * d.easy_calls as f64 / n as f64,
        EASY_P * 100.0
    ))
}

/// How much a quiet test is worth at this record, in one sentence.
fn sensitivity_note(d: &ReportData) -> Option<String> {
    let r = d.sensitivity?;
    let (only, weight) = if r < 0.5 {
        ("only ", "so this silence says little")
    } else if r < 0.8 {
        ("only ", "so this silence is moderate evidence at best")
    } else {
        ("", "so an error that size would probably have shown")
    };
    Some(format!(
        "At your {} calls, this test catches a forecaster {:.0}% too extreme {only}{:.0}% of the time, {weight}",
        d.evidence_n,
        SENSITIVITY_SHRINK * 100.0,
        r * 100.0
    ))
}

fn pending_due_note(d: &ReportData) -> Option<String> {
    let (k, first, last) = d.evidence_pending?;
    let when = if first == last {
        format!("on {first}")
    } else {
        format!("between {first} and {last}")
    };
    Some(format!(
        "{k} resolved call(s) join the test {when}. It reads claims in due-date order, which is what keeps it valid however often you look, so a call counts once its due date has passed, however early it was resolved. Until then the numbers below describe your calls; they do not decide anything"
    ))
}

fn plain_summary(d: &ReportData) -> PlainSummary {
    let n = d.resolved_binary;
    let mut insights: Vec<Insight> = Vec::new();

    // — Honest sample? (resolution discipline) —
    if let Some(rd) = &d.resolution_discipline {
        let mut a = if d.verdict == Verdict::Withheld {
            format!(
                "No. {} of your {} settled call(s) {}, and every number leaves a voided call out and scores a reworded one as reworded, so what remains may be the calls that went your way.",
                d.voids.edited().0, d.voids.settled, d.voids.edited().1
            )
        } else if rd.open == 0 && d.voids.total == 0 {
            format!("Yes — you've graded every one of your {} call(s). This isn't a picture cherry-picked from only the predictions that went your way.", rd.resolved)
        } else if rd.open == 0 {
            format!(
                "You've graded every one of the {} call(s) still on the record.",
                rd.resolved
            )
        } else {
            format!(
                "You've graded {} of {} call(s) ({}). The {} still open aren't in the numbers below.",
                rd.resolved,
                rd.resolved + rd.open,
                pct(rd.resolution_rate),
                rd.open
            )
        };
        if d.voids.total > 0 && d.verdict != Verdict::Withheld {
            a.push_str(&format!(" You voided {} call(s)", d.voids.total));
            if d.voids.late > 0 {
                a.push_str(&format!(
                    ", {} of them after they came due, when you may already have known how they went.",
                    d.voids.late
                ));
            } else {
                a.push_str(". A void hides a miss whenever it is made, so past one in ten no verdict is read.");
            }
        }
        if let Some(note) = easy_note(d) {
            a.push_str(&format!(
                " Also, {}{}.",
                note[..1].to_lowercase(),
                &note[1..]
            ));
        }
        if rd.overdue > 0 {
            a.push_str(&format!(" Watch out: {} of those are past their due date — resolve them, or these scores quietly flatter you.", rd.overdue));
        }
        if let (Some(rb), Some(ob), Some(asmd)) =
            (rd.resolved_boldness, rd.open_boldness, rd.boldness_asmd)
        {
            if asmd > SELECTION_ASMD_FLAG {
                let dir = if ob > rb { "bolder" } else { "more cautious" };
                a.push_str(&format!(
                    " And the calls you left open are {dir} than the ones you graded, so the split isn't random."
                ));
            }
        }
        insights.push(Insight {
            label: "Is this an honest sample of your calls?",
            answer: a,
            jargon: "resolution discipline / selection bias",
        });
    }

    // — Sure vs right? (calibration) —
    //
    // Word and class come from `d.verdict` and nowhere else. They used to be read
    // off the confidence gap, in which over- and under-confidence cancel: a
    // ledger of 50 calls at 0.9 on coin flips plus 50 at 0.6 on sure things has a
    // gap of roughly −1e-15, and was therefore called "Well calibrated" while its
    // Brier skill was −0.520.
    let (verdict_word, verdict_class): (String, &'static str) = match d.verdict {
        Verdict::InsufficientData => ("Not enough data".into(), "unknown"),
        Verdict::Withheld => ("Withheld".into(), "unknown"),
        Verdict::Overconfident => ("Overconfident".into(), "over"),
        Verdict::Underconfident => ("Underconfident".into(), "under"),
        Verdict::BiasedYes => ("Leans yes".into(), "over"),
        Verdict::BiasedNo => ("Leans no".into(), "under"),
        Verdict::CalibratedButUninformative => ("Uninformative".into(), "uninformative"),
        Verdict::MiscalibratedBothWays => ("Miscalibrated".into(), "both"),
        // A quiet test that would miss most 30% errors is not a green light: the badge
        // and card showed "No miscalibration found" in green at a sensitivity of 4%.
        Verdict::NoEvidenceOfMiscalibration
            if d.sensitivity.is_some_and(|r| r < DIALED_MIN_SENSITIVITY) =>
        {
            ("Nothing found yet".into(), "unknown")
        }
        Verdict::NoEvidenceOfMiscalibration => ("No miscalibration found".into(), "good"),
    };
    if let (Some(conf), Some(acc)) = (d.mean_confidence, d.accuracy) {
        let core = format!(
            "On the calls you felt about {} sure of, you turned out right about {} of the time.",
            pct(conf),
            pct(acc)
        );
        let lesson = match d.verdict {
            Verdict::Overconfident => "You OVERSELL yourself — you sound more certain than you turn out to be, so shade your confidence down.",
            Verdict::Underconfident => "You UNDERSELL yourself — reality rewards you more than you claim, so when you feel fairly sure you can trust it more.",
            Verdict::BiasedYes => "You lean toward YES — you say things will happen more often than they do.",
            Verdict::BiasedNo => "You lean toward NO — you say things won't happen more often than turns out to be true.",
            Verdict::CalibratedButUninformative => "Your confidence does not separate the calls that come true from the ones that don't — after correcting for level, every forecast you make carries the same information. That is the thing to fix first; how high or low you pitch the numbers barely matters until the ranking works.",
            Verdict::InsufficientData => "Too few graded calls to say whether that's luck or judgement.",
            Verdict::Withheld => "No reading is given. More than one in ten of the settled calls were voided, and the ones that get voided are the ones that went badly, so these numbers describe a record that has been tidied. Resolve a call when it answers, even when it went against you; a void is for a question that stopped making sense.",
            Verdict::MiscalibratedBothWays => "Your errors run BOTH ways — too sure at one end of your range and not sure enough at the other. They cancel in the average, so there is no single direction to shade: look at the reliability diagram to see where each half goes wrong.",
            Verdict::NoEvidenceOfMiscalibration => "Nothing in the record shows your confidence is off. That is not the same as proof it's right — the test can miss patterns, and a small record hides a lot.",
        };
        // A withheld verdict gives no reading, so it does not quote the accuracy
        // either: the figure is computed from a record that has been tidied.
        let answer = if d.verdict == Verdict::Withheld {
            lesson.to_string()
        } else {
            format!("{core} {lesson}")
        };
        insights.push(Insight {
            label: "When you say you're sure, should you be?",
            answer,
            jargon: "calibration verdict (CORP miscalibration + sequential evidence test)",
        });
    }

    // — Discrimination —
    let disc = match d.auc {
        None => "Everything you've logged so far turned out the same way, so there's nothing to sort yet.".to_string(),
        Some(_) if n < 12 => format!("Can't tell from {n} call(s) yet — sorting your good calls from your bad ones needs more answers before it means anything."),
        Some(a) if a >= 0.70 => "Yes — the calls you're more confident about come true noticeably more often than the ones you're unsure of.".to_string(),
        Some(a) if a >= 0.55 => "Somewhat — your confidence points the right way, but not sharply.".to_string(),
        Some(_) => "Not really — your confidence isn't tracking which calls actually come true. Of everything here, that's the one most worth fixing.".to_string(),
    };
    insights.push(Insight {
        label: "Can you tell your right calls from your wrong ones?",
        answer: disc,
        jargon: "discrimination (AUC)",
    });

    // — Evidence (is the pattern real?) —
    if let Some(e) = d.eprocess {
        let en = d.evidence_n;
        let ev = if e >= EVIDENCE_ALARM {
            "Yes, it's real. Even though you check this every session, the pattern above is statistically solid — you can act on it.".to_string()
        } else if en < VERDICT_MIN_N {
            format!(
                "Not yet answerable. Only {en} of your calls are in the test, and about {} more are needed before it can say anything either way.{}",
                VERDICT_MIN_N.saturating_sub(en),
                pending_due_note(d).map(|s| format!(" Note: {s}.")).unwrap_or_default()
            )
        } else if e >= RECAL_MIN_E {
            "Maybe — the signs are suggestive but not yet conclusive. Keep logging.".to_string()
        } else {
            format!("No. Across {en} graded calls the test found no miscalibration. That is not proof you are calibrated — the test can miss patterns it isn't looking for — but nothing here is demonstrably off.")
        };
        insights.push(Insight {
            label: "Is any of this real, or a small-sample fluke?",
            answer: ev,
            jargon: "anytime-valid e-value",
        });
    }

    // — Headline score (Brier) —
    if let Some(b) = d.brier {
        let band = d
            .brier_ci
            .map(|(lo, hi)| {
                format!(
                    " Luck alone could place the true figure anywhere between {lo:.2} and {hi:.2}."
                )
            })
            .unwrap_or_default();
        let quality = if b < 0.10 {
            "That's sharp."
        } else if b < 0.25 {
            "Better than a coin flip."
        } else {
            "That's around coin-flip territory."
        };
        insights.push(Insight {
            label: "How good are your predictions overall?",
            answer: format!(
                "{b:.2} on the forecasting \"golf score\": 0 is a perfect prophet, 0.25 is a coin flip, lower is better. {quality}{band}"
            ),
            jargon: "Brier score",
        });
    }

    // — Numeric ranges (only if you've made any) —
    if let Some(num) = &d.numeric {
        let a = if num.coverage_gap < -0.05 {
            format!("Your number ranges are TOO NARROW — meant to contain the true value {} of the time, they only did {} of the time. You're overconfident about numbers, just like probabilities.", pct(num.nominal_coverage), pct(num.empirical_coverage))
        } else if num.coverage_gap > 0.05 {
            format!("Your number ranges are too WIDE — they caught the value {} of the time versus the {} you aimed for, so you can afford to be sharper.", pct(num.empirical_coverage), pct(num.nominal_coverage))
        } else {
            "Your number ranges are about the right width — well judged.".to_string()
        };
        insights.push(Insight {
            label: "And your number ranges?",
            answer: a,
            jargon: "interval coverage",
        });
    }

    // A withheld verdict leaves only the two paragraphs that say why. Everything else
    // here (discrimination, the evidence test, the Brier score, interval coverage) is
    // a reading of the same tidied record, and printing it under "no verdict" would
    // hand back the verdict by another route.
    if d.verdict == Verdict::Withheld {
        insights.retain(|i| {
            i.jargon.starts_with("resolution discipline")
                || i.jargon.starts_with("calibration verdict")
        });
    }

    // — What to do — tailored to the verdict, then the earned correction, then n. —
    let mut actions: Vec<String> = Vec::new();
    if d.verdict == Verdict::Withheld {
        actions.push("Resolve the calls that have come due instead of voiding them. A void is for a question that stopped making sense before you knew the answer.".into());
    }
    match verdict_class {
        "under" => actions
            .push("Lean in a little when you feel sure — you tend to undersell yourself.".into()),
        "over" => {
            actions.push("Add slack and shade your confidence down — you tend to oversell.".into())
        }
        "both" => actions.push(
            "Your errors cancel: shading everything one way will not help. Compare your high-confidence and low-confidence calls separately — the reliability diagram shows which end is wrong.".into(),
        ),
        "uninformative" => actions.push(
            "Spread your probabilities out — right now they don't distinguish the calls that come true from the ones that don't.".into(),
        ),
        "good" if n >= VERDICT_CONFIDENT_N => actions
            .push("Nothing here needs correcting — keep logging so it stays that way.".into()),
        "good" => actions.push(
            "Nothing is demonstrably off yet. Keep logging: absence of evidence at this sample size is not evidence of calibration.".into(),
        ),
        _ => {}
    }
    let earned = d.eprocess.is_some_and(|e| e >= RECAL_MIN_E)
        && d.recalibration
            .as_ref()
            .is_some_and(|r| r.n >= RECAL_MIN_N && ((r.b - 1.0).abs() > 0.10 || r.a.abs() > 0.10));
    if earned {
        if let Some((p, q)) = d
            .recalibration
            .as_ref()
            .and_then(|r| r.examples.iter().find(|(p, _)| (*p - 0.7).abs() < 1e-9))
        {
            actions.push(format!(
                "A correction has earned its place: when you'd say {}, log about {} instead.",
                pct(*p),
                pct(*q)
            ));
        }
    }
    if n < 12 {
        actions.push(format!(
            "Don't over-read {n} prediction(s) — keep logging and the picture sharpens."
        ));
    }
    actions.push("Before a costly or irreversible call, run `ana decide` to turn your confidence into a clear proceed / verify / abstain.".into());

    let headline = match d.verdict {
        Verdict::Withheld => format!(
            "No verdict: {} of your {} settled calls {}.",
            d.voids.edited().0, d.voids.settled, d.voids.edited().1
        ),
        Verdict::Underconfident => {
            "You undersell yourself — trust your sure calls more.".to_string()
        }
        Verdict::Overconfident => "You oversell yourself — add slack and shade down.".to_string(),
        Verdict::BiasedYes => {
            "You lean toward yes — you predict things happen more than they do.".to_string()
        }
        Verdict::BiasedNo => {
            "You lean toward no — you predict things don't happen more than holds up.".to_string()
        }
        Verdict::CalibratedButUninformative => {
            "Right on average, but your confidence doesn't separate the good calls from the bad."
                .to_string()
        }
        Verdict::MiscalibratedBothWays => {
            "Miscalibrated in both directions at once — the errors cancel in the average."
                .to_string()
        }
        Verdict::NoEvidenceOfMiscalibration
            if n >= VERDICT_CONFIDENT_N
                && mcb_ratio(d).is_some_and(|r| r >= MCB_RATIO_NOTABLE) =>
        {
            format!(
                "The 'is it real' test is quiet, but the SIZE of your calibration error is {:.1}x its noise floor. The two checks disagree — worth watching, not settled.",
                mcb_ratio(d).unwrap_or(1.0)
            )
        }
        Verdict::NoEvidenceOfMiscalibration if n >= VERDICT_CONFIDENT_N => format!(
            "Neither check finds your confidence off — which is not the same as proof that it is right.{}",
            sensitivity_note(d).map(|s| format!(" {s}.")).unwrap_or_default()
        ),
        Verdict::NoEvidenceOfMiscalibration => format!(
            "Nothing shows your confidence is off — but this is still a small record.{}",
            sensitivity_note(d).map(|s| format!(" {s}.")).unwrap_or_default()
        ),
        Verdict::InsufficientData => format!(
            "Too few resolved calls to read your calibration yet.{}",
            pending_due_note(d).map(|s| format!(" {s}.")).unwrap_or_default()
        ),
    };
    let evidence_tag = match d.eprocess {
        _ if d.verdict == Verdict::Withheld => "verdict withheld",
        Some(e) if e >= EVIDENCE_ALARM => "evidence: solid",
        Some(e) if e >= RECAL_MIN_E => "evidence: suggestive",
        _ if d.evidence_n < VERDICT_MIN_N => "evidence: too few to tell",
        _ => "evidence: no miscalibration found",
    };
    let footer = format!(
        "{} resolved · {} · offline & local — nothing left your machine",
        d.resolved_binary, evidence_tag
    );

    PlainSummary {
        headline,
        verdict_word,
        verdict_class,
        insights,
        actions,
        footer,
    }
}

// A calibration cat whose face is the state of your judgement. Its mood is chosen
// by a 0–100 calibration score — `|confidence gap|` folded into four 25-point bands
// — so the agent's standing reads at a glance before a single number is parsed.
// Pure ASCII faces, no emoji: emoji width is font-dependent and misaligns or boxes
// in many terminals (and looks broken inside a Markdown code block). The mood NAME
// and gloss carry the meaning; the emoji legend lives only in prose docs.
const CAT_DIALED: &str = "   /\\_/\\\n  ( ^.^ ) <3\n   > ^ <";
const CAT_CLOSE: &str = "   /\\_/\\\n  ( o.o )\n   > . <";
const CAT_DRIFT: &str = "   /\\_/\\\n  ( ;_; )\n   > _ <";
const CAT_OFF: &str = "   /\\_/\\\n  ( @_@ )\n   >< ><";
const CAT_SLEEPY: &str = "   /\\_/\\\n  ( -.- )  zzz\n   > ~ <";

struct Mood {
    art: &'static str,
    name: &'static str,
    gloss: String,
}

/// A calibration error this far above its own noise floor scores 0/100. Roughly
/// the miscalibration of saying 90% to coin flips.
const MOOD_WORST_EXCESS: f64 = 0.10;

/// Pick the cat's mood from the **size of the calibration error**, measured
/// against the noise floor for a record of this size and shape, and from
/// [`ReportData::verdict`] for the wording.
///
/// It used to key off `|confidence gap|`, which is why a ledger with a 0.160
/// calibration error and a −0.520 skill score displayed `[DIALED IN] calibration
/// 100/100 · well calibrated`: its overconfident half and its underconfident half
/// cancelled to a gap of −1e-15. A cat is the most screenshot-able thing this
/// program produces, so it is the last place a cancelling statistic belongs.
fn mood(d: &ReportData) -> Mood {
    // Only DIALED IN asks "is it over the floor", and it may drop to NOTHING OFF YET one
    // look in twenty for a calibrated forecaster. That costs a friendlier name, never a
    // false reassurance; the other names follow the size of the error.
    let excess = match (d.mcb, d.mcb_null_q95) {
        (Some(m), Some(f)) => Some((m - f).max(0.0)),
        (Some(m), None) => Some(m.max(0.0)),
        _ => None,
    };
    let score = if matches!(d.verdict, Verdict::InsufficientData | Verdict::Withheld) {
        None
    } else {
        excess.map(|e| (100.0 * (1.0 - (e / MOOD_WORST_EXCESS).min(1.0))).round() as u32)
    };
    let dir = match d.verdict {
        Verdict::InsufficientData => "not enough graded calls to judge yet",
        Verdict::Withheld => "verdict withheld — more than one in ten settled calls were voided",
        Verdict::Overconfident => "overconfident — you oversell",
        Verdict::Underconfident => "underconfident — you undersell",
        Verdict::BiasedYes => "leans yes — you over-predict that things happen",
        Verdict::BiasedNo => "leans no — you over-predict that things don't",
        Verdict::CalibratedButUninformative => "your confidence sorts nothing — fix that first",
        Verdict::NoEvidenceOfMiscalibration => "no miscalibration found",
        Verdict::MiscalibratedBothWays => {
            "miscalibrated both ways — the errors cancel in the average"
        }
    };
    // The face always follows the size of the calibration error; only the NAME
    // changes when the forecasts sort nothing. An inverted forecaster — 0.95s
    // that never happen, 0.05s that always do — is uninformative AND badly
    // miscalibrated, and should not get a gentle face just because the headline
    // finding is about ranking.
    let (art, band) = match score {
        None => (CAT_SLEEPY, "WARMING UP"),
        // "DIALED IN" is the same claim the words "well calibrated" used to make,
        // so it answers to the same bar: absence of evidence at 24 graded calls is
        // not evidence of calibration, and neither is a quiet e-process while the
        // calibration error sits above its own noise floor. Measured: 11 points
        // overconfident at n = 160 scored 90/100 and drew the happiest face in the
        // program while MCB was twice the floor. The friendliest cat answers to
        // BOTH instruments.
        // And, measured again on 0.5.0: 10 points overconfident at n = 120, MCB 1.13x
        // the floor, a test with a 15% chance of seeing it, drew "DIALED IN 99/100".
        // The bar the comment above states is "not above its floor", so that is the
        // test, and the test must have been able to see an error: past 80% for one
        // 30% too extreme.
        Some(s)
            if s >= 75
                && d.evidence_n >= VERDICT_CONFIDENT_N
                && mcb_ratio(d).is_none_or(|r| r <= 1.0)
                && d.sensitivity.is_none_or(|r| r >= DIALED_MIN_SENSITIVITY)
                && !easy_heavy(d) =>
        {
            (CAT_DIALED, "DIALED IN")
        }
        Some(s) if s >= 75 => (CAT_CLOSE, "NOTHING OFF YET"),
        Some(s) if s >= 50 => (CAT_CLOSE, "CLOSE"),
        Some(s) if s >= 25 => (CAT_DRIFT, "DRIFTING"),
        Some(_) => (CAT_OFF, "WAY OFF"),
    };
    let (art, name) = match d.verdict {
        Verdict::InsufficientData => (CAT_SLEEPY, "WARMING UP"),
        Verdict::Withheld => (CAT_SLEEPY, "WITHHELD"),
        Verdict::CalibratedButUninformative => (art, "UNINFORMATIVE"),
        _ => (art, band),
    };
    // A score out of 100 beside a test that could not have seen the error reads as a
    // grade it has not earned, so below even odds of catching one it is not printed.
    let blind = d.sensitivity.is_some_and(|r| r < 0.5);
    let gloss = match score {
        Some(_) if blind => {
            format!("{dir}, but at this record the test would miss most errors of 30%")
        }
        Some(s) if easy_heavy(d) => format!(
            "calibration {s}/100 · {dir} · {:.0}% of it near-certain calls",
            100.0 * d.easy_calls as f64 / d.resolved_binary.max(1) as f64
        ),
        Some(s) => format!("calibration {s}/100 · {dir}"),
        None => dir.to_string(),
    };
    Mood { art, name, gloss }
}

/// The report in plain English — for a developer skimming, or a newcomer who has
/// never heard of a Brier score. A rendering of the same `ReportData`; it computes
/// nothing.
pub fn render_plain(
    ledger: &Ledger,
    tag_filter: Option<&str>,
    bins: usize,
    today: NaiveDate,
) -> String {
    let d = ReportData::compute(ledger, tag_filter, bins, today);
    let mut out = String::new();
    let scope = d
        .tag
        .as_deref()
        .map(|t| format!("  [tag: {t}]"))
        .unwrap_or_default();
    let title = format!("ANAMNESIS — your judgement, in plain English{scope}");
    let _ = writeln!(out, "\n{title}");
    let _ = writeln!(out, "{}", "=".repeat(title.chars().count()));

    if d.is_empty() {
        let scope = d
            .tag
            .as_ref()
            .map(|t| format!(" tagged '{t}'"))
            .unwrap_or_default();
        let _ = writeln!(
            out,
            "\nNothing to reflect yet{scope}. You have {} open prediction(s) but none resolved.\nLog a belief with `ana add`, then `ana resolve` it once you find out — the\nmirror needs something to reflect.\n",
            d.open
        );
        return out;
    }

    let m = mood(&d);
    let _ = writeln!(out, "\n{}", m.art);
    let _ = writeln!(out, "  [{}]  {}", m.name, m.gloss);

    let s = plain_summary(&d);
    let _ = writeln!(out, "\n{}", s.headline);
    let _ = writeln!(
        out,
        "Based on {} resolved prediction(s).",
        d.resolved_binary
    );
    if !d.so_far.is_empty() && d.verdict != Verdict::Withheld {
        let calls: Vec<String> = d
            .so_far
            .iter()
            .map(|g| {
                format!(
                    "[{}] {:.0}%, {}",
                    g.id,
                    g.prob * 100.0,
                    if g.came_true { "came true" } else { "didn't" }
                )
            })
            .collect();
        let _ = writeln!(
            out,
            "Your graded calls so far, newest first: {}.",
            calls.join("; ")
        );
    }
    for ins in &s.insights {
        let _ = writeln!(out, "\n{}", ins.label);
        let _ = writeln!(out, "{}", wrap(&ins.answer, 74, "  "));
        let _ = writeln!(out, "  ↳ technical name: {}", ins.jargon);
    }
    let _ = writeln!(out, "\nSo what should you do?");
    for act in &s.actions {
        let _ = writeln!(out, "{}", wrap(act, 72, "    ").replacen("    ", "  • ", 1));
    }
    let _ = writeln!(out, "\n{}\n", s.footer);
    out
}

/// The editorial CSS for the calibration card — verbatim from the Claude Design
/// handoff (`Calibration Card.template.html`), with the single severity-driven
/// `--accent-seed` left as `__ACCENT__` for substitution. Inline only: no fonts,
/// scripts, or network; light + dark via `prefers-color-scheme`.
const CARD_CSS: &str = r#"  /* ============================================================
     ANAMNESIS · CALIBRATION CARD
     One file. Inline CSS only. No fonts, no scripts, no network.
     Opens offline by double-click. A mirror, not a dashboard.
     ============================================================ */

  :root {
    color-scheme: light dark;

    /* --- the one value driven by the verdict's severity --- */
    --accent-seed: __ACCENT__;         /* e.g. #1565c0 */
    --accent: var(--accent-seed);

    /* --- light palette (paper & ink) --- */
    --paper:    #efece4;   /* page behind the card */
    --card:     #fbfaf6;   /* the card surface     */
    --ink:      #1d1b16;   /* primary text         */
    --ink-soft: #3f3c34;   /* answers, body        */
    --muted:    #75716a;   /* captions, labels     */
    --faint:    #a39e93;   /* technical terms      */
    --hairline: #e2ddd2;   /* rules & ticks        */
    --shadow:   0 1px 2px rgba(40,34,20,.05), 0 18px 50px -28px rgba(40,34,20,.30);

    /* --- type --- */
    --serif: "Iowan Old Style", "Palatino Linotype", Palatino, "Book Antiqua", Georgia, "Times New Roman", serif;
    --sans: system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
    --mono: ui-monospace, "SF Mono", "JetBrains Mono", Menlo, Consolas, "Liberation Mono", monospace;
  }

  @media (prefers-color-scheme: dark) {
    :root {
      --paper:    #0f1012;
      --card:     #16181b;
      --ink:      #eae6dd;
      --ink-soft: #c4c0b6;
      --muted:    #8f8b81;
      --faint:    #6a665e;
      --hairline: #2a2c30;
      --shadow:   0 1px 2px rgba(0,0,0,.4), 0 24px 60px -30px rgba(0,0,0,.7);
      /* lift the accent off the dark ground so it reads as light */
      --accent: color-mix(in oklab, var(--accent-seed), white 30%);
    }
  }

  * { box-sizing: border-box; }

  html, body { margin: 0; }

  body {
    background: var(--paper);
    color: var(--ink);
    font-family: var(--sans);
    font-size: 16px;
    line-height: 1.5;
    -webkit-font-smoothing: antialiased;
    text-rendering: optimizeLegibility;
    min-height: 100vh;
    display: flex;
    align-items: flex-start;
    justify-content: center;
    padding: clamp(16px, 5vw, 64px);
  }

  .card {
    width: 100%;
    max-width: 660px;
    background: var(--card);
    border: 1px solid var(--hairline);
    border-radius: 7px;
    box-shadow: var(--shadow);
    overflow: hidden;
    position: relative;
  }

  /* the severity colour as a quiet spine across the top edge */
  .card::before {
    content: "";
    position: absolute;
    inset: 0 0 auto 0;
    height: 3px;
    background: var(--accent);
    opacity: .9;
  }

  .inner {
    padding: clamp(30px, 6.5vw, 60px) clamp(26px, 6vw, 60px) clamp(28px, 5vw, 48px);
  }

  /* ---------- masthead ---------- */
  .masthead {
    display: flex;
    align-items: baseline;
    justify-content: space-between;
    gap: 16px;
    margin-bottom: clamp(30px, 6vw, 52px);
  }
  .wordmark {
    font-family: var(--serif);
    font-size: 16px;
    letter-spacing: .02em;
    color: var(--ink);
  }
  .wordmark .dot { color: var(--accent); }
  .kicker {
    font-family: var(--sans);
    font-size: 11px;
    font-weight: 600;
    letter-spacing: .22em;
    text-transform: uppercase;
    color: var(--muted);
  }

  /* ---------- verdict + headline ---------- */
  .verdict {
    font-family: var(--serif);
    font-weight: 600;
    color: var(--accent);
    font-size: clamp(40px, 9.5vw, 66px);
    line-height: .98;
    letter-spacing: -.018em;
    margin: 0;
  }
  .headline {
    font-family: var(--serif);
    font-weight: 400;
    color: var(--ink);
    font-size: clamp(20px, 4.1vw, 27px);
    line-height: 1.34;
    letter-spacing: -.005em;
    max-width: 30ch;
    text-wrap: balance;
    margin: clamp(18px, 3.5vw, 26px) 0 0;
  }

  /* ---------- a hairline rule ---------- */
  .rule {
    height: 1px;
    background: var(--hairline);
    border: 0;
    margin: clamp(30px, 6vw, 46px) 0;
  }

  /* ---------- brier stat ---------- */
  .stat-label {
    font-size: 11px;
    font-weight: 600;
    letter-spacing: .2em;
    text-transform: uppercase;
    color: var(--muted);
    margin-bottom: 10px;
  }
  .brier {
    display: flex;
    align-items: baseline;
    gap: 18px;
    flex-wrap: wrap;
  }
  .brier-num {
    font-family: var(--sans);
    font-weight: 600;
    font-size: clamp(46px, 11vw, 64px);
    line-height: 1;
    letter-spacing: -.03em;
    color: var(--ink);
    font-variant-numeric: tabular-nums lining-nums;
  }
  .brier-caption {
    font-size: 13.5px;
    line-height: 1.45;
    color: var(--muted);
    max-width: 30ch;
  }

  /* ---------- confidence gauge ---------- */
  .gauge {
    margin-top: clamp(26px, 5vw, 38px);
    --pos: 50%;
  }
  .gauge-track {
    position: relative;
    height: 30px;
  }
  /* the baseline */
  .gauge-track::before {
    content: "";
    position: absolute;
    left: 0; right: 0; top: 50%;
    height: 2px;
    transform: translateY(-50%);
    background: var(--hairline);
    border-radius: 2px;
  }
  /* the "calibrated" reference at centre */
  .gauge-center {
    position: absolute;
    left: 50%; top: 50%;
    width: 1px; height: 22px;
    transform: translate(-50%, -50%);
    background: var(--faint);
  }
  /* the marker: a plumb line + dot, in the accent */
  .gauge-marker {
    position: absolute;
    left: var(--pos); top: 50%;
    transform: translate(-50%, -50%);
    width: 2px; height: 26px;
    background: var(--accent);
    border-radius: 2px;
  }
  .gauge-marker::after {
    content: "";
    position: absolute;
    left: 50%; top: 50%;
    width: 13px; height: 13px;
    transform: translate(-50%, -50%);
    background: var(--accent);
    border-radius: 50%;
    box-shadow: 0 0 0 4px var(--card);
  }
  .gauge-labels {
    display: grid;
    grid-template-columns: 1fr auto 1fr;
    margin-top: 12px;
    font-size: 11px;
    font-weight: 600;
    letter-spacing: .14em;
    text-transform: uppercase;
    color: var(--muted);
  }
  .gauge-labels span:nth-child(1) { text-align: left; }
  .gauge-labels span:nth-child(2) { text-align: center; color: var(--faint); }
  .gauge-labels span:nth-child(3) { text-align: right; }

  /* ---------- insight list ---------- */
  .insights {
    display: flex;
    flex-direction: column;
  }
  .insight {
    padding: clamp(22px, 4vw, 30px) 0;
    border-top: 1px solid var(--hairline);
  }
  .insight:first-child { border-top: 0; padding-top: 0; }
  .insight:last-child  { padding-bottom: 0; }
  .insight-q {
    font-family: var(--serif);
    font-size: clamp(18px, 3.4vw, 21px);
    font-weight: 600;
    line-height: 1.3;
    letter-spacing: -.005em;
    color: var(--ink);
    margin: 0;
    text-wrap: pretty;
  }
  .insight-a {
    font-family: var(--sans);
    font-size: 15.5px;
    line-height: 1.6;
    color: var(--ink-soft);
    margin: 10px 0 0;
    max-width: 56ch;
    text-wrap: pretty;
  }
  .insight-term {
    font-family: var(--mono);
    font-size: 11.5px;
    letter-spacing: .01em;
    color: var(--faint);
    margin: 12px 0 0;
  }

  /* ---------- what to do ---------- */
  .todo-label {
    font-size: 11px;
    font-weight: 600;
    letter-spacing: .2em;
    text-transform: uppercase;
    color: var(--muted);
    margin-bottom: clamp(16px, 3vw, 22px);
  }
  .actions {
    list-style: none;
    margin: 0;
    padding: 0;
    display: flex;
    flex-direction: column;
    gap: 14px;
  }
  .actions li {
    position: relative;
    padding-left: 26px;
    font-size: 16.5px;
    line-height: 1.5;
    color: var(--ink);
    max-width: 54ch;
    text-wrap: pretty;
  }
  .actions li::before {
    content: "";
    position: absolute;
    left: 4px; top: .62em;
    width: 6px; height: 6px;
    border-radius: 50%;
    background: var(--accent);
  }

  /* ---------- footer ---------- */
  .footer {
    margin-top: clamp(30px, 6vw, 46px);
    padding-top: clamp(20px, 4vw, 26px);
    border-top: 1px solid var(--hairline);
    font-size: 12.5px;
    line-height: 1.6;
    color: var(--muted);
    letter-spacing: .005em;
  }

  @media (max-width: 480px) {
    .masthead { flex-direction: column; gap: 6px; }
  }
"#;

/// A self-contained, offline HTML calibration card — the Claude Design "mirror"
/// rendered for real from this report. One file, inline CSS only, zero
/// JS/fonts/network; opens by double-click; light **and** dark. Your ledger never
/// leaves your machine. Built from the same `plain_summary` prose as the text view
/// so the two can't drift — Brier is the headline stat here, so it is dropped from
/// the insight list, exactly as the design lays it out.
pub fn render_html(
    ledger: &Ledger,
    tag_filter: Option<&str>,
    bins: usize,
    today: NaiveDate,
) -> String {
    let d = ReportData::compute(ledger, tag_filter, bins, today);
    let summary = (!d.is_empty()).then(|| plain_summary(&d));

    // Verdict + accent are defined even for an empty ledger.
    let (verdict_word, verdict_class): (String, &str) = match &summary {
        Some(s) => (s.verdict_word.clone(), s.verdict_class),
        None => ("Not enough data".to_string(), "unknown"),
    };
    let accent = match verdict_class {
        "under" => "#1565c0",
        "over" => "#c62828",
        "uninformative" => "#ef6c00",
        "both" => "#c62828",
        "good" => "#2e7d32",
        _ => "#757575",
    };
    let severity_class = match verdict_class {
        "under" => "underconfident",
        "over" => "overconfident",
        "uninformative" => "uninformative",
        "both" => "miscalibrated",
        // Not "well-calibrated": this token names a verdict of *no evidence found*,
        // and nothing downstream should be able to read calibration into it. No
        // stylesheet keys off this value.
        "good" => "no-miscalibration-found",
        _ => "not-enough-data",
    };

    let mut b = String::new();
    b.push_str(&format!(
        "<main class=\"card\" data-severity=\"{severity_class}\">\n    <div class=\"inner\">\n\
      <header class=\"masthead\">\n        <span class=\"wordmark\">Anamnesis<span class=\"dot\">.</span></span>\n        <span class=\"kicker\">Calibration</span>\n      </header>\n\
      <h1 class=\"verdict\">{}</h1>\n",
        esc(&verdict_word)
    ));

    match &summary {
        None => {
            b.push_str("      <p class=\"headline\">Log a belief and resolve it once you know — the mirror needs something to reflect.</p>\n");
            b.push_str(&format!(
                "      <p class=\"footer\">{} open · 0 resolved · offline &amp; local — nothing left your machine</p>\n",
                d.open
            ));
        }
        Some(s) => {
            b.push_str(&format!(
                "      <p class=\"headline\">{}</p>\n      <hr class=\"rule\" />\n",
                esc(&s.headline)
            ));
            // Brier headline stat + gauge. The design's scale: gauge_pos = 50 + gap·100
            // (so a −0.17 gap sits at 33, left of the calibrated centre).
            if let Some(brier) = d.brier {
                b.push_str(&format!(
                    "      <div>\n        <div class=\"stat-label\">Brier score</div>\n        <div class=\"brier\">\n          <span class=\"brier-num\">{brier:.2}</span>\n          <span class=\"brier-caption\">forecasting golf score — 0 perfect, 0.25 coin-flip, lower better</span>\n        </div>\n"
                ));
                if let Some(gap) = d.confidence_gap {
                    let pos = (50.0 + gap * 100.0).clamp(3.0, 97.0);
                    b.push_str(&format!(
                        "        <div class=\"gauge\" style=\"--pos: {pos:.0}%\">\n          <div class=\"gauge-track\">\n            <span class=\"gauge-center\"></span>\n            <span class=\"gauge-marker\"></span>\n          </div>\n          <div class=\"gauge-labels\">\n            <span>Undersell</span>\n            <span>Calibrated</span>\n            <span>Oversell</span>\n          </div>\n        </div>\n"
                    ));
                }
                b.push_str("      </div>\n      <hr class=\"rule\" />\n");
            }
            // Insights — Brier is the headline stat above, so leave it out of the list.
            let items: Vec<&Insight> = s
                .insights
                .iter()
                .filter(|i| i.jargon != "Brier score")
                .collect();
            if !items.is_empty() {
                b.push_str("      <section class=\"insights\">\n");
                for i in &items {
                    b.push_str(&format!(
                        "        <article class=\"insight\">\n          <p class=\"insight-q\">{}</p>\n          <p class=\"insight-a\">{}</p>\n          <p class=\"insight-term\">{}</p>\n        </article>\n",
                        esc(i.label),
                        esc(&i.answer),
                        esc(i.jargon)
                    ));
                }
                b.push_str("      </section>\n      <hr class=\"rule\" />\n");
            }
            // What to do.
            if !s.actions.is_empty() {
                b.push_str(
                    "      <div class=\"todo-label\">What to do</div>\n      <ul class=\"actions\">\n",
                );
                for a in &s.actions {
                    b.push_str(&format!("        <li>{}</li>\n", esc(a)));
                }
                b.push_str("      </ul>\n");
            }
            b.push_str(&format!(
                "      <p class=\"footer\">{}</p>\n",
                esc(&s.footer)
            ));
        }
    }

    b.push_str("    </div>\n  </main>");

    let css = CARD_CSS.replace("__ACCENT__", accent);
    format!(
        "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n<title>Anamnesis — Calibration Card</title>\n<style>\n{css}</style>\n</head>\n<body>\n  {b}\n</body>\n</html>\n"
    )
}

/// An embeddable 400×100 README badge — the SVG cousin of the card: verdict word,
/// Brier, and the same undersell↔oversell gauge. Verbatim from the Claude Design
/// `badge.template.svg`; every colour is a presentation attribute (not CSS) so it
/// survives GitHub's SVG sanitizer. Gauge marker at `gauge_x = 28 + 344·pos/100`,
/// the same `pos = 50 + gap·100` scale as the card.
pub fn render_badge_svg(
    ledger: &Ledger,
    tag_filter: Option<&str>,
    bins: usize,
    today: NaiveDate,
) -> String {
    let d = ReportData::compute(ledger, tag_filter, bins, today);
    let summary = (!d.is_empty()).then(|| plain_summary(&d));
    let (verdict_word, verdict_class): (String, &str) = match &summary {
        Some(s) => (s.verdict_word.clone(), s.verdict_class),
        None => ("Not enough data".to_string(), "unknown"),
    };
    let accent = match verdict_class {
        "under" => "#1565c0",
        "over" => "#c62828",
        "good" => "#2e7d32",
        _ => "#757575",
    };
    let brier = d
        .brier
        .map(|b| format!("{b:.2}"))
        .unwrap_or_else(|| "—".into());
    let pos = (50.0 + d.confidence_gap.unwrap_or(0.0) * 100.0).clamp(3.0, 97.0);
    let gauge_x = 28.0 + 344.0 * pos / 100.0;
    let v = esc(&verdict_word);
    format!(
        r##"<svg xmlns="http://www.w3.org/2000/svg" width="400" height="100" viewBox="0 0 400 100" role="img" aria-label="Anamnesis calibration: {v}, Brier {brier}">
  <title>Anamnesis calibration — {v} · Brier {brier}</title>

  <clipPath id="r"><rect x="1" y="1" width="398" height="98" rx="11"></rect></clipPath>
  <rect class="card" x="1" y="1" width="398" height="98" rx="11" fill="#fbfaf6" stroke="#e2ddd2"></rect>
  <g clip-path="url(#r)"><rect class="spine" x="0" y="0" width="5" height="100" fill="{accent}"></rect></g>

  <text class="verdict" x="28" y="40" fill="{accent}" font-family="&#39;Iowan Old Style&#39;,Palatino,Georgia,&#39;Times New Roman&#39;,serif" font-size="25" font-weight="600">{v}</text>
  <text class="lab" x="372" y="24" text-anchor="end" fill="#75716a" font-family="system-ui,-apple-system,&#39;Segoe UI&#39;,Roboto,sans-serif" font-size="9.5" font-weight="600" letter-spacing="2">BRIER</text>
  <text class="brier" x="372" y="45" text-anchor="end" fill="#1d1b16" font-family="system-ui,-apple-system,&#39;Segoe UI&#39;,Roboto,sans-serif" font-size="26" font-weight="600" letter-spacing="-1">{brier}</text>

  <line class="track" x1="28" y1="66" x2="372" y2="66" stroke="#e2ddd2" stroke-width="2" stroke-linecap="round"></line>
  <line class="center" x1="200" y1="59" x2="200" y2="73" stroke="#a39e93" stroke-width="1"></line>
  <line class="mark" x1="{gauge_x:.1}" y1="57" x2="{gauge_x:.1}" y2="75" stroke="{accent}" stroke-width="2" stroke-linecap="round"></line>
  <circle class="dot" cx="{gauge_x:.1}" cy="66" r="5" fill="{accent}" stroke="#fbfaf6" stroke-width="3"></circle>

  <text class="foot" x="28" y="90" fill="#75716a" font-family="system-ui,-apple-system,&#39;Segoe UI&#39;,Roboto,sans-serif" font-size="11" letter-spacing="0.3">anamnesis · calibration · offline &amp; local</text>
</svg>
"##
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::{Claim, Forecast, NumericForecast, Outcome, Resolution};
    use chrono::{TimeZone, Utc};

    fn now() -> chrono::DateTime<Utc> {
        Utc.with_ymd_and_hms(2025, 1, 1, 12, 0, 0).unwrap()
    }

    /// Fixed "today" for deterministic reports (overdue is relative to this).
    fn td() -> NaiveDate {
        NaiveDate::from_ymd_opt(2026, 1, 1).unwrap()
    }

    fn binary(id: &str, prob: f64, happened: bool, tags: &[&str]) -> Claim {
        Claim {
            id: id.into(),
            statement: format!("claim {id}"),
            created_at: now(),
            // A past due date, so the claim enters the evidence sequence. The
            // sequential test orders by resolve-by precisely because that date is
            // chosen before the outcome is known.
            horizon_days: None,
            resolve_by: Some(NaiveDate::from_ymd_opt(2025, 6, 1).unwrap()),
            tags: tags.iter().map(|s| s.to_string()).collect(),
            kind: crate::model::ClaimKind::Binary,
            stake: 1.0,
            forecasts: vec![Forecast {
                at: now(),
                prob: Some(prob),
                interval: None,
                because: None,
            }],
            resolution: Some(Resolution {
                at: now(),
                outcome: Some(if happened {
                    Outcome::True
                } else {
                    Outcome::False
                }),
                value: None,
                note: None,
                resolved_by: None,
            }),
            void: None,
            check: None,
            extra: Default::default(),
            amendments: Vec::new(),
        }
    }

    fn numeric(id: &str, low: f64, high: f64, level: f64, value: f64) -> Claim {
        Claim {
            id: id.into(),
            statement: format!("num {id}"),
            created_at: now(),
            horizon_days: None,
            resolve_by: None,
            tags: vec![],
            kind: crate::model::ClaimKind::Numeric,
            stake: 1.0,
            forecasts: vec![Forecast {
                at: now(),
                prob: None,
                interval: Some(NumericForecast { low, high, level }),
                because: None,
            }],
            resolution: Some(Resolution {
                at: now(),
                outcome: None,
                value: Some(value),
                note: None,
                resolved_by: None,
            }),
            void: None,
            check: None,
            extra: Default::default(),
            amendments: Vec::new(),
        }
    }

    #[test]
    fn empty_ledger_renders_guidance() {
        let r = render(&Ledger::default(), None, 10, td());
        assert!(r.contains("No resolved claims yet"));
        // JSON of an empty ledger is still well-formed with null metrics.
        let j = render_json(&Ledger::default(), None, 10, td());
        let v: serde_json::Value = serde_json::from_str(&j).unwrap();
        assert_eq!(v["resolved"], 0);
        assert!(v["brier"].is_null());
    }

    #[test]
    fn json_has_no_nan_and_parses() {
        let ledger = Ledger {
            claims: vec![
                binary("a", 0.9, true, &["tech"]),
                binary("b", 0.9, false, &["tech"]),
                binary("c", 0.2, false, &["world"]),
                binary("d", 0.8, true, &["world"]),
            ],
            ..Default::default()
        };
        let j = render_json(&ledger, None, 10, td());
        // Must be valid JSON and contain no bare NaN/Infinity tokens.
        let v: serde_json::Value = serde_json::from_str(&j).unwrap();
        assert!(!j.contains("NaN") && !j.contains("Infinity"));
        assert_eq!(v["resolved"], 4);
        assert!(v["brier"].as_f64().unwrap() > 0.0);
        assert!(v["auc"].as_f64().is_some());
        // Empty calibration bins serialise observed as null, not NaN.
        let cal = v["calibration"].as_array().unwrap();
        assert!(cal.iter().any(|b| b["observed"].is_null()));
    }

    #[test]
    fn text_and_json_agree_on_brier() {
        let ledger = Ledger {
            claims: vec![binary("a", 0.7, true, &[]), binary("b", 0.3, false, &[])],
            ..Default::default()
        };
        let data = ReportData::compute(&ledger, None, 10, td());
        let v: serde_json::Value =
            serde_json::from_str(&render_json(&ledger, None, 10, td())).unwrap();
        assert_eq!(v["brier"].as_f64().unwrap(), data.brier.unwrap());
    }

    #[test]
    fn numeric_section_appears_and_scores() {
        // Two 80% intervals; one misses badly → coverage 50% < 80% (overconfident).
        let ledger = Ledger {
            claims: vec![
                numeric("n1", 10.0, 20.0, 0.8, 15.0), // inside
                numeric("n2", 10.0, 20.0, 0.8, 40.0), // outside
            ],
            ..Default::default()
        };
        let r = render(&ledger, None, 10, td());
        assert!(r.contains("Numeric forecasts"));
        assert!(r.contains("TOO NARROW"));
        let v: serde_json::Value =
            serde_json::from_str(&render_json(&ledger, None, 10, td())).unwrap();
        assert_eq!(v["numeric"]["count"], 2);
        assert_eq!(v["numeric"]["empirical_coverage"].as_f64().unwrap(), 0.5);
    }

    #[test]
    fn tag_filter_limits_and_titles() {
        let ledger = Ledger {
            claims: vec![
                binary("a", 0.9, true, &["tech"]),
                binary("b", 0.2, false, &["world"]),
            ],
            ..Default::default()
        };
        let r = render(&ledger, Some("tech"), 10, td());
        assert!(r.contains("[tag: tech]"));
        assert!(!r.contains("By domain")); // suppressed when filtered to one tag
    }

    #[test]
    fn plain_and_html_views_explain_and_render() {
        // Enough claims, and enough miscalibration, to reach a real verdict:
        // three claims is `insufficient_data`, which is its own test below.
        let ledger = Ledger {
            claims: (0..40)
                .map(|i| binary(&format!("c{i}"), 0.9, i % 3 == 0, &[]))
                .collect(),
            ..Default::default()
        };
        let p = render_plain(&ledger, None, 10, td());
        assert!(p.contains("plain English"));
        assert!(p.contains("golf score")); // Brier explained, never left bare
        assert!(p.contains("technical name:")); // jargon named, not hidden
        assert!(p.contains("what should you do")); // the action list
                                                   // The calibration cat shows one of its moods.
        assert!(["DIALED IN", "CLOSE", "DRIFTING", "WAY OFF", "WARMING UP"]
            .iter()
            .any(|m| p.contains(m)));

        let h = render_html(&ledger, None, 10, td());
        assert!(h.contains("<!DOCTYPE html"));
        assert!(h.contains("class=\"card\""));
        assert!(h.contains("class=\"verdict\""));
        assert!(h.contains("golf score")); // Brier caption
        assert!(!h.contains("__ACCENT__")); // the accent placeholder was filled
        assert!(h.contains("#c62828")); // this ledger is overconfident → red accent seed
                                        // Brier is the headline stat, so it must NOT also appear as an insight term.
        assert!(!h.contains(">Brier score</p>"));

        // Scenario 3: a handful of sure-and-right calls is not a verdict.
        let tiny = Ledger {
            claims: vec![
                binary("a", 1.0, true, &[]),
                binary("b", 1.0, true, &[]),
                binary("c", 1.0, true, &[]),
                binary("d", 0.0, false, &[]),
                binary("e", 0.0, false, &[]),
            ],
            ..Default::default()
        };
        let td5 = ReportData::compute(&tiny, None, 10, td());
        assert_eq!(td5.verdict, Verdict::InsufficientData);
        assert!(
            td5.log_score.unwrap().is_finite(),
            "log score must not be inf"
        );
        let tp = render_plain(&tiny, None, 10, td());
        // No verdict, no praise — five correct calls is five correct calls.
        assert!(
            tp.contains("Too few resolved calls") && tp.contains("WARMING UP"),
            "must say so plainly:\n{tp}"
        );
        for banned in ["DIALED IN", "Well calibrated", "confidence is honest"] {
            assert!(!tp.contains(banned), "{banned:?} at n=5:\n{tp}");
        }
        assert!(render_badge_svg(&tiny, None, 10, td()).contains("Not enough data"));

        // Both views survive an empty ledger without panicking.
        assert!(render_plain(&Ledger::default(), None, 10, td()).contains("Nothing to reflect"));
        assert!(render_html(&Ledger::default(), None, 10, td()).contains("<!DOCTYPE html"));

        // Badge: valid SVG, real verdict + accent, no leftover template placeholders.
        let svg = render_badge_svg(&ledger, None, 10, td());
        assert!(svg.contains("<svg") && svg.contains("</svg>"));
        assert!(svg.contains("Overconfident")); // this ledger is overconfident
        assert!(svg.contains("#c62828")); // → red accent
        assert!(!svg.contains("{{")); // every placeholder filled
        assert!(render_badge_svg(&Ledger::default(), None, 10, td()).contains("Not enough data"));
    }

    /// Before there is a verdict, a new user still sees their calls: ids, chances, what
    /// happened. Never the statements (the JSON reaches a model through MCP).
    #[test]
    fn a_new_ledger_lists_its_graded_calls_and_a_full_one_does_not() {
        let few = Ledger {
            claims: vec![
                binary("aa1", 0.9, false, &[]),
                binary("bb2", 0.6, true, &[]),
            ],
            ..Default::default()
        };
        let d = ReportData::compute(&few, None, 10, td());
        assert_eq!(d.so_far.len(), 2);
        let miss = d.so_far.iter().find(|g| g.id == "aa1").unwrap();
        assert!(!miss.came_true && (miss.brier - 0.81).abs() < 1e-12);
        let text = render(&few, None, 10, td());
        assert!(
            text.contains("Graded so far")
                && text.contains("[aa1]")
                && text.contains("costs the most"),
            "{text}"
        );
        assert!(render_plain(&few, None, 10, td()).contains("Your graded calls so far"));
        assert!(
            !render_json(&few, None, 10, td()).contains("claim aa1"),
            "a statement leaked"
        );

        let many = Ledger {
            claims: (0..30)
                .map(|i| binary(&format!("m{i}"), 0.7, i % 10 < 7, &[]))
                .collect(),
            ..Default::default()
        };
        assert!(ReportData::compute(&many, None, 10, td()).so_far.is_empty());
    }

    /// A quiet test that would miss most 30% errors does not get the green badge.
    #[test]
    fn a_weak_quiet_test_is_not_shown_in_green() {
        // Two confidence levels, each hit at its stated rate: nothing to find, and too
        // few calls for the test to find much if there were.
        let claims = (0..40)
            .map(|i| {
                let (p, hit) = if i < 20 {
                    (0.6, i % 10 < 6)
                } else {
                    (0.8, i % 10 < 8)
                };
                binary(&format!("w{i}"), p, hit, &[])
            })
            .collect();
        let ledger = Ledger {
            claims,
            ..Default::default()
        };
        let d = ReportData::compute(&ledger, None, 10, td());
        assert_eq!(d.verdict, Verdict::NoEvidenceOfMiscalibration);
        assert!(
            d.sensitivity.unwrap() < DIALED_MIN_SENSITIVITY,
            "{:?}",
            d.sensitivity
        );
        let svg = render_badge_svg(&ledger, None, 10, td());
        assert!(svg.contains("Nothing found yet"), "{svg}");
        assert!(!svg.contains("#2e7d32"), "green on a weak test:\n{svg}");
        assert!(!svg.contains("No miscalibration found"));
    }

    /// The old version of this test was called `mood_bands_track_the_confidence_gap`,
    /// and the name was the bug: the gap cancels over- against under-confidence,
    /// so the friendliest face in the program sat on top of the worst ledger in
    /// the test suite. The mood now tracks the SIZE of the calibration error
    /// against the noise floor for a record of that size.
    #[test]
    fn mood_tracks_the_size_of_the_calibration_error() {
        // Four sure-and-right calls is not calibration evidence, it is four calls.
        let tiny = Ledger {
            claims: vec![
                binary("a", 1.0, true, &[]),
                binary("b", 1.0, true, &[]),
                binary("c", 0.0, false, &[]),
                binary("d", 0.0, false, &[]),
            ],
            ..Default::default()
        };
        assert_eq!(
            mood(&ReportData::compute(&tiny, None, 10, td())).name,
            "WARMING UP",
            "a four-claim ledger must not earn the best face in the program"
        );

        // Wildly overconfident, and enough of it to be demonstrated.
        let bad = Ledger {
            claims: (0..40)
                .map(|i| {
                    binary(
                        &format!("c{i}"),
                        if i % 2 == 0 { 0.95 } else { 0.05 },
                        i % 2 != 0,
                        &[],
                    )
                })
                .collect(),
            ..Default::default()
        };
        // Its 0.95s never happen and its 0.05s always do: perfectly inverted, so
        // the isotonic fit pools everything and DSC is 0. The headline finding is
        // that the ranking carries no information — but the FACE still tracks the
        // size of the calibration error, which is enormous.
        let d = ReportData::compute(&bad, None, 10, td());
        assert_eq!(d.verdict, Verdict::CalibratedButUninformative);
        assert_eq!(mood(&d).name, "UNINFORMATIVE");
        assert_eq!(
            mood(&d).art,
            CAT_OFF,
            "an inverted forecaster must not look calm"
        );

        // Nothing to judge → the sleepy face.
        assert_eq!(
            mood(&ReportData::compute(&Ledger::default(), None, 10, td())).name,
            "WARMING UP"
        );
    }

    /// Finding B, as a unit test: the single ledger that most embarrassed the
    /// old code must never again be praised on any surface.
    #[test]
    fn cancelling_errors_are_never_called_well_calibrated() {
        let mut claims: Vec<Claim> = Vec::new();
        for i in 0..50 {
            claims.push(binary(&format!("f{i}"), 0.9, i % 2 == 0, &[]));
        }
        for i in 0..50 {
            claims.push(binary(&format!("s{i}"), 0.6, true, &[]));
        }
        let ledger = Ledger {
            claims,
            ..Default::default()
        };
        let d = ReportData::compute(&ledger, None, 10, td());

        // The gap that fooled the old code is still ~0 — that is the point.
        assert!(d.confidence_gap.unwrap().abs() < 1e-9);
        // DSC is exactly 0 here — higher stated confidence went with a LOWER hit
        // rate, so isotonic regression collapses both groups to one value. That
        // outranks anything about the level: telling this forecaster to shade
        // their numbers down would not help, because their numbers carry no
        // information about which calls come true in the first place.
        assert_eq!(d.verdict, Verdict::CalibratedButUninformative);
        assert!(d.mcb.unwrap() > d.mcb_null_q95.unwrap());
        assert_eq!(d.dsc.unwrap(), 0.0, "the forecasts order nothing");

        for view in [
            render(&ledger, None, 10, td()),
            render_plain(&ledger, None, 10, td()),
            render_html(&ledger, None, 10, td()),
            render_badge_svg(&ledger, None, 10, td()),
            render_json(&ledger, None, 10, td()),
        ] {
            for banned in [
                "DIALED IN",
                "Well calibrated",
                "well calibrated",
                "well-calibrated",
                "confidence is honest",
                "Keep doing what you're doing",
            ] {
                assert!(!view.contains(banned), "{banned:?} appeared in:\n{view}");
            }
        }
    }
}