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
//! `ana` — the command-line face of Anamnesis.
//!
//! A deliberately small surface: record a belief, revise it, resolve it, and
//! then look in the mirror. Beliefs come in two flavours — **binary** (a yes/no
//! proposition with a probability) and **numeric** (a quantity with a credible
//! interval). Every command also speaks `--json`, so an agent, script, or future
//! UI can drive it without scraping prose.

use std::path::PathBuf;
use std::process::ExitCode;

use chrono::{NaiveDate, Utc};
use clap::{Parser, Subcommand, ValueEnum};
use serde_json::{json, Value};

use anamnesis::model::{
    compose_reasoning, gen_id, normalize_tags, Claim, ClaimKind, Forecast, NumericForecast,
    Outcome, Resolution,
};
use anamnesis::scoring::{self, NumericSample};
use anamnesis::untrusted::printable;
use anamnesis::{mcp, report, store};

#[derive(Parser)]
#[command(
    name = "ana",
    version,
    about = "Anamnesis — an instrument against self-deception",
    long_about = "Record what you believe, how sure you are, and why — before the outcome is \
known. Later, face the real shape of your judgement: where you are overconfident, whether you \
can tell truth from falsehood, and how honestly you change your mind."
)]
struct Cli {
    /// Ledger file to use (overrides $ANAMNESIS_DATA; default ~/.anamnesis.json)
    #[arg(long, global = true, value_name = "FILE")]
    data: Option<PathBuf>,

    /// Emit machine-readable JSON instead of human text
    #[arg(long, global = true)]
    json: bool,

    #[command(subcommand)]
    cmd: Cmd,
}

#[derive(Subcommand)]
enum Cmd {
    /// Record a new belief. Use --prob for a yes/no claim, or --interval for a number.
    Add {
        /// The falsifiable statement
        statement: String,
        /// BINARY: probability it is true: 0.7, .7 or 70%
        #[arg(short, long, value_parser = prob_arg, allow_negative_numbers = true)]
        prob: Option<f64>,
        /// NUMERIC: credible interval "LOW..HIGH" (e.g. 120..180)
        #[arg(long, value_name = "LOW..HIGH")]
        interval: Option<String>,
        /// NUMERIC: confidence level of the interval (default 0.80)
        #[arg(long, default_value_t = 0.80)]
        level: f64,
        /// Date you expect to know the answer (YYYY-MM-DD)
        #[arg(long, value_name = "YYYY-MM-DD")]
        by: Option<String>,
        /// Comma-separated tags
        #[arg(long, value_delimiter = ',')]
        tags: Vec<String>,
        /// The reasoning behind the forecast — what hindsight will try to erase
        #[arg(long)]
        because: Option<String>,
        /// How much this call MATTERS (≥ 0; default 1) — weights the Brier toward
        /// your consequential predictions
        #[arg(long, default_value_t = 1.0)]
        stake: f64,
        /// BINARY: a SECOND, deliberately-opposite estimate ("consider the
        /// opposite"); the logged probability is the average of the two
        /// (dialectical bootstrapping — the wisdom of your own crowd)
        #[arg(long, value_parser = prob_arg, allow_negative_numbers = true)]
        second_prob: Option<f64>,
        /// The OUTSIDE VIEW: a reference class of similar past cases and its base
        /// rate, recorded with the forecast
        #[arg(long)]
        reference_class: Option<String>,
        /// The exact command that settles this claim, e.g. "cargo test", fixed NOW,
        /// before the outcome. It is then settled only by `ana run <id> -- <command>`,
        /// which grades it from the command's own exit status; `ana resolve` refuses it.
        #[arg(long, value_name = "COMMAND")]
        check: Option<String>,
    },
    /// Run the command a claim was pinned to, and grade the claim from its exit status
    Run {
        id: String,
        /// The command, after `--`. It must be exactly the one the claim was logged
        /// with (`ana add --check`); anything else is refused and not run.
        #[arg(last = true, required = true, num_args = 1.., allow_hyphen_values = true)]
        command: Vec<String>,
    },
    /// Revise a belief (history is preserved). Match the claim's kind.
    Update {
        id: String,
        /// BINARY: new probability: 0.7, .7 or 70%
        #[arg(short, long, value_parser = prob_arg, allow_negative_numbers = true)]
        prob: Option<f64>,
        /// NUMERIC: new interval "LOW..HIGH"
        #[arg(long, value_name = "LOW..HIGH")]
        interval: Option<String>,
        /// NUMERIC: confidence level (defaults to the claim's previous level)
        #[arg(long)]
        level: Option<f64>,
        #[arg(long)]
        because: Option<String>,
    },
    /// Resolve a belief. BINARY: yes/no. NUMERIC: --value N.
    Resolve {
        id: String,
        /// BINARY outcome: yes/true/y or no/false/n, in any case
        #[arg(value_enum, ignore_case = true)]
        outcome: Option<OutcomeArg>,
        /// NUMERIC outcome: the value that occurred
        #[arg(long)]
        value: Option<f64>,
        /// A post-mortem: with hindsight, what did you miss?
        #[arg(long)]
        note: Option<String>,
    },
    /// List beliefs (default: all)
    List {
        #[arg(long)]
        open: bool,
        #[arg(long)]
        resolved: bool,
        #[arg(long)]
        due: bool,
        /// Only claims carrying this exact tag (e.g. project:anamnesis)
        #[arg(long)]
        tag: Option<String>,
        /// Only annulled claims — the questions that turned out unanswerable
        #[arg(long)]
        void: bool,
    },
    /// Show the full history of one belief — the palimpsest of your mind
    Show { id: String },
    /// The calibration report: the real shape of your judgement
    Report {
        #[arg(long)]
        tag: Option<String>,
        #[arg(long, default_value_t = 10)]
        bins: usize,
        /// Plain-English view: every number translated into what it means for you
        #[arg(long)]
        plain: bool,
        /// Self-contained, offline HTML card (redirect to a file: `> card.html`)
        #[arg(long)]
        html: bool,
        /// Embeddable 400×100 README badge as SVG (redirect: `> badge.svg`)
        #[arg(long)]
        badge: bool,
    },
    /// Should you act on it? Corrects a stated probability through your earned
    /// recalibration map, then applies a stake-aware threshold: PROCEED / VERIFY / ABSTAIN.
    Decide {
        /// Your stated success probability: 0.7, .7 or 70%
        #[arg(long, short = 'p', value_parser = prob_arg, allow_negative_numbers = true)]
        prob: f64,
        /// Cost of a wrong action relative to one verification (1 = ordinary; raise it
        /// for consequential or irreversible calls — the bar to proceed climbs with it)
        #[arg(long, default_value_t = 1.0)]
        stake: f64,
        /// Cost of a verification step, in the same unit as stake
        #[arg(long, default_value_t = 0.2)]
        verify_cost: f64,
        /// Scope the correction map to claims carrying this tag (e.g. kind:estimate)
        #[arg(long)]
        tag: Option<String>,
    },
    /// Serve as a Model Context Protocol server over stdio — exposes
    /// predict/resolve/calibration/recalibrate/decide/list as tools for any MCP-capable agent.
    Mcp,
    /// Run a Claude Code hook: reads the hook JSON on stdin, writes the
    /// hookSpecificOutput on stdout. Replaces the shell scripts (and `jq`).
    Hook {
        /// Which hook is firing
        #[arg(value_enum)]
        event: HookEvent,
    },
    /// Try the tool on a fictional year of predictions: builds a demo ledger in
    /// a temporary directory, reports on it, and never touches your own.
    Demo {
        /// Write the demo ledger here instead of a temporary file, to poke at it
        #[arg(long)]
        keep: Option<PathBuf>,
        /// Plain-English report instead of the technical one
        #[arg(long)]
        plain: bool,
    },
    /// Export the ledger with every free-text field removed, so a real record
    /// can be published as evidence without publishing what it was about.
    Export {
        /// Strip statements, reasoning and notes; keep the numbers. Required —
        /// there is no un-anonymized export, because the obvious mistake is to
        /// publish one by accident.
        #[arg(long)]
        anonymize: bool,
        /// Write here instead of stdout
        #[arg(long)]
        out: Option<PathBuf>,
        /// Keep only these tag namespaces (default: kind, who, model, project)
        #[arg(long)]
        keep_tags: Option<String>,
    },
    /// Import an existing prediction history from CSV, so day one has a report.
    Import {
        /// CSV file. Columns: statement, prob, created, resolve_by, outcome,
        /// resolved_at, tags. Only `statement` and `prob` are required.
        file: PathBuf,
        /// Parse and report what would be imported, without writing anything
        #[arg(long)]
        dry_run: bool,
    },
    /// Annul an ambiguous or unanswerable question: it keeps its place in the
    /// history but is excluded from every score, the way a forecasting platform
    /// annuls a question rather than grading it.
    Void {
        /// Claim id, or any unambiguous prefix of one
        id: String,
        /// Why this question cannot fairly be graded
        #[arg(long)]
        reason: String,
    },
    /// Fix a typo in a statement, or correct its tags. Pre-resolution only, and
    /// never the probability or the timestamps — those are the record.
    Amend {
        /// Claim id, or any unambiguous prefix of one
        id: String,
        /// Replacement statement
        #[arg(long)]
        statement: Option<String>,
        /// Replacement tags, comma-separated (replaces the whole set)
        #[arg(long)]
        tags: Option<String>,
    },
    /// The weekly ON/OFF trial of the whole tool (docs/MEASUREMENT.md, addendum 4):
    /// `start` enrols once, `status` says which week it is without naming the arm.
    Trial {
        #[arg(value_enum)]
        action: TrialAction,
        /// The first Monday (YYYY-MM-DD); default: the first one the protocol allows
        #[arg(long, value_parser = parse_date)]
        from: Option<NaiveDate>,
        /// Pairs of weeks
        #[arg(long, default_value_t = anamnesis::trial::DEFAULT_PAIRS)]
        pairs: u32,
    },
    /// Print where everything lives: both ledger paths, which environment
    /// variables are overriding them, the lock and backup files, and the version.
    Where,
}

impl Cmd {
    /// Commands that write the ledger, and therefore need the exclusive lock
    /// held across the whole load-modify-save.
    fn mutates(&self) -> bool {
        matches!(
            self,
            Cmd::Add { .. }
                | Cmd::Update { .. }
                | Cmd::Resolve { .. }
                | Cmd::Void { .. }
                | Cmd::Amend { .. }
                | Cmd::Import { .. }
        )
    }
}

#[derive(Clone, Copy, ValueEnum)]
enum TrialAction {
    Start,
    Status,
}

/// The hook events `ana hook` understands.
#[derive(Clone, Copy, ValueEnum)]
enum HookEvent {
    SessionStart,
    UserPrompt,
    PostTool,
    PreTool,
    PostToolFailure,
    Stop,
}

impl From<HookEvent> for anamnesis::hook::Event {
    fn from(e: HookEvent) -> Self {
        match e {
            HookEvent::SessionStart => anamnesis::hook::Event::SessionStart,
            HookEvent::UserPrompt => anamnesis::hook::Event::UserPrompt,
            HookEvent::PostTool => anamnesis::hook::Event::PostTool,
            HookEvent::PreTool => anamnesis::hook::Event::PreTool,
            HookEvent::PostToolFailure => anamnesis::hook::Event::PostToolFailure,
            HookEvent::Stop => anamnesis::hook::Event::Stop,
        }
    }
}

#[derive(Clone, Copy, ValueEnum)]
enum OutcomeArg {
    #[value(alias = "true", alias = "y")]
    Yes,
    #[value(alias = "false", alias = "n")]
    No,
}

impl From<OutcomeArg> for Outcome {
    fn from(o: OutcomeArg) -> Self {
        match o {
            OutcomeArg::Yes => Outcome::True,
            OutcomeArg::No => Outcome::False,
        }
    }
}

fn main() -> ExitCode {
    let cli = Cli::parse();
    // `ana run` hands back the command's own exit code, so it cannot go through
    // `run`, whose every error becomes exit status 1.
    if let Cmd::Run { id, command } = &cli.cmd {
        return match cmd_run(&cli, id, command) {
            Ok(code) => code,
            Err(msg) => {
                eprintln!("error: {msg}");
                ExitCode::FAILURE
            }
        };
    }
    match run(cli) {
        Ok(()) => ExitCode::SUCCESS,
        Err(msg) => {
            eprintln!("error: {msg}");
            ExitCode::FAILURE
        }
    }
}

/// `ana run <id> -- <command>`: run the command a claim was pinned to, and settle the
/// claim from the process's own exit status.
///
/// Three things are deliberate. The ledger is looked at *without* the lock and the lock
/// is taken only to write the answer, because a test run can take minutes and holding
/// the lock across it blocked every other writer (and the hooks, which also lock). A
/// command that is not the pinned one is refused *before* it is run. And the pinned text
/// is only compared, never executed: the command that runs is the one the caller typed.
fn cmd_run(cli: &Cli, id: &str, command: &[String]) -> Result<ExitCode, String> {
    use anamnesis::hook::{judge_run, RunJudgement};
    use anamnesis::model::{collapse_spaces, ResolvedBy};
    use anamnesis::untrusted::{line, MAX_LINE};

    let path = data_path(cli)?;
    let ledger = store::load(&path).map_err(|e| load_error(&path, e))?;
    let idx = ledger.index_of(id)?;
    let c = &ledger.claims[idx];
    let cid = c.id.clone();
    if c.is_void() {
        return Err(format!("[{cid}] is void, so there is nothing to settle"));
    }
    if c.is_resolved() {
        return Err(format!("[{cid}] is already resolved"));
    }
    if !matches!(c.kind, ClaimKind::Binary) {
        return Err(format!(
            "[{cid}] is a numeric claim; an exit status settles a yes/no claim"
        ));
    }
    let Some(check) = c.check.clone() else {
        return Err(format!(
            "[{cid}] has no check pinned, so there is nothing to hold the command to. Log a claim with --check \"<command>\", or settle this one with `ana resolve`."
        ));
    };
    if !c.check_matches(command) {
        return Err(format!(
            "[{cid}] is pinned to `{}`, and you gave `{}`. Nothing was run. The command is fixed when the claim is logged so that it cannot be chosen once the outcome is known.",
            line(&check, MAX_LINE),
            line(&command.join(" "), MAX_LINE)
        ));
    }
    drop(ledger);

    let ran = anamnesis::check::run_command(command)
        .map_err(|e| format!("could not start `{}`: {e}", line(&command[0], 80)))?;
    let Some(code) = ran.code else {
        eprintln!(
            "ana: the command was ended by a signal, so there is no exit status and [{cid}] was not graded. It is still open."
        );
        return Ok(ExitCode::FAILURE);
    };
    // The command's own code is ana's, so `ana run -- cargo test` can stand in for it.
    let exit = ExitCode::from(anamnesis::check::exit_byte(code));
    let cmdline = collapse_spaces(&command.join(" "));
    let happened = match judge_run(command, i64::from(code), &ran.facts) {
        RunJudgement::Passed => true,
        RunJudgement::Failed => false,
        RunJudgement::NotGraded(why) => {
            eprintln!(
                "ana: `{}` exited {code}, but {why}, so [{cid}] was not graded. It is still open.",
                line(&cmdline, MAX_LINE)
            );
            return Ok(exit);
        }
    };

    // Only now take the lock, and look again: the claim may have changed while the
    // command ran.
    let _guard = store::lock(&path).map_err(|e| format!("locking {}: {e}", path.display()))?;
    let mut ledger = store::load(&path).map_err(|e| load_error(&path, e))?;
    let idx = ledger.index_of(&cid)?;
    {
        let c = &ledger.claims[idx];
        if c.is_resolved() || c.is_void() || !c.check_matches(command) {
            eprintln!(
                "ana: [{cid}] changed while the command ran, so it was not graded. Nothing was written."
            );
            return Ok(exit);
        }
    }
    let prob = ledger.claims[idx].first_prob().unwrap_or(0.5);
    ledger.claims[idx].resolution = Some(Resolution {
        at: Utc::now(),
        outcome: Some(if happened {
            Outcome::True
        } else {
            Outcome::False
        }),
        value: None,
        note: Some(format!("auto: `{cmdline}` exited {code} (ana run)")),
        resolved_by: Some(ResolvedBy::Auto),
    });
    store::save(&path, &ledger).map_err(|e| format!("saving: {e}"))?;

    let brier = (prob - if happened { 1.0 } else { 0.0 }).powi(2);
    if cli.json {
        out_json(json!({
            "id": cid, "outcome": happened, "exit_code": code,
            "resolved_by": "auto", "brier": brier, "score_basis": "first",
        }));
    } else {
        let truth = if happened { "TRUE" } else { "FALSE" };
        println!(
            "[{cid}] resolved {truth}.  you said {}  →  Brier {:.3} on this one",
            pct(prob),
            brier
        );
        println!(
            "  graded from `{}` exiting {code}, the command you pinned before the outcome. Grading is not up to you; choosing that command was.",
            line(&cmdline, MAX_LINE)
        );
    }
    Ok(exit)
}

/// The user's home directory.
///
/// `std::env::home_dir` reads `$HOME` on Unix and `USERPROFILE` (falling back to
/// `GetUserProfileDirectory`) on Windows. It was fixed for Windows in Rust 1.85
/// and un-deprecated in 1.87, so at our 1.89 MSRV this needs no crate.
///
/// Reading `$HOME` directly, as this used to, meant a normal Windows setup found
/// nothing and silently fell back to a ledger in the *current directory* — so
/// every folder quietly got its own separate record of the user's judgement, and
/// nothing ever said so.
fn home_dir() -> Option<PathBuf> {
    #[allow(deprecated)]
    std::env::home_dir().filter(|p| !p.as_os_str().is_empty())
}

/// Where the human ledger lives: `--data`, else `$ANAMNESIS_DATA`, else
/// `~/.anamnesis.json`. An error rather than a cwd fallback when there is no home
/// directory — a wrong ledger path is worse than a refusal.
fn data_path(cli: &Cli) -> Result<PathBuf, String> {
    if let Some(p) = &cli.data {
        return Ok(p.clone());
    }
    if let Ok(p) = std::env::var("ANAMNESIS_DATA") {
        if !p.is_empty() {
            return Ok(PathBuf::from(p));
        }
    }
    match home_dir() {
        Some(h) => Ok(h.join(".anamnesis.json")),
        None => Err(
            "no home directory found, so there is nowhere to keep your ledger.\n  \
             Pass --data <FILE>, or set ANAMNESIS_DATA, to say where it should live."
                .into(),
        ),
    }
}

/// The global agent ledger driven by `ana mcp` and the Claude Code plugin — the
/// cross-project calibration spine. `ANAMNESIS_AGENT_DATA` overrides it.
fn agent_ledger_path() -> Result<PathBuf, String> {
    if let Ok(p) = std::env::var("ANAMNESIS_AGENT_DATA") {
        if !p.is_empty() {
            return Ok(PathBuf::from(p));
        }
    }
    match home_dir() {
        Some(h) => Ok(h.join(".anamnesis").join("agent.json")),
        None => Err(
            "no home directory found, so there is nowhere to keep the agent ledger.\n  \
             Pass --data <FILE>, or set ANAMNESIS_AGENT_DATA, to say where it should live."
                .into(),
        ),
    }
}

/// A corrupt ledger is a data-loss emergency, not a parse error: say exactly
/// where the JSON went wrong and where the last good copy is, and never write
/// over the file.
fn load_error(path: &std::path::Path, e: std::io::Error) -> String {
    let mut msg = format!("reading {}: {e}", path.display());
    if e.kind() == std::io::ErrorKind::InvalidData {
        let bak = store::backup_path(path);
        msg.push_str("\n  the ledger was NOT modified.");
        if bak.exists() {
            msg.push_str(&format!(
                "\n  last good copy: {} (inspect it before overwriting anything)",
                bak.display()
            ));
        }
    }
    msg
}

/// `ana where` — the first thing to ask a bug reporter for.
///
/// Deliberately runs before any ledger is loaded, so it still answers when the
/// ledger is the thing that is broken.
fn cmd_where(cli: &Cli) -> Result<(), String> {
    let human = data_path(cli);
    let agent = agent_ledger_path();
    let env = |k: &str| std::env::var(k).ok().filter(|v| !v.is_empty());

    if cli.json {
        let describe = |p: &Result<PathBuf, String>| match p {
            Ok(p) => json!({
                "path": p.display().to_string(),
                "exists": p.exists(),
                "lock": store::lock_path(p).display().to_string(),
                "backup": store::backup_path(p).display().to_string(),
            }),
            Err(e) => json!({ "error": e }),
        };
        out_json(json!({
            "version": env!("CARGO_PKG_VERSION"),
            "human_ledger": describe(&human),
            "agent_ledger": describe(&agent),
            "home": home_dir().map(|h| h.display().to_string()),
            "env": {
                "ANAMNESIS_DATA": env("ANAMNESIS_DATA"),
                "ANAMNESIS_AGENT_DATA": env("ANAMNESIS_AGENT_DATA"),
            },
            "data_flag": cli.data.as_ref().map(|p| p.display().to_string()),
            "hooks": anamnesis::hook::hook_stats().iter().map(|h| json!({
                "event": h.event, "last": h.last, "fires": h.fires, "model_bytes": h.model_bytes,
            })).collect::<Vec<_>>(),
        }));
        return Ok(());
    }

    println!("ana {}", env!("CARGO_PKG_VERSION"));
    println!(
        "home                 {}",
        home_dir().map_or("(none found)".into(), |h| h.display().to_string())
    );
    for (label, p, var) in [
        ("human ledger", &human, "ANAMNESIS_DATA"),
        ("agent ledger", &agent, "ANAMNESIS_AGENT_DATA"),
    ] {
        match p {
            Ok(p) => {
                println!(
                    "\n{label}         {}  {}",
                    p.display(),
                    if p.exists() {
                        "(exists)"
                    } else {
                        "(not created yet)"
                    }
                );
                println!("  lock               {}", store::lock_path(p).display());
                println!("  backup             {}", store::backup_path(p).display());
            }
            Err(e) => println!("\n{label}         ERROR: {e}"),
        }
        match env(var) {
            Some(v) => println!("  overridden by      {var}={v}"),
            None => println!("  {var} is unset"),
        }
    }
    if let Some(p) = &cli.data {
        println!("\n--data {} overrides both of the above.", p.display());
    }
    // Liveness and cost: whether each hook has run here, and how much of what it printed
    // reached the model. A hook that never fired is the failure that is otherwise silent.
    println!("\nhooks on this machine     last ran (UTC)          runs   to the model");
    for h in anamnesis::hook::hook_stats() {
        let per = if h.fires > 0 {
            format!(
                "{} bytes in all, about {} tokens a run",
                h.model_bytes,
                (h.model_bytes as f64 / h.fires as f64 / 4.0).round()
            )
        } else {
            "-".into()
        };
        println!(
            "  {:<22}  {:<22}  {:>5}   {per}",
            h.event,
            h.last.as_deref().unwrap_or("never"),
            h.fires
        );
    }
    println!("  (counted since this engine was installed; tokens are bytes / 4, a rough guide)");
    Ok(())
}

/// `ana demo` — a result before we ask for a habit.
///
/// A new user's first report is empty, and a visitor decides in about two
/// minutes. This builds a fictional year of predictions in a temporary
/// directory, reports on it, and deletes it — the real ledger is never opened,
/// never mind written.
fn cmd_demo(cli: &Cli, keep: Option<&std::path::Path>, plain: bool) -> Result<(), String> {
    let ledger = anamnesis::demo::ledger();
    let today = Utc::now().date_naive();

    if cli.json {
        println!("{}", report::render_json(&ledger, None, 10, today));
    } else if plain {
        print!("{}", report::render_plain(&ledger, None, 10, today));
    } else {
        print!("{}", report::render(&ledger, None, 10, today));
    }

    match keep {
        Some(path) => {
            store::save(path, &ledger).map_err(|e| format!("writing {}: {e}", path.display()))?;
            if !cli.json {
                println!("\nDemo ledger written to {}", path.display());
                println!("Poke at it:  ana --data {} list", path.display());
            }
        }
        None if !cli.json => {
            println!("\nThis was a fictional ledger — nothing of yours was touched.");
            println!("Your own first prediction:");
            println!("  ana add \"this refactor takes under an hour\" --prob 0.7 --by {today}");
            println!("  ana resolve <id> yes|no      # the moment reality answers");
            println!("  ana report");
            println!("\nKeep a copy to explore:  ana demo --keep demo.json");
        }
        None => {}
    }
    Ok(())
}

/// `ana export --anonymize` — publish the shape of a record without its content.
///
/// Keeps every number: probabilities, intervals, outcomes, kinds, stakes, and
/// dates rounded to the day. Drops every free-text field — statements, reasoning,
/// resolution notes, void reasons and amendments — and keeps only whitelisted tag
/// namespaces. Ids are replaced with sequential ones, so nothing can be joined
/// back to the original ledger.
///
/// `--anonymize` is required rather than default-on, because an export that can
/// be run without it is an export somebody will run without it.
fn cmd_export(
    ledger: &anamnesis::model::Ledger,
    anonymize: bool,
    out: Option<&std::path::Path>,
    keep_tags: Option<&str>,
) -> Result<(), String> {
    if !anonymize {
        return Err(
            "refusing to export raw statements. Pass --anonymize; there is no other mode.".into(),
        );
    }
    let allowed: Vec<String> = keep_tags
        .map(|s| {
            s.split(',')
                .map(|t| t.trim().to_lowercase())
                .filter(|t| !t.is_empty())
                .collect()
        })
        .unwrap_or_else(|| {
            ["kind", "who", "model", "project"]
                .iter()
                .map(|s| s.to_string())
                .collect()
        });

    let claims: Vec<Value> = ledger
        .claims
        .iter()
        .enumerate()
        .map(|(i, c)| {
            let tags: Vec<&String> = c
                .tags
                .iter()
                .filter(|t| {
                    t.split_once(':')
                        .is_some_and(|(ns, _)| allowed.iter().any(|a| a == ns))
                })
                .collect();
            let forecasts: Vec<Value> = c
                .forecasts
                .iter()
                .map(|f| {
                    json!({
                        "at": f.at.date_naive().to_string(),
                        "prob": f.prob,
                        "interval": f.interval,
                    })
                })
                .collect();
            json!({
                "id": format!("c{i:05}"),
                "created_at": c.created_at.date_naive().to_string(),
                "resolve_by": c.resolve_by.map(|d| d.to_string()),
                "kind": c.kind,
                "stake": c.stake,
                "tags": tags,
                "forecasts": forecasts,
                "resolution": c.resolution.as_ref().map(|r| json!({
                    "at": r.at.date_naive().to_string(),
                    "outcome": r.outcome,
                    "value": r.value,
                    "resolved_by": r.resolved_by,
                })),
                "void": c.void.is_some(),
                "amendments": c.amendments.len(),
            })
        })
        .collect();

    let doc = json!({
        "anonymized": true,
        "note": "Statements, reasoning, notes and ids are removed; dates are rounded to the day. Numbers are unchanged.",
        "claims": claims,
    });
    let text = serde_json::to_string_pretty(&doc).map_err(|e| e.to_string())?;
    match out {
        Some(p) => {
            std::fs::write(p, &text).map_err(|e| format!("writing {}: {e}", p.display()))?;
            eprintln!(
                "wrote {} anonymized claim(s) to {}",
                ledger.claims.len(),
                p.display()
            );
        }
        None => println!("{text}"),
    }
    Ok(())
}

/// `ana import <file.csv>` — bring an existing prediction history in, so the
/// first report has something to say.
///
/// Columns, by header name: `statement, prob, created, resolve_by, outcome,
/// resolved_at, tags`. Only `statement` and `prob` are required. Unknown columns
/// are ignored; a row that cannot be parsed is reported by line number and
/// skipped rather than silently dropped.
fn cmd_import(
    cli: &Cli,
    path: &std::path::Path,
    ledger: &mut anamnesis::model::Ledger,
    file: &std::path::Path,
    dry_run: bool,
) -> Result<(), String> {
    let text =
        std::fs::read_to_string(file).map_err(|e| format!("reading {}: {e}", file.display()))?;
    let mut rows = text
        .lines()
        .enumerate()
        .filter(|(_, l)| !l.trim().is_empty());
    let (_, header) = rows.next().ok_or("the file is empty")?;
    let cols: Vec<String> = split_csv(header)
        .into_iter()
        .map(|c| c.trim().to_lowercase())
        .collect();
    let col = |name: &str| cols.iter().position(|c| c == name);
    let (Some(i_stmt), Some(i_prob)) = (col("statement"), col("prob")) else {
        return Err(format!(
            "the header must name at least `statement` and `prob`; found: {}",
            cols.join(", ")
        ));
    };
    let (i_created, i_by, i_outcome, i_resolved, i_tags) = (
        col("created"),
        col("resolve_by"),
        col("outcome"),
        col("resolved_at"),
        col("tags"),
    );

    let now = Utc::now();
    let mut added = 0usize;
    let mut skipped: Vec<String> = Vec::new();
    let mut salt = now.timestamp_nanos_opt().unwrap_or(0) as u64;

    for (n, line) in rows {
        let f = split_csv(line);
        let get = |i: Option<usize>| {
            i.and_then(|i| f.get(i))
                .map(|s| s.trim())
                .filter(|s| !s.is_empty())
        };
        let lineno = n + 1;

        let Some(statement) = f.get(i_stmt).map(|s| s.trim()).filter(|s| !s.is_empty()) else {
            skipped.push(format!("line {lineno}: empty statement"));
            continue;
        };
        let prob: f64 = match f.get(i_prob).map(|s| s.trim()).unwrap_or("").parse() {
            Ok(p) => p,
            Err(_) => {
                skipped.push(format!("line {lineno}: unreadable prob"));
                continue;
            }
        };
        if !(0.0..=1.0).contains(&prob) {
            skipped.push(format!("line {lineno}: prob {prob} is not between 0 and 1"));
            continue;
        }
        let created = match get(i_created) {
            Some(d) => match parse_date(d) {
                Ok(d) => d
                    .and_hms_opt(12, 0, 0)
                    .map(|dt| dt.and_utc())
                    .unwrap_or(now),
                Err(e) => {
                    skipped.push(format!("line {lineno}: {e}"));
                    continue;
                }
            },
            None => now,
        };
        let resolve_by = match get(i_by) {
            Some(d) => match parse_date(d) {
                Ok(d) => Some(d),
                Err(e) => {
                    skipped.push(format!("line {lineno}: {e}"));
                    continue;
                }
            },
            None => None,
        };
        let outcome = match get(i_outcome).map(|o| o.to_lowercase()) {
            None => None,
            Some(o) => match o.as_str() {
                "yes" | "true" | "1" | "y" => Some(Outcome::True),
                "no" | "false" | "0" | "n" => Some(Outcome::False),
                other => {
                    skipped.push(format!("line {lineno}: unreadable outcome '{other}'"));
                    continue;
                }
            },
        };
        let resolved_at = get(i_resolved)
            .and_then(|d| parse_date(d).ok())
            .and_then(|d| d.and_hms_opt(12, 0, 0))
            .map(|dt| dt.and_utc());
        let tags = get(i_tags)
            .map(|t| {
                normalize_tags(
                    &t.split([',', ';', ' '])
                        .map(|s| s.trim().to_string())
                        .filter(|s| !s.is_empty())
                        .collect::<Vec<_>>(),
                )
            })
            .unwrap_or_default();

        salt = salt.wrapping_add(1);
        let mut id = gen_id(statement, salt);
        while ledger.has_id(&id) {
            salt = salt.wrapping_add(1);
            id = gen_id(statement, salt);
        }
        ledger.claims.push(Claim {
            id,
            statement: statement.to_string(),
            created_at: created,
            resolve_by,
            horizon_days: Some(anamnesis::evidence::horizon_for(&tags)),
            tags,
            kind: ClaimKind::Binary,
            stake: 1.0,
            forecasts: vec![Forecast {
                at: created,
                prob: Some(prob),
                interval: None,
                because: None,
            }],
            resolution: outcome.map(|o| Resolution {
                // A resolution with no date falls on the deadline if there is
                // one, so imported claims land in the evidence sequence in a
                // sensible place rather than all at "now".
                at: resolved_at
                    .or_else(|| {
                        resolve_by
                            .and_then(|d| d.and_hms_opt(12, 0, 0))
                            .map(|d| d.and_utc())
                    })
                    .unwrap_or(now),
                outcome: Some(o),
                value: None,
                note: None,
                resolved_by: None,
            }),
            void: None,
            check: None,
            extra: Default::default(),
            amendments: Vec::new(),
        });
        added += 1;
    }

    if !dry_run {
        store::save(path, ledger).map_err(|e| format!("saving: {e}"))?;
    }

    if cli.json {
        out_json(json!({
            "imported": added,
            "skipped": skipped.len(),
            "problems": skipped,
            "dry_run": dry_run,
            "ledger": path.display().to_string(),
        }));
    } else {
        let verb = if dry_run { "would import" } else { "imported" };
        println!("{verb} {added} claim(s) from {}", file.display());
        if !skipped.is_empty() {
            println!("skipped {}:", skipped.len());
            for s in skipped.iter().take(10) {
                println!("  {s}");
            }
            if skipped.len() > 10 {
                println!("  … and {} more", skipped.len() - 10);
            }
        }
        if dry_run {
            println!("(--dry-run: nothing was written)");
        } else {
            println!("Now run:  ana report");
        }
    }
    Ok(())
}

/// Split one CSV line, honouring double-quoted fields and `""` escapes. Enough
/// for the documented column set; this is an importer, not a CSV library, and a
/// dependency for one function would not earn its place.
fn split_csv(line: &str) -> Vec<String> {
    let mut out = Vec::new();
    let mut cur = String::new();
    let mut in_quotes = false;
    let mut chars = line.chars().peekable();
    while let Some(c) = chars.next() {
        match c {
            '"' if in_quotes && chars.peek() == Some(&'"') => {
                cur.push('"');
                chars.next();
            }
            '"' => in_quotes = !in_quotes,
            ',' if !in_quotes => out.push(std::mem::take(&mut cur)),
            _ => cur.push(c),
        }
    }
    out.push(cur);
    out
}

/// A probability as people write one: `0.7`, `.7` or `70%`.
///
/// A bare `70` is refused with the fix, not read as 70%: it is as likely to be a slip for
/// `0.70` as for `0.07`, and guessing would put a wrong number in a record that cannot be
/// edited. A negative number reaches here too (`allow_negative_numbers`), so it gets this
/// message instead of clap's "unexpected argument '-0'".
fn prob_arg(s: &str) -> Result<f64, String> {
    let t = s.trim();
    let (num, percent) = match t.strip_suffix('%') {
        Some(n) => (n.trim(), true),
        None => (t, false),
    };
    let v: f64 = num
        .parse()
        .map_err(|_| format!("'{s}' is not a probability; write it as 0.7 or 70%"))?;
    if !percent && v > 1.0 && v <= 100.0 {
        return Err(format!(
            "probability must be between 0 and 1, got {v}; for {v} percent write {v}% or {}",
            v / 100.0
        ));
    }
    let p = if percent { v / 100.0 } else { v };
    if !p.is_finite() || !(0.0..=1.0).contains(&p) {
        return Err(format!("probability must be between 0 and 1, got {s}"));
    }
    Ok(p)
}

/// Words for a deadline that is already behind us. A claim logged with one is due the
/// moment it is written, its answer often already known, and it is not a prediction.
///
/// `today` is the UTC date, and a person west of Greenwich can be a day behind it: at 8pm
/// in California it is already tomorrow in UTC, and the local date they type, which the
/// standing rule tells an agent to type, must not be refused. So one day of slack.
fn check_deadline(by: NaiveDate, today: NaiveDate) -> Result<(), String> {
    if by < today - chrono::Duration::days(1) {
        return Err(format!(
            "--by {by} is in the past: a claim must be logged before its answer can be known. Use today ({today}) or later; to record past forecasts, use `ana import`."
        ));
    }
    Ok(())
}

fn check_prob(p: f64) -> Result<(), String> {
    if (0.0..=1.0).contains(&p) {
        Ok(())
    } else {
        Err(format!("probability must be between 0 and 1, got {p}"))
    }
}

fn check_level(l: f64) -> Result<(), String> {
    if l > 0.0 && l < 1.0 {
        Ok(())
    } else {
        Err(format!("level must be strictly between 0 and 1, got {l}"))
    }
}

fn parse_interval(s: &str) -> Result<(f64, f64), String> {
    let (lo, hi) = s
        .split_once("..")
        .ok_or_else(|| format!("interval must look like LOW..HIGH, got '{s}'"))?;
    let lo: f64 = lo
        .trim()
        .parse()
        .map_err(|_| format!("bad interval low '{lo}'"))?;
    let hi: f64 = hi
        .trim()
        .parse()
        .map_err(|_| format!("bad interval high '{hi}'"))?;
    if !lo.is_finite() || !hi.is_finite() {
        return Err("interval bounds must be finite".into());
    }
    if lo > hi {
        return Err(format!("interval low must be ≤ high ({lo} > {hi})"));
    }
    Ok((lo, hi))
}

/// `ana trial start|status`. Neither prints the schedule or today's arm: an agent may be
/// the one running it, and the model is never told which week is which.
fn cmd_trial(
    cli: &Cli,
    ledger_path: &std::path::Path,
    action: TrialAction,
    from: Option<NaiveDate>,
    pairs: u32,
) -> Result<(), String> {
    use anamnesis::trial;
    let today = Utc::now().date_naive();
    let t = match action {
        TrialAction::Start => trial::start(ledger_path, from, pairs, today)?,
        TrialAction::Status => match trial::load(ledger_path) {
            Some(t) => t,
            None => {
                if cli.json {
                    println!("{}", json!({ "enrolled": false }));
                } else {
                    println!(
                        "no trial enrolled ({} does not exist or cannot be read). `ana trial start` enrols one.",
                        trial::path(ledger_path).display()
                    );
                }
                return Ok(());
            }
        },
    };
    let week = t.week_of(today);
    if cli.json {
        println!(
            "{}",
            json!({
                "enrolled": true, "id": t.id, "start": t.start, "end": t.end(),
                "pairs": t.on_first.len(), "week": week, "file": trial::path(ledger_path),
            })
        );
        return Ok(());
    }
    let verb = if matches!(action, TrialAction::Start) {
        "enrolled"
    } else {
        "trial"
    };
    println!(
        "{verb} [{}]: {} pairs of weeks, Monday {} to Sunday {} (UTC dates)",
        t.id,
        t.on_first.len(),
        t.start,
        t.end() - chrono::Duration::days(1)
    );
    match week {
        Some(w) => println!("  today is in week {w} of {}", 2 * t.on_first.len()),
        None if today < t.start => println!("  it has not started"),
        None => println!("  it has ended: python3 validation/crossover_report.py reads it"),
    }
    println!(
        "  the schedule is in {} and is not printed, so a model running this never reads it",
        trial::path(ledger_path).display()
    );
    Ok(())
}

fn parse_date(s: &str) -> Result<NaiveDate, String> {
    NaiveDate::parse_from_str(s, "%Y-%m-%d")
        .map_err(|_| format!("could not parse date '{s}' (expected YYYY-MM-DD)"))
}

fn pct(p: f64) -> String {
    format!("{:.0}%", p * 100.0)
}

fn out_json(v: Value) {
    println!("{}", serde_json::to_string_pretty(&v).unwrap());
}

fn run(cli: Cli) -> Result<(), String> {
    // Dispatched before any ledger load: `ana mcp` serves the AGENT ledger, so a
    // corrupt or unreadable human ledger must not be able to break it.
    if matches!(cli.cmd, Cmd::Mcp) {
        let ledger_path = match cli.data.clone() {
            Some(p) => p,
            None => agent_ledger_path()?,
        };
        return mcp::serve(ledger_path).map_err(|e| format!("mcp: {e}"));
    }

    if matches!(cli.cmd, Cmd::Where) {
        return cmd_where(&cli);
    }
    // Hooks read the AGENT ledger, like `mcp`, and must not be broken by a
    // corrupt human one.
    if let Cmd::Hook { event } = &cli.cmd {
        let ledger_path = match cli.data.clone() {
            Some(p) => p,
            None => agent_ledger_path()?,
        };
        return anamnesis::hook::run((*event).into(), &ledger_path);
    }
    // The trial lives beside the AGENT ledger, which the hooks read.
    if let Cmd::Trial {
        action,
        from,
        pairs,
    } = &cli.cmd
    {
        let ledger_path = match cli.data.clone() {
            Some(p) => p,
            None => agent_ledger_path()?,
        };
        return cmd_trial(&cli, &ledger_path, *action, *from, *pairs);
    }
    // `demo` must never be able to touch a real ledger, so it is dispatched
    // before one is even resolved.
    if let Cmd::Demo { keep, plain } = &cli.cmd {
        return cmd_demo(&cli, keep.as_deref(), *plain);
    }

    let path = data_path(&cli)?;

    // Lock BEFORE loading, and hold it for the whole function, so concurrent
    // writers serialise instead of each overwriting the other's claim.
    let _guard = if cli.cmd.mutates() {
        Some(store::lock(&path).map_err(|e| format!("locking {}: {e}", path.display()))?)
    } else {
        None
    };

    let mut ledger = store::load(&path).map_err(|e| load_error(&path, e))?;

    match &cli.cmd {
        Cmd::Run { .. } => unreachable!("`ana run` is dispatched in main"),
        Cmd::Add {
            statement,
            prob,
            interval,
            level,
            by,
            tags,
            because,
            stake,
            second_prob,
            reference_class,
            check,
        } => {
            let statement = statement.trim().to_string();
            let check = check.as_deref().map(anamnesis::check::pin).transpose()?;
            if statement.is_empty() {
                return Err("statement must not be empty".into());
            }
            let stake = *stake;
            if !(stake.is_finite() && stake >= 0.0) {
                return Err(format!("stake must be a finite number ≥ 0, got {stake}"));
            }
            let resolve_by = by.as_deref().map(parse_date).transpose()?;
            let now = Utc::now();
            if let Some(d) = resolve_by {
                check_deadline(d, now.date_naive())?;
            }
            if let Some(p) = prob.filter(|p| *p == 0.0 || *p == 1.0) {
                eprintln!(
                    "note: {} is certainty. If it turns out wrong, its log score is the worst there is (clamped to 13.8); say 0.99 or 0.01 if any doubt is left.",
                    pct(p)
                );
            }

            let (kind, forecast) = match (prob, interval) {
                (Some(_), Some(_)) => {
                    return Err(
                        "give either --prob (binary) or --interval (numeric), not both".into(),
                    )
                }
                (Some(p), None) => {
                    check_prob(*p)?;
                    // Dialectical bootstrapping: if a second "consider the opposite"
                    // estimate is given, log the average of the two.
                    let (p_eff, estimates) = match second_prob {
                        Some(sp) => {
                            check_prob(*sp)?;
                            (scoring::dialectical_mean(*p, *sp), Some((*p, *sp)))
                        }
                        None => (*p, None),
                    };
                    (
                        ClaimKind::Binary,
                        Forecast {
                            at: now,
                            prob: Some(p_eff),
                            interval: None,
                            because: compose_reasoning(
                                because.as_deref(),
                                reference_class.as_deref(),
                                estimates,
                            ),
                        },
                    )
                }
                (None, Some(iv)) => {
                    check_level(*level)?;
                    let (low, high) = parse_interval(iv)?;
                    (
                        ClaimKind::Numeric,
                        Forecast {
                            at: now,
                            prob: None,
                            interval: Some(NumericForecast {
                                low,
                                high,
                                level: *level,
                            }),
                            because: compose_reasoning(
                                because.as_deref(),
                                reference_class.as_deref(),
                                None,
                            ),
                        },
                    )
                }
                (None, None) => {
                    return Err("give --prob 0.7 (binary) or --interval 120..180 (numeric)".into())
                }
            };

            let mut salt = now.timestamp_nanos_opt().unwrap_or(0) as u64;
            let id = loop {
                let candidate = gen_id(&statement, salt);
                if !ledger.has_id(&candidate) {
                    break candidate;
                }
                salt = salt.wrapping_add(1);
            };

            let disp_prob = forecast.prob;
            let disp_iv = forecast.interval;
            ledger.claims.push(Claim {
                id: id.clone(),
                statement: statement.clone(),
                created_at: now,
                resolve_by,
                horizon_days: Some(anamnesis::evidence::horizon_for(&normalize_tags(tags))),
                tags: normalize_tags(tags),
                kind,
                stake,
                forecasts: vec![forecast],
                resolution: None,
                void: None,
                check: check.clone(),
                extra: anamnesis::pin::origin_here(),
                amendments: Vec::new(),
            });
            store::save(&path, &ledger).map_err(|e| format!("saving: {e}"))?;

            if let (Some(check), false) = (&check, cli.json) {
                println!("  pinned to `{check}`: settle it with `ana run {id} -- {check}`");
            }
            if cli.json {
                out_json(
                    json!({"id": id, "kind": kind, "prob": disp_prob, "interval": disp_iv, "statement": statement}),
                );
            } else {
                match kind {
                    ClaimKind::Binary => {
                        println!(
                            "added [{id}]  {}  \"{}\"",
                            pct(disp_prob.unwrap()),
                            printable(&statement)
                        )
                    }
                    ClaimKind::Numeric => {
                        let iv = disp_iv.unwrap();
                        println!(
                            "added [{id}]  {:.0}% interval [{}, {}]  \"{}\"",
                            iv.level * 100.0,
                            iv.low,
                            iv.high,
                            printable(&statement)
                        )
                    }
                }
            }
        }

        Cmd::Update {
            id,
            prob,
            interval,
            level,
            because,
        } => {
            let idx = ledger.index_of(id)?;
            if ledger.claims[idx].is_resolved() {
                return Err(format!(
                    "[{}] is already resolved; its history is final",
                    ledger.claims[idx].id
                ));
            }
            let kind = ledger.claims[idx].kind;
            let now = Utc::now();

            let (forecast, human) = match kind {
                ClaimKind::Binary => {
                    let p = prob.ok_or("this is a binary claim; revise it with --prob 0..1")?;
                    if interval.is_some() {
                        return Err("this is a binary claim; use --prob, not --interval".into());
                    }
                    check_prob(p)?;
                    let old = ledger.claims[idx].current_prob().unwrap_or(p);
                    (
                        Forecast {
                            at: now,
                            prob: Some(p),
                            interval: None,
                            because: because.clone(),
                        },
                        format!("{} → {}", pct(old), pct(p)),
                    )
                }
                ClaimKind::Numeric => {
                    let iv = interval
                        .as_deref()
                        .ok_or("this is a numeric claim; revise it with --interval LOW..HIGH")?;
                    if prob.is_some() {
                        return Err("this is a numeric claim; use --interval, not --prob".into());
                    }
                    let (low, high) = parse_interval(iv)?;
                    let lvl = level
                        .or_else(|| ledger.claims[idx].current_interval().map(|i| i.level))
                        .unwrap_or(0.80);
                    check_level(lvl)?;
                    (
                        Forecast {
                            at: now,
                            prob: None,
                            interval: Some(NumericForecast {
                                low,
                                high,
                                level: lvl,
                            }),
                            because: because.clone(),
                        },
                        format!("[{low}, {high}] @ {:.0}%", lvl * 100.0),
                    )
                }
            };

            ledger.claims[idx].forecasts.push(forecast);
            let cid = ledger.claims[idx].id.clone();
            let rev = ledger.claims[idx].forecasts.len();
            store::save(&path, &ledger).map_err(|e| format!("saving: {e}"))?;

            if cli.json {
                out_json(json!({"id": cid, "kind": kind, "revision": rev}));
            } else {
                println!("[{cid}]  {human}  (revision #{rev})");
            }
        }

        Cmd::Resolve {
            id,
            outcome,
            value,
            note,
        } => {
            let idx = ledger.index_of(id)?;
            if ledger.claims[idx].is_resolved() {
                return Err(format!("[{}] is already resolved", ledger.claims[idx].id));
            }
            if let Some(check) = &ledger.claims[idx].check {
                return Err(anamnesis::check::pinned_message(
                    &ledger.claims[idx].id,
                    check,
                ));
            }
            let kind = ledger.claims[idx].kind;
            let now = Utc::now();
            let cid = ledger.claims[idx].id.clone();

            match kind {
                ClaimKind::Binary => {
                    if value.is_some() {
                        return Err(
                            "this is a binary claim; resolve it with yes/no, not --value".into(),
                        );
                    }
                    let o: Outcome = (*outcome
                        .as_ref()
                        .ok_or("resolve a binary claim with yes or no")?)
                    .into();
                    // The FIRST forecast is what gets graded (invariant #6): the
                    // belief recorded before the answer was known. Reporting the
                    // last one here told a reviser their score was the one they
                    // arrived at after the evidence came in.
                    let prob = ledger.claims[idx].first_prob().unwrap_or(0.5);
                    let final_prob = ledger.claims[idx].current_prob();
                    let revisions = ledger.claims[idx].forecasts.len();
                    ledger.claims[idx].resolution = Some(Resolution {
                        at: now,
                        outcome: Some(o),
                        value: None,
                        note: note.clone(),
                        resolved_by: None,
                    });
                    store::save(&path, &ledger).map_err(|e| format!("saving: {e}"))?;
                    let truth_f = if o.happened() { 1.0 } else { 0.0 };
                    let brier = (prob - truth_f).powi(2);
                    let final_brier = final_prob.map(|fp| (fp - truth_f).powi(2));
                    if cli.json {
                        out_json(json!({
                            "id": cid,
                            "kind": kind,
                            "outcome": o.happened(),
                            "prob": prob,
                            "brier": brier,
                            "score_basis": "first",
                            "final_prob": final_prob,
                            "final_brier": final_brier,
                        }));
                    } else {
                        let truth = if o.happened() { "TRUE" } else { "FALSE" };
                        println!(
                            "[{cid}] resolved {truth}.  you said {}  →  Brier {:.3} on this one",
                            pct(prob),
                            brier
                        );
                        if revisions > 1 {
                            if let (Some(fp), Some(fb)) = (final_prob, final_brier) {
                                println!(
                                    "  graded on your FIRST forecast; you later revised to {} ({:.3} — shown, not graded)",
                                    pct(fp),
                                    fb
                                );
                            }
                        }
                    }
                }
                ClaimKind::Numeric => {
                    if outcome.is_some() {
                        return Err("this is a numeric claim; resolve it with --value N".into());
                    }
                    let v = value.ok_or("resolve a numeric claim with --value N")?;
                    let iv = ledger.claims[idx]
                        .current_interval()
                        .ok_or("numeric claim has no interval forecast")?;
                    ledger.claims[idx].resolution = Some(Resolution {
                        at: now,
                        outcome: None,
                        value: Some(v),
                        note: note.clone(),
                        resolved_by: None,
                    });
                    store::save(&path, &ledger).map_err(|e| format!("saving: {e}"))?;
                    let ns = NumericSample {
                        low: iv.low,
                        high: iv.high,
                        level: iv.level,
                        value: v,
                    };
                    let w = scoring::winkler(&ns);
                    let caught = ns.contains();
                    if cli.json {
                        out_json(
                            json!({"id": cid, "kind": kind, "value": v, "interval": iv, "inside": caught, "winkler": w}),
                        );
                    } else {
                        let verdict = if caught { "caught it" } else { "MISSED" };
                        println!(
                            "[{cid}] resolved value {v}.  interval [{}, {}] {verdict}  →  Winkler {:.3}",
                            iv.low, iv.high, w
                        );
                    }
                }
            }
        }

        Cmd::Void { id, reason } => {
            let reason = reason.trim().to_string();
            if reason.is_empty() {
                return Err("a void needs a reason — it is the whole record of why".into());
            }
            let idx = ledger.index_of(id)?;
            let c = &mut ledger.claims[idx];
            if c.is_void() {
                return Err(format!("[{}] is already void", c.id));
            }
            // A resolved claim has had its answer seen. Voiding it then removes the
            // outcome from every score, and the ones people void are the misses.
            if c.is_resolved() {
                return Err(format!(
                    "[{}] is already resolved, and a resolved claim cannot be voided: that would remove an outcome after it was seen. A void is for a question that stopped making sense before you knew the answer.",
                    c.id
                ));
            }
            let cid = c.id.clone();
            c.void = Some(anamnesis::model::Void {
                at: Utc::now(),
                reason: reason.clone(),
            });
            store::save(&path, &ledger).map_err(|e| format!("saving: {e}"))?;
            if cli.json {
                out_json(json!({"id": cid, "void": true, "reason": reason}));
            } else {
                println!("[{cid}] voided — excluded from every score, kept in history.");
                println!("  reason: {reason}");
            }
        }

        Cmd::Amend {
            id,
            statement,
            tags,
        } => {
            if statement.is_none() && tags.is_none() {
                return Err("nothing to amend — pass --statement and/or --tags".into());
            }
            let idx = ledger.index_of(id)?;
            let c = &mut ledger.claims[idx];
            // Amending after the answer is known would let the record be rewritten
            // to match the outcome, which is the failure this whole tool exists to
            // prevent.
            if c.is_resolved() {
                return Err(format!(
                    "[{}] is already resolved — a resolved claim is the record, and the record does not change",
                    c.id
                ));
            }
            let cid = c.id.clone();
            let mut am = anamnesis::model::Amendment {
                at: Utc::now(),
                old_statement: None,
                new_statement: None,
                old_tags: None,
                new_tags: None,
            };
            if let Some(new) = statement {
                let new = new.trim().to_string();
                if new.is_empty() {
                    return Err("statement must not be empty".into());
                }
                am.old_statement = Some(c.statement.clone());
                am.new_statement = Some(new.clone());
                c.statement = new;
            }
            if let Some(new) = tags {
                let parsed: Vec<String> = new
                    .split(',')
                    .map(|t| t.trim().to_lowercase())
                    .filter(|t| !t.is_empty())
                    .collect();
                am.old_tags = Some(c.tags.clone());
                am.new_tags = Some(parsed.clone());
                c.tags = parsed;
            }
            c.amendments.push(am);
            let statement = ledger.claims[idx].statement.clone();
            let tags = ledger.claims[idx].tags.clone();
            store::save(&path, &ledger).map_err(|e| format!("saving: {e}"))?;
            if cli.json {
                out_json(json!({"id": cid, "statement": statement, "tags": tags}));
            } else {
                println!("[{cid}] amended — \"{}\"", printable(&statement));
                if !tags.is_empty() {
                    println!("  tags: {}", tags.join(", "));
                }
                println!("  the previous wording is kept in the claim's history.");
            }
        }

        Cmd::List {
            open,
            resolved,
            due,
            tag,
            void,
        } => {
            let today = Utc::now().date_naive();
            let tagf = tag.as_ref().map(|t| t.to_lowercase());
            let keep = |c: &Claim| {
                if let Some(t) = &tagf {
                    if !c.tags.iter().any(|x| x == t) {
                        return false;
                    }
                }
                // Voided claims are shown only when asked for: they are history,
                // not open work, and they are not part of any score.
                if *void {
                    return c.is_void();
                }
                if c.is_void() {
                    return false;
                }
                if *due {
                    c.is_due(today)
                } else if *open {
                    c.is_open()
                } else if *resolved {
                    c.is_resolved()
                } else {
                    true
                }
            };

            if cli.json {
                let arr: Vec<Value> = ledger
                    .claims
                    .iter()
                    .filter(|c| keep(c))
                    .map(|c| {
                        json!({
                            "id": c.id,
                            "kind": c.kind,
                            "statement": c.statement,
                            "prob": c.current_prob(),
                            "interval": c.current_interval(),
                            "tags": c.tags,
                            "resolve_by": c.resolve_by,
                            "resolved": c.is_resolved(),
                            "outcome": c.outcome().map(|o| o.happened()),
                            "value": c.value(),
                        })
                    })
                    .collect();
                out_json(json!(arr));
                return Ok(());
            }

            let mut shown = 0;
            for c in ledger.claims.iter().filter(|c| keep(c)) {
                shown += 1;
                let belief = match c.kind {
                    ClaimKind::Binary => c.current_prob().map(pct).unwrap_or_else(|| "  ?".into()),
                    ClaimKind::Numeric => c
                        .current_interval()
                        .map(|i| format!("[{},{}]", i.low, i.high))
                        .unwrap_or_else(|| "  ?".into()),
                };
                let status = match c.kind {
                    ClaimKind::Binary => match c.outcome() {
                        Some(Outcome::True) => "✓ true".to_string(),
                        Some(Outcome::False) => "✗ false".to_string(),
                        None => open_status(c, today),
                    },
                    ClaimKind::Numeric => match c.value() {
                        Some(v) => format!("= {v}"),
                        None => open_status(c, today),
                    },
                };
                let tags = if c.tags.is_empty() {
                    String::new()
                } else {
                    format!(" [{}]", printable(&c.tags.join(",")))
                };
                println!(
                    "{:<6}  {:>9}  {:<11}  {}{tags}",
                    c.id,
                    belief,
                    status,
                    truncate(&printable(&c.statement), 52)
                );
            }
            if shown == 0 {
                println!("(no matching claims)");
            }
        }

        Cmd::Show { id } => {
            let idx = ledger.index_of(id)?;
            let c = &ledger.claims[idx];
            if cli.json {
                out_json(serde_json::to_value(c).map_err(|e| e.to_string())?);
                return Ok(());
            }
            println!("[{}]  {}", c.id, printable(&c.statement));
            println!(
                "  kind: {}",
                match c.kind {
                    ClaimKind::Binary => "binary",
                    ClaimKind::Numeric => "numeric",
                }
            );
            println!("  created {}", c.created_at.date_naive());
            if let Some(d) = c.resolve_by {
                println!("  resolve by {d}");
            }
            if !c.tags.is_empty() {
                println!("  tags: {}", printable(&c.tags.join(", ")));
            }
            if let Some(check) = &c.check {
                let shown = anamnesis::untrusted::line(check, anamnesis::untrusted::MAX_LINE);
                println!(
                    "  check: `{shown}` — settle it with: ana run {} -- {shown}",
                    c.id
                );
            }
            if let Some(v) = &c.void {
                println!(
                    "  VOID since {} — excluded from every score",
                    v.at.date_naive()
                );
                println!("    reason: {}", printable(&v.reason));
            }
            for a in &c.amendments {
                if let (Some(o), Some(n)) = (&a.old_statement, &a.new_statement) {
                    println!(
                        "  amended {}: \"{}\" → \"{}\"",
                        a.at.date_naive(),
                        printable(o),
                        printable(n)
                    );
                }
                if let (Some(o), Some(n)) = (&a.old_tags, &a.new_tags) {
                    println!(
                        "  amended {}: tags [{}] → [{}]",
                        a.at.date_naive(),
                        printable(&o.join(", ")),
                        printable(&n.join(", "))
                    );
                }
            }
            println!("  forecasts:");
            for (i, f) in c.forecasts.iter().enumerate() {
                let marker = if i + 1 == c.forecasts.len() {
                    "→"
                } else {
                    " "
                };
                let belief = match (f.prob, f.interval) {
                    (Some(p), _) => pct(p),
                    (_, Some(iv)) => {
                        format!("[{}, {}] @ {:.0}%", iv.low, iv.high, iv.level * 100.0)
                    }
                    _ => "?".into(),
                };
                println!("    {marker} {}  {}", f.at.date_naive(), belief);
                if let Some(b) = &f.because {
                    println!("        because: {}", printable(b));
                }
            }
            match &c.resolution {
                Some(r) => {
                    match c.kind {
                        ClaimKind::Binary => {
                            let truth = if c.outcome().map(|o| o.happened()).unwrap_or(false) {
                                "TRUE"
                            } else {
                                "FALSE"
                            };
                            let how = match r.resolved_by {
                                Some(anamnesis::model::ResolvedBy::Auto) => {
                                    "  (graded from the exit status of the command pinned when it was logged)"
                                }
                                Some(anamnesis::model::ResolvedBy::Human) => {
                                    "  (graded by a human)"
                                }
                                _ => "",
                            };
                            println!("  resolved {truth} on {}{how}", r.at.date_naive());
                            if let Some(s) = c.sample() {
                                println!(
                                    "    Brier on your FIRST forecast: {:.3}",
                                    (s.prob - s.outcome).powi(2)
                                );
                                if let Some(f) = c.sample_final() {
                                    if (f.prob - s.prob).abs() > 1e-9 {
                                        println!(
                                            "    (final forecast {:.2} would score {:.3} — shown, not graded)",
                                            f.prob,
                                            (f.prob - f.outcome).powi(2)
                                        );
                                    }
                                }
                            }
                        }
                        ClaimKind::Numeric => {
                            if let Some(ns) = c.numeric_sample() {
                                let verdict = if ns.contains() { "inside" } else { "OUTSIDE" };
                                println!(
                                    "  resolved value {} on {} ({verdict} the interval)",
                                    ns.value,
                                    r.at.date_naive()
                                );
                                println!(
                                    "    Winkler on final interval: {:.3}",
                                    scoring::winkler(&ns)
                                );
                            }
                        }
                    }
                    if let Some(n) = &r.note {
                        println!("    post-mortem: {}", printable(n));
                    }
                }
                None => println!("  (open — reality has not yet spoken)"),
            }
        }

        Cmd::Report {
            tag,
            bins,
            plain,
            html,
            badge,
        } => {
            let today = Utc::now().date_naive();
            let tag = tag.as_deref();
            if cli.json {
                println!("{}", report::render_json(&ledger, tag, *bins, today));
            } else if *html {
                print!("{}", report::render_html(&ledger, tag, *bins, today));
            } else if *badge {
                print!("{}", report::render_badge_svg(&ledger, tag, *bins, today));
            } else if *plain {
                print!("{}", report::render_plain(&ledger, tag, *bins, today));
            } else {
                print!("{}", report::render(&ledger, tag, *bins, today));
            }
        }

        Cmd::Decide {
            prob,
            stake,
            verify_cost,
            tag,
        } => {
            let p = *prob;
            if !(0.0..=1.0).contains(&p) {
                return Err(format!("prob must be between 0 and 1, got {p}"));
            }
            // Correct the number through the earned map (if any), then threshold by
            // the stakes — the same evidence gate as the report and the MCP tools.
            let (recal, earned, n, e) =
                report::earned_recalibration(&ledger, tag.as_deref(), Utc::now().date_naive());
            let map = if earned { recal } else { None };
            let d = scoring::decide(p, map, *stake, *verify_cost);
            let verb = match d.act {
                scoring::Act::Proceed => "PROCEED",
                scoring::Act::Verify => "VERIFY",
                scoring::Act::Abstain => "ABSTAIN",
            };
            if cli.json {
                println!(
                    "{}",
                    json!({
                        "act": verb.to_lowercase(),
                        "stated": p,
                        "adjusted": d.adjusted_p,
                        "proceed_threshold": d.proceed_threshold,
                        "margin": d.margin,
                        "stake": *stake,
                        "verify_cost": *verify_cost,
                        "used_recalibration": earned,
                        "map_kind": d.map_kind.as_str(),
                        "n": n,
                        "eprocess": e,
                    })
                );
            } else {
                let gloss = match d.act {
                    scoring::Act::Proceed => "confidence clears the bar for the stakes",
                    scoring::Act::Verify => "in the doubt zone — check before you commit: run it here if you can; if it lives off this machine, read the primary source",
                    scoring::Act::Abstain => {
                        "more likely to fail than succeed — replan or escalate"
                    }
                };
                let corr = if earned {
                    format!(
                        "  (corrected {:.0}%→{:.0}% from {n} resolved calls)",
                        p * 100.0,
                        d.adjusted_p * 100.0
                    )
                } else {
                    String::new()
                };
                println!("{verb}  —  {gloss}");
                println!(
                    "  need ≥{:.0}% to proceed at stake {:.1}; you have {:.0}%{corr}",
                    d.proceed_threshold * 100.0,
                    *stake,
                    d.adjusted_p * 100.0
                );
                // A collapsed map returns the same act for every stated p. Say so,
                // or it reads as the gate ignoring the input.
                if d.map_kind == scoring::MapKind::Constant {
                    println!(
                        "  note: your stated confidence hasn't tracked outcomes over {n} calls, so the number you gave was replaced with your base rate — every --prob returns this same answer until that changes."
                    );
                }
            }
        }

        Cmd::Import { file, dry_run } => cmd_import(&cli, &path, &mut ledger, file, *dry_run)?,

        Cmd::Export {
            anonymize,
            out,
            keep_tags,
        } => cmd_export(&ledger, *anonymize, out.as_deref(), keep_tags.as_deref())?,

        // All handled at the top of run(), before any ledger load.
        Cmd::Mcp | Cmd::Where | Cmd::Demo { .. } | Cmd::Hook { .. } | Cmd::Trial { .. } => {
            unreachable!("dispatched before the ledger load")
        }
    }
    Ok(())
}

fn open_status(c: &Claim, today: NaiveDate) -> String {
    match c.resolve_by {
        Some(d) if d <= today => format!("● due {d}"),
        Some(d) => format!("○ by {d}"),
        None => "○ open".to_string(),
    }
}

fn truncate(s: &str, max: usize) -> String {
    if s.chars().count() <= max {
        s.to_string()
    } else {
        let mut t: String = s.chars().take(max.saturating_sub(1)).collect();
        t.push('…');
        t
    }
}

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

    #[test]
    fn a_deadline_is_refused_only_when_it_is_past_everywhere() {
        let today = NaiveDate::from_ymd_opt(2026, 11, 8).unwrap();
        assert!(check_deadline(today, today).is_ok());
        // A local date west of UTC.
        assert!(check_deadline(NaiveDate::from_ymd_opt(2026, 11, 7).unwrap(), today).is_ok());
        let e = check_deadline(NaiveDate::from_ymd_opt(2026, 11, 6).unwrap(), today).unwrap_err();
        assert!(e.contains("is in the past"), "{e}");
    }

    #[test]
    fn probabilities_are_read_as_people_write_them() {
        for (s, want) in [
            ("0.7", 0.7),
            (".7", 0.7),
            ("70%", 0.7),
            ("0%", 0.0),
            ("100%", 1.0),
            ("1", 1.0),
        ] {
            assert!((prob_arg(s).unwrap() - want).abs() < 1e-12, "{s}");
        }
        assert!(prob_arg("70").unwrap_err().contains("write 70% or 0.7"));
        for bad in ["-0.2", "1.5", "150%", "nan", "inf", "seventy"] {
            assert!(prob_arg(bad).is_err(), "{bad} was accepted");
        }
    }
}