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
//! `ana hook <event>` — the Claude Code hooks, implemented in the binary.
//!
//! These used to be three shell scripts, each re-deriving the calibration
//! verdict from `--json` output with its own `jq` expression. That meant three
//! more copies of the logic P0-5 exists to centralise, a hard dependency on `jq`,
//! and — because every script ended `exit 0` on any problem — total silence when
//! something was misconfigured. A user whose hooks never fired had no way to find
//! out why.
//!
//! Everything here reads the hook's JSON on stdin and writes one
//! `hookSpecificOutput` object on stdout. Two fields matter, per the hooks
//! reference: `additionalContext` is injected into the model's context, and
//! `systemMessage` is shown to the user. Nothing here ever blocks a tool call.

use std::io::Read;

use chrono::{NaiveDate, Utc};
use serde_json::{json, Value};

use crate::model::{Claim, Ledger, Outcome, Resolution, ResolvedBy};
use crate::report::{ReportData, Verdict};
use crate::store;
use crate::untrusted;

/// Which hook is firing.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Event {
    SessionStart,
    UserPrompt,
    PostTool,
    /// Before a Bash call runs: the opt-in "pin first" reminder (see [`crate::pin`]).
    PreTool,
    /// A tool call that failed. Claude Code sends a command that exits non-zero here
    /// and never as `PostToolUse`, so without this event a failing test is invisible.
    PostToolFailure,
    Stop,
}

impl Event {
    /// The `hookEventName` the harness expects back.
    fn name(self) -> &'static str {
        match self {
            Event::SessionStart => "SessionStart",
            Event::UserPrompt => "UserPromptSubmit",
            Event::PostTool => "PostToolUse",
            Event::PreTool => "PreToolUse",
            Event::PostToolFailure => "PostToolUseFailure",
            Event::Stop => "Stop",
        }
    }
}

/// What `ana where` says about one hook event on this machine.
#[derive(Debug, Clone, PartialEq)]
pub struct HookStat {
    pub event: &'static str,
    /// When it last ran, as it recorded it (RFC 3339).
    pub last: Option<String>,
    pub fires: u64,
    /// Bytes of its output that reached the model, summed over every firing.
    pub model_bytes: u64,
}

const ALL_EVENTS: [Event; 6] = [
    Event::SessionStart,
    Event::UserPrompt,
    Event::PreTool,
    Event::PostTool,
    Event::PostToolFailure,
    Event::Stop,
];

fn stat_file(event: Event) -> Option<std::path::PathBuf> {
    dirs_counters().map(|d| d.join(format!("hook-{}.stat", event.name())))
}

fn read_stat(event: Event) -> HookStat {
    let text = stat_file(event)
        .and_then(|f| std::fs::read_to_string(f).ok())
        .unwrap_or_default();
    let mut it = text.split_whitespace();
    let fires = it.next().and_then(|x| x.parse().ok()).unwrap_or(0);
    let model_bytes = it.next().and_then(|x| x.parse().ok()).unwrap_or(0);
    HookStat {
        event: event.name(),
        last: it.next().map(str::to_string),
        fires,
        model_bytes,
    }
}

/// Count a firing (`fired`) or the bytes it sent the model. Read-modify-write without a
/// lock: two hooks of one event at the same instant can lose a count, which makes this a
/// liveness line and an approximate cost, never a measurement.
fn note(event: Event, model_bytes: usize, fired: bool) {
    let Some(file) = stat_file(event) else {
        return;
    };
    let mut st = read_stat(event);
    if fired {
        st.fires += 1;
        st.last = Some(Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true));
    }
    st.model_bytes += model_bytes as u64;
    if let Some(dir) = file.parent() {
        let _ = std::fs::create_dir_all(dir);
    }
    let tmp = file.with_extension("stat.tmp");
    let line = format!(
        "{} {} {}\n",
        st.fires,
        st.model_bytes,
        st.last.as_deref().unwrap_or("-")
    );
    if std::fs::write(&tmp, line).is_ok() {
        let _ = std::fs::rename(&tmp, &file);
    }
}

/// Every hook event's record on this machine, for `ana where`.
pub fn hook_stats() -> Vec<HookStat> {
    ALL_EVENTS.iter().map(|e| read_stat(*e)).collect()
}

/// The most of `protocol.md` that is passed on; past it the file is cut, and says so.
const PROTOCOL_MAX_BYTES: usize = 6000;

/// The owner's standing protocol for agents on this machine: `protocol.md` beside the agent
/// ledger, given at session start.
///
/// It lives here rather than in the agent's global instructions so the weekly trial's OFF
/// weeks can withhold it with everything else the tool says (MEASUREMENT.md, addendum 4).
/// It is the owner's configuration, like those instructions, not ledger text, so it is
/// passed as written, framed by where it came from. No file, no line: nothing changes for
/// anyone who has not written one.
fn owner_protocol(ledger_path: &std::path::Path) -> Option<String> {
    let file = ledger_path.with_file_name("protocol.md");
    let text = std::fs::read_to_string(&file).ok()?;
    let text = text.trim();
    if text.is_empty() {
        return None;
    }
    let mut cut = text.len().min(PROTOCOL_MAX_BYTES);
    while !text.is_char_boundary(cut) {
        cut -= 1;
    }
    let tail = if cut < text.len() {
        format!("\n(cut at {PROTOCOL_MAX_BYTES} bytes of {})", text.len())
    } else {
        String::new()
    };
    Some(format!(
        "⟢ Standing protocol on this machine, set by its owner ({}):\n{}{tail}",
        file.display(),
        &text[..cut]
    ))
}

/// Below this many graded calls, a calibration line is noise and is not shown.
const MIN_N: usize = 6;
/// Re-surface the standing calibration every Nth user prompt. A counter, not
/// willpower: nobody remembers to audit themselves unprompted.
const DEFAULT_EVERY: u64 = 7;
/// How long a hook waits for the ledger lock before giving up, in milliseconds.
/// Claude Code's own default for a command hook is 600 seconds (30 on UserPromptSubmit),
/// so a hook that waited forever would stall the session instead of failing.
const DEFAULT_LOCK_WAIT_MS: u64 = 2000;

/// The engine's own version, stamped on the first line of everything a hook
/// injects.
///
/// On the machine this was built on, the session hooks ran a 0.3.0 engine behind
/// June-era scripts for a whole release cycle, and greeted the agent in wording
/// the repo had already deleted. Nothing said so, because nothing in the output
/// named the binary that wrote it. A stale engine now announces itself.
const VERSION: &str = env!("CARGO_PKG_VERSION");

fn env_usize(key: &str, default: u64) -> u64 {
    std::env::var(key)
        .ok()
        .and_then(|v| v.parse().ok())
        .filter(|n| *n > 0)
        .unwrap_or(default)
}

/// One line naming the agent's standing calibration, or `None` when there is
/// nothing honest to say.
///
/// The wording comes from [`report::Verdict`] and nowhere else, so the hook, the
/// report, the badge and the card cannot disagree about whether the agent is
/// calibrated — which they did, when each parsed the confidence gap for itself.
fn standing_line(d: &ReportData) -> Option<String> {
    if d.evidence_n < MIN_N {
        return None;
    }
    let n = d.evidence_n;
    Some(match d.verdict {
        Verdict::InsufficientData => return None,
        Verdict::Withheld => format!(
            "NO VERDICT: {} of your {} settled claims {}, so no reading of your {n} graded calls can be trusted. Resolve a claim when it answers, even when it went against you; void only a question that stopped making sense, and reword only before the answer is in sight.",
            d.voids.edited().0, d.voids.settled, d.voids.edited().1
        ),
        Verdict::NoEvidenceOfMiscalibration => format!(
            "no miscalibration found across {n} graded calls — which is not proof you are calibrated, only that nothing shows otherwise"
        ),
        Verdict::CalibratedButUninformative => format!(
            "right on average across {n} calls, but your confidence does not separate the ones that come true — spread your probabilities out"
        ),
        Verdict::Overconfident => format!(
            "OVERCONFIDENT ({n} graded): right {} of the time while claiming about {}. Add slack.",
            pct(d.accuracy),
            pct(d.mean_confidence)
        ),
        Verdict::Underconfident => format!(
            "UNDERCONFIDENT ({n} graded): right {} while claiming about {}. Trust your sure calls more.",
            pct(d.accuracy),
            pct(d.mean_confidence)
        ),
        Verdict::BiasedYes => format!(
            "LEANS YES ({n} graded): you predict things happen more often than they do."
        ),
        Verdict::BiasedNo => format!(
            "LEANS NO ({n} graded): you predict things don't happen more often than holds up."
        ),
        Verdict::MiscalibratedBothWays => format!(
            "MISCALIBRATED BOTH WAYS ({n} graded): too sure at one end of your range and not sure enough at the other. Shading everything one way will not help."
        ),
    })
}

fn pct(v: Option<f64>) -> String {
    v.map_or_else(|| "—".into(), |x| format!("{:.0}%", x * 100.0))
}

/// The worst per-kind slice, but only once it clears the multiplicity-corrected
/// bar — searching K subgroups for the worst one is K tests, not one.
fn worst_kind(d: &ReportData) -> Option<String> {
    // Naming an agent's "worst group" from a slice of the record that happens to
    // be tagged is advice drawn from a self-selected sample. Measured: 363 of 422
    // claims on a real ledger carried no `kind:` tag at all, so no grouping is
    // selected there and this stays quiet.
    let ns = d.group_by.as_deref()?;
    let threshold = d.kind_alarm_threshold?;
    let (row, e) = d
        .by_kind
        .iter()
        .filter_map(|t| t.eprocess.map(|e| (t, e)))
        .filter(|&(_, e)| e >= threshold)
        .max_by(|a, b| a.1.total_cmp(&b.1))?;
    let dir = match row.confidence_gap {
        Some(g) if g > 0.0 => "overconfident",
        Some(_) => "underconfident",
        None => "miscalibrated",
    };
    Some(format!(
        "  worst group: {}:{} is really {dir} (e={e:.0}, n={}, K={}) — trust those calls least",
        untrusted::tag(ns),
        untrusted::tag(&row.tag),
        row.n,
        d.group_k
    ))
}

/// The identities that count as this agent in the standing line.
///
/// Claude Code introduces itself to an MCP server as `claude-code` (captured from
/// 2.1.251), so everything the plugin's own MCP server logs carries
/// `who:claude-code`, while claims logged from the CLI under the documented
/// protocol carry `who:claude`. The standing line read only the second, so it was
/// blind to what the plugin itself had logged: 25 MCP predictions at 95%, all
/// wrong, produced an OVERCONFIDENT report and a hook that said nothing.
const AGENT_WHO: [&str; 2] = ["who:claude", "who:claude-code"];

/// This agent's claims, under either identity, as one agent.
///
/// The ledger on disk keeps the true client on every claim. In this private copy
/// both identities are `who:claude`, so the report logic sees one agent and the
/// grouping selector cannot mistake the two names for a two-group breakdown.
fn agent_claims(ledger: &Ledger) -> Ledger {
    let mut claims = Vec::new();
    for c in &ledger.claims {
        if !c.tags.iter().any(|t| AGENT_WHO.contains(&t.as_str())) {
            continue;
        }
        let mut c = c.clone();
        let mut tags: Vec<String> = Vec::with_capacity(c.tags.len());
        for t in c.tags.drain(..) {
            let t = if t == "who:claude-code" {
                "who:claude".to_string()
            } else {
                t
            };
            if !tags.contains(&t) {
                tags.push(t);
            }
        }
        c.tags = tags;
        claims.push(c);
    }
    Ledger {
        claims,
        ..Default::default()
    }
}

/// The project slug, used to scope "what is due here".
pub(crate) fn project_slug(cwd: Option<&str>) -> String {
    let dir = cwd
        .map(std::path::PathBuf::from)
        .or_else(|| std::env::current_dir().ok())
        .unwrap_or_default();
    dir.file_name()
        .map(|n| n.to_string_lossy().to_lowercase())
        .unwrap_or_else(|| "unknown".into())
}

fn due_lines(ledger: &Ledger, today: NaiveDate, slug: &str) -> Vec<String> {
    let lines: Vec<String> = ledger
        .claims
        .iter()
        .filter(|c| !c.is_void() && c.is_due(today))
        .filter(|c| c.tags.iter().any(|t| t == &format!("project:{slug}")))
        .take(5)
        .map(|c| format!("  DUE {} — resolve it", quoted(c)))
        .collect();
    framed(lines)
}

/// One claim as a single quoted line of stored data: `[id] "statement"`.
fn quoted(c: &Claim) -> String {
    format!(
        "[{}] \"{}\"",
        untrusted::tag(&c.id),
        untrusted::line(&c.statement, untrusted::MAX_LINE)
    )
}

/// Put the "this is data" label in front of any block of ledger text.
fn framed(lines: Vec<String>) -> Vec<String> {
    if lines.is_empty() {
        return lines;
    }
    let mut out = vec![format!("  ({})", untrusted::FRAME)];
    out.extend(lines);
    out
}

/// The per-session prompt counter, kept next to the ledger. Returns the new count.
/// Whether prompt `n` of `session` gets the checkpoint: a draw with probability `1/every`.
///
/// It used to be every `every`-th prompt, which shows the same amount but can say nothing
/// about whether it helps: a fixed schedule has no comparison. A draw per prompt, logged
/// with its probability, is a micro-randomized trial (Klasnja et al. 2015): within one
/// session, prompts that got it and prompts that did not differ only by chance, so a few
/// sessions are enough for a randomization test that is exact. The draw is a hash of the
/// session id and the prompt number, so it is reproducible and cannot depend on what the
/// prompt says. `every = 1` shows it every time.
pub(crate) fn checkpoint_drawn(session: &str, n: u64, every: u64) -> bool {
    let mut h: u64 = 0xcbf2_9ce4_8422_2325; // FNV-1a
    for b in session.bytes().chain(n.to_le_bytes()) {
        h ^= u64::from(b);
        h = h.wrapping_mul(0x0100_0000_01b3);
    }
    let mut z = h.wrapping_add(0x9e37_79b9_7f4a_7c15); // SplitMix64's finaliser
    z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
    z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
    z ^= z >> 31;
    z.is_multiple_of(every.max(1))
}

/// One line per prompt in `checkpoints.jsonl`, beside the ledger: which prompt, the chance
/// it had, and whether it was drawn. Never the prompt. This is the assignment record the
/// analysis in `validation/effect_report.py` reads; claims are matched to the prompt they
/// were logged under by their `origin.session` and time.
/// `drawn` is the assignment, made before anything is known; `shown` is whether the
/// checkpoint was then actually printed. They differ when a drawn prompt has nothing to
/// say (an empty or unreadable ledger), and the analysis needs both: the assignment for
/// the test, the difference for how often it was a no-op.
fn log_checkpoint(
    ledger_path: &std::path::Path,
    session: &str,
    n: u64,
    every: u64,
    drawn: bool,
    shown: bool,
) {
    let rec = json!({
        "v": 2,
        "at": Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true),
        "session": untrusted::tag(session),
        "prompt": n,
        "p": 1.0 / every.max(1) as f64,
        "drawn": drawn,
        "shown": shown,
        "arm": crate::trial::arm_today(ledger_path).map(crate::trial::Arm::label),
        "engine": VERSION,
    });
    let _ = store::append_private(
        &ledger_path.with_file_name("checkpoints.jsonl"),
        &rec.to_string(),
    );
}

fn bump_counter(session: &str) -> u64 {
    let Some(dir) = dirs_counters() else {
        return 1;
    };
    let _ = std::fs::create_dir_all(&dir);
    let file = dir.join(format!("{}.count", sanitize(session)));
    let n = std::fs::read_to_string(&file)
        .ok()
        .and_then(|s| s.trim().parse::<u64>().ok())
        .unwrap_or(0)
        + 1;
    let _ = std::fs::write(&file, n.to_string());
    n
}

/// The current prompt number of `session`, read without counting a new prompt.
pub(crate) fn current_prompt(session: &str) -> Option<u64> {
    let file = dirs_counters()?.join(format!("{}.count", sanitize(session)));
    std::fs::read_to_string(file).ok()?.trim().parse().ok()
}

/// Whether this is the first Stop of the session, remembered in a marker file beside the
/// prompt counters. The Stop hook speaks once per session, not at the end of every turn.
/// If the marker cannot be written there is nothing to remember it by, and it speaks.
fn first_stop_of_session(session: &str) -> bool {
    let Some(dir) = dirs_counters() else {
        return true;
    };
    let _ = std::fs::create_dir_all(&dir);
    std::fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(dir.join(format!("{}.stop", sanitize(session))))
        .is_ok()
}

pub(crate) fn dirs_counters() -> Option<std::path::PathBuf> {
    #[allow(deprecated)]
    std::env::home_dir().map(|h| h.join(".anamnesis").join("counters"))
}

pub(crate) fn sanitize(s: &str) -> String {
    s.chars()
        .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
        .take(64)
        .collect()
}

/// The kinds of test runner whose exit status answers "did the tests pass".
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Runner {
    Cargo,
    /// Everything else we recognise: pytest, go, npm and friends, flutter, gradle, maven.
    Other,
}

impl Runner {
    /// The exit codes that mean "the tests ran and at least one failed".
    ///
    /// Any other non-zero status means the run itself went wrong: a missing directory, a
    /// usage error, a crash before a test started. It says nothing about the claim, and
    /// grading it FALSE would record a failure that did not happen.
    fn failure_codes(self) -> &'static [i64] {
        match self {
            Runner::Cargo => &[101],
            Runner::Other => &[1],
        }
    }

    /// Whether the evidence shows the suite failing, not merely the runner stopping.
    ///
    /// Cargo exits 101 for a failing test, but also for a manifest it cannot find, an
    /// unknown subcommand and most other errors, and a live session once graded a run
    /// that tested nothing as a failed suite. Every other runner exits 1 for a missing
    /// directory, a missing module and a project with no test script, as well as for a
    /// failing test; an independent review found each of those graded FALSE. So a
    /// failure needs the runner's own words for one, and none of the words for the other.
    fn confirms_failure(self, f: &RunFacts) -> bool {
        match self {
            Runner::Cargo => f.cargo_failed || f.compile_error,
            Runner::Other => f.fail_marker && !f.env_error,
        }
    }

    /// Whether the evidence shows a test passing, so a pass and a failure are judged by
    /// the same standard. `cargo test > log 2>&1` hides the output: its failure stayed
    /// ungraded while its pass was graded TRUE on nothing.
    fn confirms_pass(self, f: &RunFacts) -> bool {
        match self {
            Runner::Cargo => f.cargo_passed > 0,
            Runner::Other => true,
        }
    }
}

/// What a runner's output says, gathered line by line so that it holds however much was
/// printed. `ana run` feeds it as the command streams past; a hook feeds it the output
/// Claude Code reports. Reading only the end of the output once lost a passing run: a
/// loud `cargo test -- --nocapture` pushed `running 1 test` out of a 64 KB tail.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct RunFacts {
    /// The total from every cargo `test result: ok. N passed` line.
    pub cargo_passed: u64,
    /// A cargo `test result: FAILED` line.
    pub cargo_failed: bool,
    /// Cargo's `could not compile`: the code under test does not build.
    pub compile_error: bool,
    /// Any runner's own words for a failing test: `1 failed`, `--- FAIL`, `FAIL`.
    pub fail_marker: bool,
    /// Words that mean the run never got going: `command not found`, `No module named`.
    pub env_error: bool,
    /// A runner saying no test ran: unittest's `NO TESTS RAN`, pytest's `collected 0
    /// items` or `no tests ran`, jest's `No tests found`, go's `[no test files]`.
    pub no_tests: bool,
    /// Any runner's words for a test that passed: `3 passed`, go's `ok  pkg`, unittest's
    /// `Ran 3 tests` followed by `OK`.
    pub saw_pass: bool,
}

/// Phrases that say no test ran at all.
const NO_TESTS: [&str; 6] = [
    "no tests ran",
    "collected 0 items",
    "no tests collected",
    "no tests found",
    "[no test files]",
    "ran 0 tests",
];

/// Phrases that say the run itself went wrong, whatever the exit code.
const ENV_ERRORS: [&str; 10] = [
    "command not found",
    "no such file or directory",
    "no module named",
    "no test specified",
    "missing script",
    "cannot find module",
    "go.mod file not found",
    "is not recognized as",
    "permission denied",
    "enoent",
];

impl RunFacts {
    /// The facts in a whole block of output.
    pub fn of(text: &str) -> RunFacts {
        let mut f = RunFacts::default();
        for line in text.lines() {
            f.observe_line(line);
        }
        f
    }

    /// Fold one line of output in.
    pub fn observe_line(&mut self, line: &str) {
        let l = line.trim();
        if l.is_empty() {
            return;
        }
        if let Some(rest) = l.strip_prefix("test result: ok.") {
            if let Some(n) = rest
                .split(';')
                .next()
                .and_then(|part| counts_before(part, "passed").next())
            {
                self.cargo_passed = self.cargo_passed.saturating_add(n);
            }
        } else if l.starts_with("test result: FAILED") {
            self.cargo_failed = true;
        }
        if l.contains("could not compile") {
            self.compile_error = true;
        }
        let lower = l.to_ascii_lowercase();
        if lower.starts_with("--- fail")
            || l == "FAIL"
            || l.starts_with("FAIL\t")
            || l.starts_with("FAIL ")
            || l.starts_with("FAILED ")
            || ["failed", "failing", "failures"]
                .iter()
                .any(|w| counts_before(&lower, w).any(|n| n > 0))
        {
            self.fail_marker = true;
        }
        if ENV_ERRORS.iter().any(|e| lower.contains(e)) {
            self.env_error = true;
        }
        if NO_TESTS.iter().any(|e| lower.contains(e)) {
            self.no_tests = true;
        }
        if counts_before(&lower, "passed").any(|n| n > 0)
            || l.starts_with("ok ")
            || l.starts_with("ok\t")
            || counts_before(&lower, "test").any(|n| n > 0) && lower.starts_with("ran ")
        {
            self.saw_pass = true;
        }
    }

    /// Fold another stream's facts into these (stdout and stderr are read separately).
    pub fn merge(&mut self, other: &RunFacts) {
        self.cargo_passed = self.cargo_passed.saturating_add(other.cargo_passed);
        self.cargo_failed |= other.cargo_failed;
        self.compile_error |= other.compile_error;
        self.fail_marker |= other.fail_marker;
        self.env_error |= other.env_error;
        self.no_tests |= other.no_tests;
        self.saw_pass |= other.saw_pass;
    }
}

/// How many tests a run's output says passed: cargo's `test result: ok. N passed` lines
/// summed over test binaries, else the last `N passed` any runner printed (pytest, jest,
/// vitest). `None` when the output names no number, as go's `ok  pkg` does.
pub(crate) fn passed_count(text: &str) -> Option<u64> {
    let f = RunFacts::of(text);
    if f.cargo_passed > 0 {
        return Some(f.cargo_passed);
    }
    text.lines()
        .rev()
        .find_map(|l| counts_before(&l.to_ascii_lowercase(), "passed").last())
}

/// Every `N` that is directly followed by a word starting with `word`, in `text`:
/// `1 failed, 3 passed` gives 1 for "failed" and 3 for "passed".
fn counts_before<'a>(text: &'a str, word: &'a str) -> impl Iterator<Item = u64> + 'a {
    let toks: Vec<&str> = text.split_whitespace().collect();
    (0..toks.len().saturating_sub(1)).filter_map(move |i| {
        if toks[i + 1].starts_with(word) {
            toks[i]
                .trim_matches(|c: char| !c.is_ascii_digit())
                .parse()
                .ok()
        } else {
            None
        }
    })
}

/// Flags that make a test command not run any test, by exact match or by prefix.
const NON_RUNNING_EXACT: [&str; 3] = ["--co", "-h", "-V"];
const NON_RUNNING_PREFIX: [&str; 11] = [
    "--no-run",
    "--collect-only",
    "--help",
    "--version",
    "--list",
    "-list",
    "--setup-",
    "--fixtures",
    "--markers",
    "--trace-config",
    "--dry-run",
];

/// Environment variables that cannot change whether, or which, tests run. Anything else
/// can: `PYTEST_ADDOPTS=--co` and `GOFLAGS=-run=^$` turn a runner into a no-op that
/// exits 0, and `CARGO_TARGET_<triple>_RUNNER=true` replaces the test binary with `true`.
const HARMLESS_ENV: [&str; 12] = [
    "RUST_BACKTRACE",
    "RUST_LOG",
    "CI",
    "NO_COLOR",
    "FORCE_COLOR",
    "CARGO_TERM_COLOR",
    "PYTHONUNBUFFERED",
    "PYTHONDONTWRITEBYTECODE",
    "PYTHONPATH",
    "NODE_ENV",
    "TERM",
    "TZ",
];

/// Characters that let a shell do something other than run one command and report its
/// status. Quoting is refused wholesale, not parsed: a quoted flag reaches the runner
/// unquoted (`cargo test '--no-run'` is `cargo test --no-run`), so the matcher cannot
/// judge a command it has not read the way the shell will.
const SHELL_SYNTAX: [char; 14] = [
    '|', ';', '`', '(', ')', '\n', '#', '\'', '"', '\\', '$', '{', '}', '!',
];

/// A test run whose exit status is a trustworthy answer, or `None`.
///
/// Claude Code sends no exit status. It sends a command that exited 0 as `PostToolUse`,
/// and one that exited non-zero as `PostToolUseFailure`, so the event stands in for the
/// status, and it stands in for the *shell's* status. Anything that can make that differ
/// from the runner's own is refused: a pipe (the status is the last stage's), `||`
/// (swallowed), `;` or `&` (a later command wins, or it ran in the background), a
/// comment (`cd #x && cargo test` never runs cargo), a subshell, a substitution, a
/// negation, any quoting, and an environment variable that is not on a short allowlist.
/// Measured: `cargo test 2>&1 | tail -3` over a failing test and `cargo test || true`
/// both arrive as ordinary successes.
///
/// A leading `cd DIR &&` is allowed, with a plain directory word, since it is how agents
/// run tests. The runner must then be the command itself, not a word in an `echo`.
/// Builds and lints are not tests: `cargo build` is not an answer to "the tests pass".
fn test_run(cmd: &str) -> Option<Runner> {
    let cmd = cmd.trim();
    if cmd.is_empty() || cmd.contains(SHELL_SYNTAX) {
        return None;
    }
    // `2>&1` and friends are redirections, not background jobs.
    let flat = cmd
        .replace("2>&1", " ")
        .replace("1>&2", " ")
        .replace(">&2", " ")
        .replace("&>", " ");
    let mut segments: Vec<&str> = flat.split("&&").map(str::trim).collect();
    let last = segments.pop()?;
    if segments.iter().any(|s| !is_plain_cd(s)) || last.contains('&') {
        return None;
    }
    let mut toks: Vec<&str> = last.split_whitespace().collect();
    while let Some((name, _)) = toks.first().and_then(|t| assignment(t)) {
        if !HARMLESS_ENV.contains(&name) {
            return None;
        }
        toks.remove(0);
    }
    runner_of(&toks)
}

/// `cd DIR` where DIR is a plain path word, so nothing in it can be an operator.
fn is_plain_cd(segment: &str) -> bool {
    let t: Vec<&str> = segment.split_whitespace().collect();
    t.len() == 2
        && t[0] == "cd"
        && !t[1].is_empty()
        && t[1]
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || "._/~+-".contains(c))
}

/// The runner a command line starts, from its words. Shared by the hook, which reads
/// them out of a shell command, and `ana run`, which is handed them directly.
/// Whether any word is a flag that makes the command not run a test (`--no-run`, `--help`).
pub(crate) fn has_non_running_flag(t: &[&str]) -> bool {
    t.iter().any(|w| {
        NON_RUNNING_EXACT.contains(w) || NON_RUNNING_PREFIX.iter().any(|p| w.starts_with(p))
    })
}

pub(crate) fn runner_of(t: &[&str]) -> Option<Runner> {
    if has_non_running_flag(t) {
        return None;
    }
    match t {
        ["cargo", rest @ ..] => {
            // Skip a toolchain selector: `cargo +nightly test`.
            let rest: &[&str] = match rest {
                [first, tail @ ..] if first.starts_with('+') => tail,
                _ => rest,
            };
            match rest {
                ["test", ..] => Some(Runner::Cargo),
                _ => None,
            }
        }
        ["npm" | "pnpm" | "yarn" | "bun", "test" | "t" | "tst", ..]
        | ["npm" | "pnpm" | "yarn" | "bun", "run" | "run-script", "test", ..] => {
            Some(Runner::Other)
        }
        ["pytest" | "py.test" | "jest" | "vitest", ..]
        | ["python" | "python3", "-m", "pytest", ..]
        | ["npx" | "pnpx" | "bunx", "jest" | "vitest" | "pytest", ..]
        | ["go" | "flutter" | "dart", "test", ..] => Some(Runner::Other),
        ["gradle" | "./gradlew" | "gradlew" | "mvn" | "./mvnw", rest @ ..]
            if rest.contains(&"test") =>
        {
            Some(Runner::Other)
        }
        _ => None,
    }
}

/// `NAME=value`, with a valid shell identifier for a name.
pub(crate) fn assignment(tok: &str) -> Option<(&str, &str)> {
    let (name, value) = tok.split_once('=')?;
    let ok = !name.is_empty()
        && !name.starts_with(|c: char| c.is_ascii_digit())
        && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_');
    ok.then_some((name, value))
}

/// Whether `cmd` is `ana run ...`, which settles its own claim and needs no nudge.
pub(crate) fn is_ana_run(cmd: &str) -> bool {
    let toks: Vec<&str> = cmd
        .rsplit("&&")
        .next()
        .unwrap_or("")
        .split_whitespace()
        .collect();
    let is_ana = |t: &str| {
        let name = t.rsplit(['/', '\\']).next().unwrap_or(t);
        name == "ana" || name == "ana.exe"
    };
    if !toks.first().is_some_and(|t| is_ana(t)) {
        return false;
    }
    // The subcommand is the first word past the global flags. Taking any later `run` counted
    // `ana add "the suite will run" --prob 0.7` as a pinned run.
    let mut rest = toks[1..].iter();
    while let Some(t) = rest.next() {
        match *t {
            "--data" => {
                rest.next();
            }
            "--json" => {}
            t if t.starts_with("--data=") => {}
            t => return t == "run",
        }
    }
    false
}

/// The exit code Claude Code puts inside a failed call's `error` text, which reads
/// `"Exit code 101\n<output>"`.
fn exit_code_in(error: &str) -> Option<i64> {
    let digits: String = error
        .strip_prefix("Exit code ")?
        .chars()
        .take_while(char::is_ascii_digit)
        .collect();
    digits.parse().ok()
}

/// What a finished command says about the claim it was pinned to.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RunJudgement {
    Passed,
    Failed,
    /// The command ended, but not in a way that answers the claim; the reason says why.
    NotGraded(&'static str),
}

/// Judge a finished run of `runner` from its exit `code` and what its output showed.
fn judge(runner: Runner, code: i64, facts: &RunFacts) -> RunJudgement {
    // `go test ./...` in a module without tests prints `[no test files]` and exits 0; that
    // passed nothing. Mixed output (`ok` for one package) still passes.
    if facts.no_tests && !facts.saw_pass && !facts.fail_marker && !facts.cargo_failed {
        return RunJudgement::NotGraded("the runner says no test ran");
    }
    if code == 0 {
        if runner.confirms_pass(facts) {
            RunJudgement::Passed
        } else {
            RunJudgement::NotGraded("no test was seen to pass")
        }
    } else if runner.failure_codes().contains(&code) && runner.confirms_failure(facts) {
        RunJudgement::Failed
    } else {
        RunJudgement::NotGraded(
            "that exit status is not a failed suite for this runner, or its output does not show one",
        )
    }
}

/// Judge a pinned command from its exit `code` and the facts its output showed.
///
/// `ana run` started the process itself and was handed its words directly, so there is
/// no shell to swallow the status and the shape checks a hook needs do not apply. The
/// runner knowledge does. A command that is not a test runner, `make ci` or a script, is
/// simply judged by its own exit status, since pinning it was the claim-maker's choice.
///
/// What it will not do is grade a run that never ran a test, whatever the command: one
/// that only lists or builds them (`--collect-only`, `--no-run`), one whose runner says
/// no test ran (unittest exits 5 with `NO TESTS RAN`), or one that never started
/// (`No module named pytest`, `command not found`). An audit of 0.5.0 found each of
/// those graded FALSE, a failure that did not happen.
pub fn judge_run(argv: &[String], code: i64, facts: &RunFacts) -> RunJudgement {
    let toks: Vec<&str> = argv.iter().map(String::as_str).collect();
    if has_non_running_flag(&toks) {
        return RunJudgement::NotGraded("that command lists or builds tests without running them");
    }
    match runner_of(&toks) {
        Some(runner) => judge(runner, code, facts),
        None if facts.no_tests && !facts.saw_pass && !facts.fail_marker => {
            RunJudgement::NotGraded("the runner says no test ran")
        }
        None if code != 0 && facts.env_error && !facts.fail_marker => {
            RunJudgement::NotGraded("the command never started")
        }
        None if code == 0 => RunJudgement::Passed,
        None => RunJudgement::Failed,
    }
}

/// What a post-tool event says about the claim it might settle.
enum Grade {
    /// The runner's own exit status, taken from the event it arrived as.
    Exit(i64),
    /// A test command was seen, but its status cannot be trusted.
    Untrusted,
    /// Nothing to say.
    NotATest,
}

fn grade_of(event: Event, input: &Value, cmd: &str) -> Grade {
    // Claude Code returns a background call at once, before anything has run: a suite
    // that fails a minute later has already been "passed".
    if input
        .pointer("/tool_input/run_in_background")
        .and_then(Value::as_bool)
        == Some(true)
    {
        return Grade::NotATest;
    }
    let Some(runner) = test_run(cmd) else {
        return if event == Event::PostTool
            && !is_ana_run(cmd)
            && crate::pin::test_run_in(cmd).is_some()
        {
            Grade::Untrusted
        } else {
            Grade::NotATest
        };
    };
    let text = |p: &str| input.pointer(p).and_then(Value::as_str).unwrap_or("");
    match event {
        // Claude Code sends this event only for a call that succeeded.
        Event::PostTool => {
            let out = format!(
                "{}\n{}",
                text("/tool_response/stdout"),
                text("/tool_response/stderr")
            );
            match judge(runner, 0, &RunFacts::of(&out)) {
                RunJudgement::Passed => Grade::Exit(0),
                _ => Grade::Untrusted,
            }
        }
        Event::PostToolFailure => {
            if input.get("is_interrupt").and_then(Value::as_bool) == Some(true) {
                return Grade::NotATest;
            }
            let error = text("/error");
            match exit_code_in(error) {
                Some(code) => match judge(runner, code, &RunFacts::of(error)) {
                    RunJudgement::Failed => Grade::Exit(code),
                    _ => Grade::NotATest,
                },
                None => Grade::NotATest,
            }
        }
        _ => Grade::NotATest,
    }
}

/// Run one hook. `stdin` is the hook's JSON payload; the result is what to print.
pub fn run(event: Event, ledger_path: &std::path::Path) -> Result<(), String> {
    let mut raw = String::new();
    let _ = std::io::stdin().read_to_string(&mut raw);
    let input: Value = serde_json::from_str(raw.trim()).unwrap_or_else(|_| json!({}));
    note(event, 0, true);

    // Every path below fails soft into "say nothing" — except a missing engine,
    // which cannot happen here because the engine IS this binary. That was the
    // point of moving the logic in.
    //
    // Except that "silent" must not mean "silently broken": a ledger that cannot be read
    // is remembered, so the session hooks can say so. A user whose hooks never fired had
    // no way to find out why, which is what moving them into the binary was meant to end.
    let (ledger, load_error) = match store::load(ledger_path) {
        Ok(l) => (l, None),
        Err(e) => (Ledger::default(), Some(e)),
    };
    let today = Utc::now().date_naive();
    let cwd = input.get("cwd").and_then(Value::as_str);
    let slug = project_slug(cwd);
    // Inside an OFF week of the weekly trial (MEASUREMENT.md, addendum 4) nothing that
    // reaches the model is said; grading and the logs go on as in an ON week.
    let speaks = crate::trial::speaks(ledger_path);

    // A file edit: one silent line in the outcome log, which the trial's primary outcome
    // needs, and nothing else.
    if event == Event::PostTool && crate::pin::is_edit(&input) {
        crate::pin::log_edit(
            &input,
            ledger_path,
            input
                .get("session_id")
                .and_then(Value::as_str)
                .and_then(current_prompt),
        );
        return Ok(());
    }

    // The opt-in "pin first" reminder runs before the call, and is its own reply.
    if event == Event::PreTool {
        if (crate::pin::enabled() || crate::pin::audit_rate().is_some()) && speaks {
            if let Some(out) = crate::pin::pre_tool(&input, &ledger, ledger_path) {
                let said = out
                    .pointer("/hookSpecificOutput/permissionDecisionReason")
                    .and_then(Value::as_str)
                    .map_or(0, str::len);
                note(event, said, false);
                println!("{out}");
            }
        }
        return Ok(());
    }
    if event == Event::SessionStart && crate::pin::enabled() {
        crate::pin::prune_state();
    }

    let mut context: Vec<String> = Vec::new();
    let mut user_message: Option<String> = None;
    // What the post-tool hook has to tell the person about their bets, if anything.
    let mut bet_note: Option<String> = None;
    // A drawn checkpoint, logged once it is known whether anything was shown.
    let mut checkpoint: Option<(&str, u64, u64)> = None;

    match event {
        Event::PreTool => {} // handled above
        Event::SessionStart | Event::UserPrompt => {
            if event == Event::SessionStart && !speaks {
                return Ok(());
            }
            if event == Event::UserPrompt {
                let session = input
                    .get("session_id")
                    .and_then(Value::as_str)
                    .unwrap_or("default");
                // A bet on the agent is blocked before the counter moves: it never
                // reaches the model, so it is not one of the model's prompts.
                if let Some(parsed) = input
                    .get("prompt")
                    .and_then(Value::as_str)
                    .and_then(crate::bet::parse)
                {
                    let reason = match parsed.and_then(|p| {
                        crate::bet::record(
                            ledger_path,
                            session,
                            current_prompt(session).unwrap_or(0),
                            &slug,
                            p,
                        )
                        .map(|id| (id, p))
                    }) {
                        Ok((id, p)) => format!(
                            "anamnesis: bet [{}] logged, {:.0}% that {}. The agent was not told. It is graded by that run's exit status; `ana --data {} report` reads your bets.",
                            untrusted::tag(&id),
                            p * 100.0,
                            crate::bet::STATEMENT,
                            crate::bet::path(ledger_path).display()
                        ),
                        Err(e) => format!(
                            "anamnesis: not a bet, and not sent to the agent: {}",
                            untrusted::line(&e, 160)
                        ),
                    };
                    println!("{}", crate::bet::block(reason));
                    return Ok(());
                }
                let every = env_usize("ANAMNESIS_INTROSPECT_EVERY", DEFAULT_EVERY);
                let n = bump_counter(session);
                if !speaks {
                    // An OFF week draws nothing; the line records that the prompt happened.
                    log_checkpoint(ledger_path, session, n, every, false, false);
                    return Ok(());
                }
                let drawn = checkpoint_drawn(session, n, every);
                if !drawn {
                    log_checkpoint(ledger_path, session, n, every, false, false);
                    return Ok(()); // silent on the prompts the draw passed over
                }
                checkpoint = Some((session, n, every));
                context.push(format!(
                    "⟢ Anamnesis (ana {VERSION}) — self-introspection checkpoint (prompt #{n})"
                ));
            } else {
                context.push(format!(
                    "⟢ Anamnesis (ana {VERSION}) — your standing calibration"
                ));
            }

            if let Some(e) = &load_error {
                println!(
                    "{}",
                    json!({ "systemMessage": format!(
                        "anamnesis: the agent ledger could not be read ({}), so the calibration hooks have nothing to say. Nothing was changed; fix or restore it, or the hooks stay quiet.",
                        untrusted::line(&e.to_string(), 200)
                    ) })
                );
                if let Some((s, n, every)) = checkpoint {
                    log_checkpoint(ledger_path, s, n, every, true, false);
                }
                return Ok(());
            }
            let d = ReportData::compute(&agent_claims(&ledger), Some("who:claude"), 10, today);
            if let Some(line) = standing_line(&d) {
                context.push(line);
                if let Some(k) = worst_kind(&d) {
                    context.push(k);
                }
            }
            if d.evidence_ungraded_due > 0 {
                if let Some(id) = &d.evidence_oldest_gap {
                    context.push(format!(
                        "  {} ungraded call(s) are costing you evidence, oldest [{}] — resolve or void them",
                        d.evidence_ungraded_due,
                        untrusted::tag(id)
                    ));
                }
            }
            context.extend(due_lines(&ledger, today, &slug));
            // The rule goes in at the start of every session, and again after /clear and
            // compaction (SessionStart fires for both). The most reliable place for an
            // instruction a model would otherwise skip is the start of its context.
            if event == Event::SessionStart && crate::pin::enabled() {
                context.push(crate::pin::standing_rule());
            }
            if event == Event::SessionStart {
                if let Some(p) = owner_protocol(ledger_path) {
                    context.push(p);
                }
            }
            if context.len() == 1 {
                if let Some((s, n, every)) = checkpoint {
                    log_checkpoint(ledger_path, s, n, every, true, false);
                }
                return Ok(()); // header only: nothing worth saying
            }
            context.push(
                "Log predictions with a probability BEFORE acting; resolve them the moment reality answers.".into(),
            );
            if let Some((s, n, every)) = checkpoint {
                log_checkpoint(ledger_path, s, n, every, true, true);
            }
        }

        Event::PostTool | Event::PostToolFailure => {
            let cmd = input
                .pointer("/tool_input/command")
                .and_then(Value::as_str)
                .unwrap_or("");
            // A file changed through the shell: one silent line of its own kind, so the
            // weekly trial's edit-turns stay as registered (MEASUREMENT.md, addendum 5).
            if event == Event::PostTool && crate::pin::edits_by_shell(cmd) {
                crate::pin::log_shell_edit(
                    &input,
                    ledger_path,
                    cmd,
                    input
                        .get("session_id")
                        .and_then(Value::as_str)
                        .and_then(current_prompt),
                );
            }
            // The exit status is the fact. Grading a "the tests will pass"
            // prediction from the agent's own account of what happened is the
            // weakest link in a self-graded ledger; this removes it.
            let grade = grade_of(event, &input, cmd);
            {
                let background = input
                    .pointer("/tool_input/run_in_background")
                    .and_then(Value::as_bool)
                    == Some(true);
                let exit = match event {
                    _ if background => None,
                    Event::PostTool => Some(0),
                    _ => input
                        .get("error")
                        .and_then(Value::as_str)
                        .and_then(exit_code_in),
                };
                let graded = match grade {
                    _ if background => "background",
                    Grade::Exit(0) => "pass",
                    Grade::Exit(_) => "fail",
                    Grade::Untrusted => "untrusted",
                    Grade::NotATest => "not_graded",
                };
                let session = input.get("session_id").and_then(Value::as_str);
                let prompt = session.and_then(current_prompt);
                let edited =
                    crate::pin::log_outcome(&input, ledger_path, cmd, exit, graded, prompt);
                // The person's bets on the agent (`?70`): graded by a run that came after
                // an edit, and told to the person only.
                if let (Grade::Exit(code), Some(true), Some(s), Some(n)) =
                    (&grade, edited, session, prompt)
                {
                    match crate::bet::grade(ledger_path, s, n, *code) {
                        Ok(bets) if !bets.is_empty() => {
                            bet_note = Some(format!(
                                "anamnesis: your bet{} on the agent {} ({}): the test run after its edit {}",
                                if bets.len() > 1 { "s" } else { "" },
                                bets.iter()
                                    .map(|(id, p)| format!("[{}] {:.0}%", untrusted::tag(id), p * 100.0))
                                    .collect::<Vec<_>>()
                                    .join(", "),
                                if *code == 0 { "came true" } else { "did not come true" },
                                if *code == 0 { "passed".to_string() } else { format!("failed, exit {code}") }
                            ));
                        }
                        Ok(_) => {}
                        Err(e) => {
                            bet_note = Some(format!(
                                "anamnesis: a bet was not graded ({})",
                                untrusted::line(&e, 160)
                            ))
                        }
                    }
                }
            }
            match grade {
                Grade::NotATest => return Ok(()),
                Grade::Exit(code) => {
                    match auto_resolve(
                        ledger_path,
                        &slug,
                        input.get("session_id").and_then(Value::as_str),
                        cmd,
                        code,
                    ) {
                        // The ledger was busy or unreadable: the run is not graded, and
                        // the user is told so rather than left to wonder.
                        Err(e) => {
                            user_message = Some(format!(
                                "anamnesis: this test run was not graded ({})",
                                untrusted::line(&e, 160)
                            ));
                        }
                        Ok(resolved) if resolved.is_empty() => {}
                        Ok(resolved) => {
                            let happened = code == 0;
                            context.push(format!(
                                "⟢ Anamnesis (ana {VERSION}): resolved {} prediction(s) from the command's exit status ({code}) — {}, graded by the exit status, not by you: {}",
                                resolved.len(),
                                if happened { "it passed" } else { "it failed" },
                                resolved
                                    .iter()
                                    .map(|i| untrusted::tag(i))
                                    .collect::<Vec<_>>()
                                    .join(", ")
                            ));
                            user_message = Some(format!(
                                "anamnesis: auto-resolved {} prediction(s) from exit code {code}",
                                resolved.len()
                            ));
                        }
                    }
                }
                Grade::Untrusted => {
                    let project = format!("project:{slug}");
                    let session = input.get("session_id").and_then(Value::as_str);
                    // A test command ran, but its exit status cannot be trusted
                    // (piped, chained, or no test ran). Say so, and say plainly
                    // that resolving it now is on the agent's word.
                    let open: Vec<String> = ledger
                        .claims
                        .iter()
                        .filter(|c| c.is_open() && !c.is_void())
                        .filter(|c| {
                            c.tags.iter().any(|t| t == "kind:tests-pass")
                                || c.tags.iter().any(|t| t == "kind:approach")
                        })
                        // Only this project's claims, or this session's. It used to name
                        // open claims from every project on the machine, which an agent
                        // can only resolve by guessing.
                        .filter(|c| {
                            c.tags.iter().any(|t| t == &project)
                                || session.is_some_and(|s| {
                                    c.extra
                                        .get("origin")
                                        .and_then(|o| o.get("session"))
                                        .and_then(Value::as_str)
                                        == Some(s)
                                })
                        })
                        .take(5)
                        .map(|c| untrusted::tag(&c.id))
                        .collect();
                    if open.is_empty() {
                        return Ok(());
                    }
                    context.push(format!(
                        "⟢ Anamnesis (ana {VERSION}) (moment of truth): a test command just ran, but its exit status cannot be trusted here (it was piped, chained, or ran no tests), so nothing was graded automatically. Resolve your open prediction(s) about it NOW ({}), before hindsight rewrites how sure you were; this one is on your word.",
                        open.join(", ")
                    ));
                }
            }
        }

        Event::Stop => {
            // For a Stop hook, Claude Code reads `additionalContext` as "the conversation
            // continues so Claude can act on it". This arm used to return it whenever any
            // claim was overdue and never read `stop_hook_active`, so every turn was
            // followed by another until the turn cap: measured live, with one overdue
            // claim a one-word prompt ran 13 assistant messages. It shipped in the plugin.
            // A Stop hook here may speak to the person (`systemMessage`) and may never
            // return context.
            if input
                .get("stop_hook_active")
                .and_then(Value::as_bool)
                .unwrap_or(false)
            {
                return Ok(());
            }
            let overdue = ledger
                .claims
                .iter()
                .filter(|c| crate::evidence::came_due(c, today))
                .count();
            if overdue == 0 {
                return Ok(());
            }
            let session = input
                .get("session_id")
                .and_then(Value::as_str)
                .unwrap_or("default");
            if !first_stop_of_session(session) {
                return Ok(());
            }
            user_message = Some(format!(
                "anamnesis (ana {VERSION}): {overdue} prediction(s) are past their due date (their --by, or 1 to 7 days after they were logged, by kind) and ungraded, which leaves the calibration numbers resting on a self-selected sample. Resolve or void them. (Said once per session.)"
            ));
        }
    }

    if let Some(b) = bet_note {
        user_message = Some(match user_message {
            Some(m) => format!("{m}; {b}"),
            None => b,
        });
    }
    // An OFF week: whatever was computed, none of it reaches the model. What goes to the
    // person (`systemMessage`) is not part of the arm.
    if !speaks {
        context.clear();
    }
    if context.is_empty() && user_message.is_none() {
        return Ok(());
    }
    let mut out = json!({});
    if !context.is_empty() {
        let said = context.join("\n");
        note(event, said.len(), false);
        out["hookSpecificOutput"] = json!({
            "hookEventName": event.name(),
            "additionalContext": said,
        });
    }
    if let Some(msg) = user_message {
        out["systemMessage"] = json!(msg);
    }
    println!("{out}");
    Ok(())
}

/// Resolve open `kind:tests-pass` claims for this project from a command's exit
/// status, and return the ids that were graded.
///
/// Deliberately narrow: only claims explicitly tagged `kind:tests-pass`, only in
/// this project, and only when the claim was made before the command ran.
/// How old an unstamped claim may be and still be graded by a test run seen now.
const AUTO_UNSTAMPED_HOURS: i64 = 12;

/// Whether a claim belongs to the session whose test run is being graded.
///
/// A claim stamped with a session (`origin.session`, 0.5.0 on, inside Claude Code) is
/// graded only by a run in that session. One without a stamp, or a run whose session is
/// unknown, falls back to recency. Until 0.5.0 every open claim tagged with the folder's
/// name was graded by any run there: an October claim from another session, about another
/// checkout with the same folder name, was resolved by today's `cargo test`.
fn same_session(c: &Claim, session: Option<&str>, now: chrono::DateTime<Utc>) -> bool {
    let stamped = c
        .extra
        .get("origin")
        .and_then(|o| o.get("session"))
        .and_then(Value::as_str);
    match (stamped, session) {
        (Some(mine), Some(run)) => mine == untrusted::tag(run),
        _ => now - c.created_at <= chrono::Duration::hours(AUTO_UNSTAMPED_HOURS),
    }
}

fn auto_resolve(
    ledger_path: &std::path::Path,
    slug: &str,
    session: Option<&str>,
    cmd: &str,
    exit_code: i64,
) -> Result<Vec<String>, String> {
    let wait = std::time::Duration::from_millis(env_usize(
        "ANAMNESIS_HOOK_LOCK_WAIT_MS",
        DEFAULT_LOCK_WAIT_MS,
    ));
    let _guard = store::lock_within(ledger_path, wait).map_err(|e| e.to_string())?;
    let mut ledger = store::load(ledger_path).map_err(|e| e.to_string())?;
    let now = Utc::now();
    let passed = exit_code == 0;
    let project = format!("project:{slug}");

    let mut done = Vec::new();
    for c in ledger.claims.iter_mut() {
        if !c.is_open() || c.is_void() {
            continue;
        }
        if !c.tags.iter().any(|t| t == "kind:tests-pass") {
            continue;
        }
        // A pinned claim is settled by `ana run` and by nothing else: a hook grading
        // it from whichever test happened to run would be the escape pinning closes.
        if c.check.is_some() {
            continue;
        }
        if !c.tags.iter().any(|t| t == &project) {
            continue;
        }
        if c.created_at > now || !same_session(c, session, now) {
            continue;
        }
        c.resolution = Some(Resolution {
            at: now,
            outcome: Some(if passed {
                Outcome::True
            } else {
                Outcome::False
            }),
            value: None,
            note: Some(format!("auto: `{}` exited {exit_code}", cmd.trim())),
            resolved_by: Some(ResolvedBy::Auto),
        });
        done.push(c.id.clone());
    }
    if !done.is_empty() {
        store::save(ledger_path, &ledger).map_err(|e| e.to_string())?;
    }
    Ok(done)
}

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

    #[test]
    fn passed_count_reads_each_runners_own_number() {
        let cargo = "test result: ok. 3 passed; 0 failed\ntest result: ok. 2 passed; 0 failed";
        assert_eq!(passed_count(cargo), Some(5));
        assert_eq!(
            passed_count("===== 1 failed, 12 passed in 0.31s ====="),
            Some(12)
        );
        assert_eq!(passed_count("Tests:       4 passed, 4 total"), Some(4));
        assert_eq!(passed_count("ok  \texample.com/pkg\t0.01s"), None);
        assert_eq!(passed_count(""), None);
    }

    #[test]
    fn the_checkpoint_draw_has_the_logged_chance_and_every_one_always_draws() {
        let mut drawn = 0;
        for s in 0..400 {
            let session = format!("session-{s:04}");
            for n in 1..=50u64 {
                drawn += usize::from(checkpoint_drawn(&session, n, 7));
                assert!(checkpoint_drawn(&session, n, 1));
                assert!(checkpoint_drawn(&session, n, 0), "0 is read as always");
            }
        }
        // 20,000 draws at 1/7: 2857 expected, sd about 49.
        assert!((2650..3070).contains(&drawn), "{drawn} of 20000");
        // The same prompt of the same session always gets the same draw.
        assert_eq!(checkpoint_drawn("abc", 9, 7), checkpoint_drawn("abc", 9, 7));
    }

    #[test]
    fn the_checkpoint_log_records_the_draw_and_never_the_prompt() {
        let dir = std::env::temp_dir().join(format!("ana-cp-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let ledger = dir.join("agent.json");
        log_checkpoint(&ledger, "sess-1", 3, 7, true, true);
        log_checkpoint(&ledger, "sess-1", 4, 7, false, false);
        let text = std::fs::read_to_string(dir.join("checkpoints.jsonl")).unwrap();
        let rows: Vec<Value> = text
            .lines()
            .map(|l| serde_json::from_str(l).unwrap())
            .collect();
        assert_eq!(rows.len(), 2);
        assert_eq!(rows[0]["prompt"], 3);
        assert_eq!(rows[0]["drawn"], true);
        assert_eq!(rows[1]["drawn"], false);
        assert_eq!(rows[0]["shown"], true);
        assert!((rows[0]["p"].as_f64().unwrap() - 1.0 / 7.0).abs() < 1e-12);
        let mut keys: Vec<&str> = rows[0]
            .as_object()
            .unwrap()
            .keys()
            .map(String::as_str)
            .collect();
        keys.sort_unstable();
        assert_eq!(
            keys,
            ["arm", "at", "drawn", "engine", "p", "prompt", "session", "shown", "v"]
        );
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn plain_test_runs_are_graded() {
        for cmd in [
            "cargo test",
            "cargo test --all -- --nocapture",
            "cargo +nightly test -p foo",
            "  PYTHONPATH=. pytest -q ",
            "python3 -m pytest tests/",
            "npm test",
            "npm run test -- --watch=false",
            "pnpm test",
            "yarn test",
            "go test ./...",
            "flutter test",
            "npx vitest run",
            "./gradlew test",
            "mvn test",
            "cd /work/project && cargo test",
            "cd sub && RUST_LOG=debug cargo test 2>&1",
            "RUST_BACKTRACE=1 CI=true cargo test --color always",
        ] {
            assert!(test_run(cmd).is_some(), "should be graded: {cmd}");
        }
    }

    #[test]
    fn anything_that_can_change_the_shells_status_is_not() {
        for cmd in [
            "cargo test | tail -3",
            "cargo test 2>&1 | tail -3",
            "cargo test || true",
            "cargo test; echo done",
            "cargo test &",
            "cargo test && echo ok",
            "echo cargo test",
            "! cargo test",
            "(cargo test)",
            "x=$(cargo test)",
            "cargo test\nexit 0",
            "cd a && cd b && cargo test | cat",
            "make && cargo test",
            // Found by an independent review: an operator hidden in the cd segment.
            "cd #x && cargo test",
            "cd .&exit && cargo test",
            "cd a;b && cargo test",
            "cd $(pwd) && cargo test",
            "cd 'a b' && cargo test",
            "cargo test # && false",
            // Quoting reaches the runner unquoted; an unlisted environment variable can
            // turn a runner into a no-op.
            "cargo test '--no-run'",
            "cargo test \"--no-run\"",
            "cargo test --no\\-run",
            "PYTEST_ADDOPTS=--co pytest",
            "GOFLAGS=-run=^$ go test ./...",
            "CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_RUNNER=true cargo test",
            "cargo nextest run",
        ] {
            assert!(test_run(cmd).is_none(), "must not be graded: {cmd}");
        }
    }

    #[test]
    fn builds_lints_and_runs_that_test_nothing_are_not_tests() {
        for cmd in [
            "cargo build",
            "cargo clippy --all-targets",
            "cargo test --no-run",
            "cargo test -- --list",
            "pytest --collect-only",
            "pytest --help",
            "pytest --setup-plan",
            "pytest --fixtures",
            "go test -list .",
            "npm run build",
            "go build ./...",
            "ls -la",
            "git commit -m 'tests'",
            "ana run -- cargo test",
            "",
        ] {
            assert!(test_run(cmd).is_none(), "must not be graded: {cmd:?}");
        }
    }

    #[test]
    fn ana_run_is_recognised_and_left_alone() {
        assert!(is_ana_run("ana run abc123 -- cargo test"));
        assert!(is_ana_run(
            "/home/u/.anamnesis/bin/ana run abc123 -- cargo test"
        ));
        assert!(is_ana_run("ana --data x.json run abc123 -- pytest"));
        assert!(is_ana_run("cd /work && ana run abc123 -- cargo test"));
        assert!(is_ana_run(
            "ana --data x.json --json run abc123 -- cargo test"
        ));
        assert!(!is_ana_run("ana report -- run"));
        assert!(!is_ana_run("ana add \"the suite will run\" --prob 0.7"));
        assert!(!is_ana_run("ana --json list run"));
        assert!(is_ana_run("ana --json --data=x.json run abc -- cargo test"));
        assert!(!is_ana_run("cargo test"));
        assert!(!is_ana_run("echo ana run"));
        assert!(!is_ana_run("ana report"));
    }

    #[test]
    fn a_test_failure_is_only_the_runners_own_failure_code() {
        assert_eq!(test_run("cargo test").unwrap().failure_codes(), [101]);
        assert_eq!(test_run("pytest").unwrap().failure_codes(), [1]);
    }

    #[test]
    fn cargo_must_say_the_suite_failed_not_merely_that_it_stopped() {
        let cargo = Runner::Cargo;
        let f = RunFacts::of;
        assert!(cargo.confirms_failure(&f(
            "Exit code 101\n\ntest result: FAILED. 0 passed; 1 failed"
        )));
        assert!(
            cargo.confirms_failure(&f("Exit code 101\nerror: could not compile `x` (lib test)"))
        );
        assert!(!cargo.confirms_failure(&f(
            "Exit code 101\nerror: manifest path `tiny/Cargo.toml` does not exist"
        )));
        assert!(!cargo.confirms_failure(&f("Exit code 101\nerror: no such command: `tset`")));
    }

    #[test]
    fn other_runners_must_show_a_failing_suite_and_no_sign_the_run_never_started() {
        let other = Runner::Other;
        let f = RunFacts::of;
        assert!(other.confirms_failure(&f("=== 1 failed, 3 passed in 0.1s ===")));
        assert!(other.confirms_failure(&f("--- FAIL: TestX (0.00s)\nFAIL\tpkg\t0.004s")));
        assert!(other.confirms_failure(&f("Tests:       2 failed, 4 passed, 6 total")));
        assert!(other.confirms_failure(&f("  2 passing\n  1 failing")));
        // Nothing failed, or the run never began.
        assert!(!other.confirms_failure(&f("=== 4 passed, 0 failed in 0.1s ===")));
        assert!(!other.confirms_failure(&f("Exit code 1")));
        assert!(!other.confirms_failure(&f("bash: pytest: command not found")));
        assert!(!other.confirms_failure(&f("/usr/bin/python3: No module named pytest")));
        assert!(!other.confirms_failure(&f(
            "1 failed\nbash: cd: /nonexistent: No such file or directory"
        )));
    }

    #[test]
    fn a_pinned_command_is_judged_by_its_own_status_and_the_runners_rules() {
        use RunJudgement::*;
        let argv = |s: &str| crate::check::split_command(s).unwrap();
        let j = |cmd: &str, code: i64, out: &str| judge_run(&argv(cmd), code, &RunFacts::of(out));
        // A plain script or make target: its exit status is the answer.
        assert_eq!(j("make ci", 0, ""), Passed);
        assert_eq!(j("make ci", 2, ""), Failed);
        assert_eq!(j("./scripts/check.sh", 1, "anything"), Failed);
        // A run that never ran a test is not graded either way (audit of 0.5.0).
        let ng = |r: RunJudgement| matches!(r, NotGraded(_));
        assert!(ng(j(
            "python3 -m pytest -q --co",
            1,
            "/usr/bin/python3: No module named pytest"
        )));
        assert!(ng(j(
            "python3 -m pytest --collect-only",
            0,
            "collected 4 items"
        )));
        assert!(ng(j(
            "python3 -m unittest",
            5,
            "Ran 0 tests in 0.000s\n\nNO TESTS RAN"
        )));
        assert!(ng(j(
            "go test ./...",
            0,
            "?   \texample.com/m\t[no test files]"
        )));
        assert!(ng(j(
            "./scripts/missing.sh",
            127,
            "sh: ./scripts/missing.sh: No such file or directory"
        )));
        // ...while a mixed `go test ./...` that passed a package still passes,
        assert_eq!(
            j(
                "go test ./...",
                0,
                "?   \texample.com/m\t[no test files]\nok  \texample.com/m/sub\t0.01s"
            ),
            Passed
        );
        // and unittest's real answers are read from its exit status.
        assert_eq!(
            j("python3 -m unittest", 0, "Ran 3 tests in 0.01s\n\nOK"),
            Passed
        );
        assert_eq!(
            j(
                "python3 -m unittest",
                1,
                "Ran 3 tests\n\nFAILED (failures=1)"
            ),
            Failed
        );
        // A test runner: only its own failure code, and evidence for either answer.
        assert_eq!(
            j("cargo test", 0, "test result: ok. 2 passed; 0 failed"),
            Passed
        );
        assert!(matches!(
            j("cargo test", 0, "test result: ok. 0 passed; 0 failed"),
            NotGraded(_)
        ));
        assert!(matches!(j("cargo test", 0, ""), NotGraded(_)));
        assert_eq!(
            j("cargo test", 101, "test result: FAILED. 0 passed; 1 failed"),
            Failed
        );
        assert!(matches!(
            j("cargo test", 101, "error: manifest path does not exist"),
            NotGraded(_)
        ));
        assert!(matches!(j("cargo test", 2, "usage error"), NotGraded(_)));
        assert_eq!(j("pytest -q", 1, "=== 1 failed in 0.1s ==="), Failed);
        assert!(matches!(j("pytest -q", 1, ""), NotGraded(_)));
        assert!(matches!(j("pytest -q", 5, "no tests ran"), NotGraded(_)));
        // `ana run` is handed words, so quotes are fine there: pytest is still pytest.
        assert_eq!(j(r#"pytest -k "not slow""#, 1, "1 failed"), Failed);
    }

    #[test]
    fn the_exit_code_is_read_from_the_error_text() {
        assert_eq!(exit_code_in("Exit code 101\n\nrunning 1 test"), Some(101));
        assert_eq!(exit_code_in("Exit code 3"), Some(3));
        assert_eq!(exit_code_in("Command timed out"), None);
        assert_eq!(exit_code_in("exit code 3"), None);
    }

    #[test]
    fn a_cargo_pass_is_the_sum_of_every_binary_and_needs_one_test() {
        let n = |t: &str| RunFacts::of(t).cargo_passed;
        assert_eq!(
            n("running 0 tests\n\ntest result: ok. 0 passed; 0 failed; 0 ignored\n"),
            0
        );
        assert_eq!(
            n("test result: ok. 0 passed; 0 failed; 1 ignored"),
            0,
            "only an ignored test"
        );
        assert_eq!(
            n("test result: ok. 40 passed; 0 failed\ntest result: ok. 0 passed; 0 failed"),
            40,
            "empty doc-tests after a real suite"
        );
        assert_eq!(
            n("test result: ok. 2 passed; 0 failed\ntest result: ok. 3 passed; 0 failed"),
            5
        );
        assert_eq!(n("no cargo output at all"), 0);
        assert!(!RunFacts::of("test result: ok. 4 passed; 0 failed").cargo_failed);
    }

    #[test]
    fn the_standing_line_is_silent_on_too_little_evidence() {
        let d = ReportData::compute(&Ledger::default(), None, 10, today_for_test());
        assert!(standing_line(&d).is_none());
    }

    fn today_for_test() -> NaiveDate {
        NaiveDate::from_ymd_opt(2026, 1, 1).unwrap()
    }

    #[test]
    fn claude_and_claude_code_are_one_agent_and_other_clients_are_not() {
        let claim = |id: &str, tags: &[&str]| -> Claim {
            serde_json::from_value(serde_json::json!({
                "id": id, "statement": "s", "created_at": "2024-01-01T00:00:00Z",
                "tags": tags, "kind": "binary",
                "forecasts": [{"at": "2024-01-01T00:00:00Z", "prob": 0.7}]
            }))
            .unwrap()
        };
        let ledger = Ledger {
            claims: vec![
                claim("a", &["who:claude", "kind:x"]),
                claim("b", &["who:claude-code"]),
                claim("c", &["who:claude", "who:claude-code"]),
                claim("d", &["who:cursor"]),
                claim("e", &["kind:x"]),
            ],
            ..Default::default()
        };
        let mine = agent_claims(&ledger);
        let ids: Vec<&str> = mine.claims.iter().map(|c| c.id.as_str()).collect();
        assert_eq!(ids, ["a", "b", "c"]);
        // One identity, spelled once, whichever name it arrived under.
        for c in &mine.claims {
            assert_eq!(c.tags.iter().filter(|t| t.starts_with("who:")).count(), 1);
            assert!(c.tags.contains(&"who:claude".to_string()));
        }
        assert!(ledger.claims[1]
            .tags
            .contains(&"who:claude-code".to_string()));
    }

    #[test]
    fn session_names_become_safe_filenames() {
        assert_eq!(sanitize("abc/../x"), "abc----x");
        assert!(!sanitize("a/b").contains('/'));
    }
}