recall 0.4.13

Sync Claude Code's auto memory across machines and cloud sessions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
//! `recall review run` and `recall review show` — checks what a memory
//! *claims* against what this checkout and its git history can see, and
//! says which claims still hold. See `docs/history/memory-truth.md`.
//!
//! **How loudly it may fail:** as quietly as `recall status`. A memory file
//! this cannot read, a directory that is not a git repository, a claim with
//! nothing here to check it against — none of that is an error. The review
//! offers evidence; it never refuses to run, and its exit code is always
//! [`exit::OK`] once it has run at all (`docs/history/memory-truth.md`'s
//! decision 4). The only non-zero exit is a genuine usage mistake, such as
//! naming a `[FILE]` that is not a memory file in any scope that is on.
//!
//! Layers 1 and 2: a candidate filter for dead artefact references, and
//! evidence from the checkout (`git ls-files`, `git log`, `git grep`, `git
//! tag`), from what this machine and its server say they are, from the
//! project's compose files and from a few environment variables. The last
//! four live in [`sources`], which says what they send and what they never
//! read; this file opens no connection of its own
//! (`this_module_never_touches_the_network`). `recall review apply`, in
//! [`apply`], makes one stale claim's suggested edit, and is the only
//! thing here that ever changes a note. [`reports`] shows the worker's
//! newest evaluation report beside the claims its findings cover.
//!
//! Layer 3, only with `--claude`, lives in [`claude`]: the local `claude`
//! CLI over what layers 1 and 2 left undecided, handed a fact sheet of
//! what they observed and held to citing it. It is the only incremental
//! layer: layers 1 and 2 are cheap enough to run over every claim on every
//! run (`docs/history/memory-truth.md`'s "Incremental" section), while
//! layer 3 asks again only about a file whose content changed, or one
//! whose earlier answer cited a fact no longer observed, unless `--all`.
//!
//! **Scope matters to what can be checked.** A path, a script name or a
//! version only means something against *this* project's checkout — a
//! claim in the global or machine scope is not about this repository, so
//! those checks come back `cant_tell` there, whatever the checkout shows.
//! A `~/` or absolute path (or a Windows drive path) is checked against
//! this machine regardless of scope, since that is what it always means.

use std::collections::{BTreeMap, HashSet};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};

use clap::Subcommand;
use recall_hooks::exit;
use serde::{Deserialize, Serialize};

use crate::project as proj;
use crate::ui;

mod apply;
mod claude;
mod reports;
mod sources;

/// `recall review …`.
#[derive(Subcommand)]
pub enum Cmd {
    /// Check which claims in memory still hold
    ///
    /// Extracts every checkable claim from memory, and checks it against
    /// what this checkout and its git history can see.
    #[command(verbatim_doc_comment)]
    Run {
        /// Only these files; every file in every scope that is on, when left out
        ///
        /// Relative to the memory directory, as recall status shows it.
        /// Naming a file that is not memory in an active scope is an error.
        #[arg(verbatim_doc_comment)]
        files: Vec<String>,
        /// With --claude, ask about every file again
        ///
        /// Not only those changed since claude was last asked. Layers 1 and 2
        /// check every file on every run regardless.
        #[arg(long, verbatim_doc_comment)]
        all: bool,
        /// Also ask the local claude CLI about undecided claims
        ///
        /// Layer 3: one call per file, about the claims layers 1 and 2 left
        /// undecided. Spends your Claude usage; no API key is read or needed.
        #[arg(long, verbatim_doc_comment)]
        claude: bool,
        /// With --claude, the most files one run asks about
        ///
        /// The rest are listed as skipped.
        #[arg(long, value_name = "N", default_value_t = claude::DEFAULT_MAX_CALLS, requires = "claude")]
        max_calls: u32,
        /// Also ask each host a note names for its discovery document
        ///
        /// GET /.well-known/recall, with no credential, of every host but
        /// this machine's server. Off by default: a note's text does not
        /// decide where this machine sends requests.
        #[arg(long, verbatim_doc_comment)]
        probe_hosts: bool,
        /// List every claim checked, not only what needs you
        ///
        /// Also what no check could decide, each rule with its anchors, and
        /// what claude read as no claim at all, each with its evidence.
        #[arg(long, verbatim_doc_comment)]
        details: bool,
        /// Machine-readable output, for scripts
        #[arg(long)]
        json: bool,
    },
    /// Show the last report again
    Show {
        /// List every claim checked, not only what needs you
        #[arg(long)]
        details: bool,
        /// Machine-readable output, for scripts
        #[arg(long)]
        json: bool,
    },
    /// Make a stale claim's suggested edit, and push it
    ///
    /// The edit rewrites the claim, in the local file, into a record of
    /// what changed.
    #[command(verbatim_doc_comment)]
    Apply {
        /// The claim, such as t3, as recall review show lists it
        claim: String,
        /// Apply without asking, for scripts
        #[arg(long, short)]
        yes: bool,
    },
}

/// Runs one `recall review` command.
pub async fn run(cmd: Cmd) -> anyhow::Result<i32> {
    match cmd {
        Cmd::Run {
            files,
            all,
            claude,
            max_calls,
            probe_hosts,
            details,
            json,
        } => {
            let layer3 = claude.then_some(max_calls);
            let output = Output::of(json, details);
            run_review(&files, all, layer3, probe_hosts, output).await
        }
        Cmd::Show { details, json } => show_last(Output::of(json, details)),
        Cmd::Apply { claim, yes } => apply::run(&claim, yes).await,
    }
}

// ---------------------------------------------------------------------------
// The report
// ---------------------------------------------------------------------------

/// What a claim is, decided before anything judges it.
///
/// See `docs/history/memory-truth.md`'s classification table. The heuristic
/// leans toward [`Class::Record`] on purpose: calling a record present
/// pushes toward deleting history, and calling a present claim a record
/// only misses a stale line. Checked in this order — a record heading or
/// verb outranks a `type: user`/`feedback` note, so a correction written
/// inside the owner's own feedback still reads as history, not as a rule
/// to verify and never flag.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Class {
    /// A present-tense statement of state. Can go stale.
    Present,
    /// A heading, change verb, negated anchor or dated correction records
    /// what used to be true. Never stale, whatever the evidence.
    Record,
    /// A claim in a `type: user` or `type: feedback` note: the owner's own
    /// instruction. Substance is never judged; each anchor gets its own
    /// verdict instead of the claim getting one.
    Rule,
    /// None of the above. Only layer 3 (`--claude`) can judge it.
    Unsure,
    /// A merge left an inline `[CONFLICT: ...]` marker here. Reported, not
    /// judged.
    Conflict,
}

/// What a layer decided about a claim or an anchor, with the evidence that
/// decided it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Verdict {
    /// Evidence contradicts it.
    Stale,
    /// Evidence confirms it: a value it states matches what is observed.
    /// That what it names exists is never enough, except for a rule's
    /// anchor, which is only ever checked for that.
    StillTrue,
    /// Nothing here can decide it, or it concerns another machine or scope.
    CantTell,
}

/// One thing read to decide an anchor's verdict.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Evidence {
    /// Where this came from: `repository`, `git`, `machine`, `server`,
    /// `environment`, `compose`, `probe`, or `claude` (layer 3's reading).
    pub source: String,
    /// What was found, in a sentence.
    pub detail: String,
    /// This one anchor's own verdict. For a `present` claim these are
    /// aggregated into [`Claim::verdict`] too; for a `rule` claim this is
    /// the only verdict there is — the design gives every anchor of a rule
    /// its own verdict rather than the claim as a whole one, since a rule's
    /// substance is never judged.
    pub verdict: Verdict,
    /// Whether layer 3 may cite this as a fact: true for whatever decided
    /// something or showed that what an anchor names exists, false for what
    /// decided nothing ("not found on this machine"). Layer 2 sets it on
    /// every run, and nothing reads it from a saved report, so it is never
    /// written out.
    #[serde(skip)]
    pub citable: bool,
}

/// One claim: a list item, a sentence, or a fenced block, with the line
/// range it occupies.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Claim {
    /// `t1`, `t2`, … — never `f<n>`, so a claim's id cannot collide with a
    /// worker finding's when the two are shown together (a later PR).
    /// Reassigned on every run, in file-then-line order, so a merge with a
    /// restricted run's stored state never leaves a gap or a duplicate.
    pub id: String,
    /// The file this claim is in, relative to the memory directory, exactly
    /// as it is on disk (`global/editor.md`, `machine/ram.md`, `topics/x.md`).
    pub file: String,
    /// The 1-based line range this claim occupies.
    pub lines: [u32; 2],
    /// What kind of claim this is.
    pub class: Class,
    /// The claim's own text, for display; wrapped lines are joined with a
    /// single space, matching how Markdown reads them.
    pub text: String,
    /// The claim's own verdict: present claims only, aggregated across
    /// their anchors. Absent for a record (never judged), an unsure claim
    /// (waits for layer 3), a conflict (reported, not judged), and a rule
    /// (judged per anchor — see each entry in `evidence` instead).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub verdict: Option<Verdict>,
    /// Which layer produced the verdict.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub layer: Option<u8>,
    /// What was read to decide it, one entry per anchor.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub evidence: Vec<Evidence>,
    /// For a `stale` claim layer 3 decided, the edit `recall review apply`
    /// would make: the claim rewritten as a record of what changed, in the
    /// lines it occupies, against the version of the file this run read.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub suggested_edit: Option<recall_wire::SuggestedEdit>,
    /// The findings of the worker's newest report that cover this claim's
    /// lines, when this machine can read reports: the review says whether a
    /// note is still true, the report whether it holds a secret, a
    /// duplicate, a dead link, a wrong scope or a contradiction.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub eval: Vec<reports::EvalFinding>,
}

/// A source this design names that was not consulted, and why.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct UnavailableSource {
    /// `repository`, `server`, `compose`, `probe`, `claude` or `evaluation`.
    pub source: String,
    /// Why it was not read this run.
    pub reason: String,
}

/// What this run actually read, and what it did not. See
/// `docs/history/memory-truth.md`'s Output section.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SourcesRead {
    /// The repository's `HEAD`, short form, when the project root is a git
    /// repository.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub repository_head: Option<String>,
    /// Whether that `HEAD` is detached rather than on a branch.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub repository_detached: bool,
    /// What the checkout is compared with: its branch's upstream, or, when
    /// `HEAD` is detached, the remote's default branch (`origin/HEAD`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub repository_upstream: Option<String>,
    /// How many commits `repository_upstream`, as last fetched, has that
    /// the checkout does not. Claims are checked against the checkout, so
    /// a checkout behind is one reason a verdict can be wrong.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub repository_behind: Option<u32>,
    /// The version the configured server's discovery document reports.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub server_version: Option<String>,
    /// The commit the configured server's `/health` reports.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub server_commit: Option<String>,
    /// The compose files read, relative to the repository root.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub compose_files: Vec<String>,
    /// The hosts `--probe-hosts` asked. Empty without it.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub probed: Vec<String>,
    /// Sources that could not be read this run, and why: the repository
    /// outside a git repository, the server when none is configured or it
    /// did not answer, the compose files when the checkout has none, and
    /// the hosts memory names when `--probe-hosts` was not given.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub unavailable: Vec<UnavailableSource>,
    /// What layer 3 did, when `--claude` asked for it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub claude: Option<ClaudeRun>,
    /// The worker's report whose findings are shown beside the claims: its
    /// newest finished one, when this machine can read reports.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub evaluation: Option<String>,
}

/// What one `--claude` run did.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ClaudeRun {
    /// How many times `claude` was called: one per file asked about.
    pub calls: u32,
    /// Files whose earlier answer still holds (unchanged, and every fact it
    /// cited still observed), so nothing was asked about them.
    pub reused: u32,
    /// Files with claims to decide that were not asked about, and why.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub skipped: Vec<SkippedFile>,
    /// Why `claude` could not answer at all, when it could not: not
    /// installed, or the CLI itself failing (a login, a usage limit). The
    /// rest of the files are then not asked.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub failure: Option<String>,
    /// The `claude` binary that was run: the first on `PATH`, resolved to
    /// a full path, so a failure says which one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub binary: Option<String>,
}

/// A file layer 3 did not ask about, and why.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SkippedFile {
    /// The file, relative to the memory directory.
    pub file: String,
    /// Why it was skipped.
    pub reason: String,
}

/// The `--json` shape. Stable from its first release, under
/// `docs/reference/releasing.md`'s Versioning rules: a later PR may add a
/// field, never remove or repurpose one of these.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Report {
    /// When this review ran, RFC 3339.
    pub reviewed_at: String,
    /// The sources this run read, and what it could not.
    pub evidence: SourcesRead,
    /// Every claim this review holds, in file then line order: this run's
    /// files, merged with whatever a prior run held for files this run did
    /// not touch (see [`run_review`]).
    pub claims: Vec<Claim>,
}

/// What `.recall-review.json` holds: per-machine, never pushed, beside
/// `.recall-state.json`. See `claude::Env::review_file`.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
struct SavedState {
    /// Each reviewed file's content hash, as of the last run that touched
    /// it, and layer 3's last answer about it.
    #[serde(default)]
    files: BTreeMap<String, FileState>,
    /// The last report, so `recall review show` can print it again without
    /// re-reading memory.
    #[serde(default)]
    report: Option<Report>,
}

/// One file's bookkeeping in [`SavedState`].
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
struct FileState {
    /// [`recall_wire::content_sha256`] of the content this review last read.
    content_sha256: String,
    /// Layer 3's answer, while it still holds.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    claude: Option<claude::Reviewed>,
}

fn load_state(path: &Path) -> SavedState {
    std::fs::read(path)
        .ok()
        .and_then(|bytes| serde_json::from_slice(&bytes).ok())
        .unwrap_or_default()
}

fn save_state(path: &Path, state: &SavedState) -> std::io::Result<()> {
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    let body = serde_json::to_vec_pretty(state).map_err(std::io::Error::other)?;
    std::fs::write(path, body)
}

// ---------------------------------------------------------------------------
// Running the review
// ---------------------------------------------------------------------------

fn now_rfc3339() -> String {
    time::OffsetDateTime::now_utc()
        .format(&time::format_description::well_known::Rfc3339)
        .unwrap_or_default()
}

fn join_relative(dir: &Path, rel: &str) -> PathBuf {
    let mut p = dir.to_path_buf();
    for part in rel.split('/').filter(|s| !s.is_empty()) {
        p.push(part);
    }
    p
}

/// Whether `rel` (relative to the memory directory) is a file the project
/// scope owns, rather than the global or machine scope.
fn is_project_scope(scopes: &[recall_hooks::Scope], rel: &str) -> bool {
    recall_hooks::scope::route(scopes, rel)
        .map(|(scope, _)| scope.prefix.is_none())
        .unwrap_or(true)
}

/// Runs layers 1 and 2 over every file in scope (or the files named), and
/// layer 3 when `layer3` holds `--max-calls`.
async fn run_review(
    file_args: &[String],
    all: bool,
    layer3: Option<u32>,
    probe_hosts: bool,
    output: Output,
) -> anyhow::Result<i32> {
    let here = proj::resolve();
    let cfg = here.config();
    let remote = proj::remote();
    let scopes = recall_hooks::scope::scopes(
        here.project_key(&cfg, &remote),
        cfg.global_key.clone(),
        cfg.machine_key.clone(),
    );
    let memory_dir = here.memory_dir();
    let review_file = here.review_file();

    let all_files: Vec<String> = recall_hooks::state::list_memory_files(&memory_dir)
        .unwrap_or_default()
        .into_iter()
        // `MEMORY.md` is the index, not a memory: the worker already checks
        // its links, and this design reviews claims, not link hygiene.
        .filter(|rel| rel != "MEMORY.md")
        // Only a file some active scope actually owns — this also drops a
        // miscased `Global/`-style directory, the same way `recall status`
        // never counts it as memory.
        .filter(|rel| recall_hooks::scope::route(&scopes, rel).is_some())
        .collect();

    let mut candidates = all_files.clone();
    if !file_args.is_empty() {
        let wanted: HashSet<&str> = file_args.iter().map(String::as_str).collect();
        let missing: Vec<&str> = wanted
            .iter()
            .copied()
            .filter(|f| !all_files.iter().any(|c| c == f))
            .collect();
        if !missing.is_empty() {
            let mut missing = missing;
            missing.sort_unstable();
            eprintln!(
                "recall review: not a memory file in any scope that is on: {}",
                missing.join(", ")
            );
            return Ok(exit::CONFIG);
        }
        candidates.retain(|f| wanted.contains(f.as_str()));
    }
    candidates.sort();

    let repo = Repo::at(proj::git_root());
    // Read once per run, not once per version anchor: the tag list does not
    // change while this command is running.
    let newest_tag = repo.newest_tag();

    // Extracted and classified first, judged after: which hosts
    // `--probe-hosts` asks depends on what the claims name.
    let mut extracted = Vec::new();
    let mut new_file_states = BTreeMap::new();
    let mut contents: BTreeMap<String, (String, bool)> = BTreeMap::new();
    for rel in &candidates {
        let is_project = is_project_scope(&scopes, rel);
        let path = join_relative(&memory_dir, rel);
        let Ok(content) = std::fs::read_to_string(&path) else {
            // Unreadable (removed mid-run, not UTF-8, a permissions race):
            // nothing to review here, and nothing worth failing the run
            // over — the next run sees it if it is still there.
            continue;
        };
        new_file_states.insert(
            rel.clone(),
            FileState {
                content_sha256: recall_wire::content_sha256(&content),
                claude: None,
            },
        );
        let note_type = front_matter_type(&content);
        for raw in extract_claims(&content) {
            let class = classify(&raw.text, raw.in_record_section, note_type.as_deref());
            extracted.push((rel.clone(), is_project, raw, class));
        }
        contents.insert(rel.clone(), (content, is_project));
    }

    let mut facts = sources::read(&here, &cfg, repo.root.as_deref()).await;
    let to_probe = sources::hosts_to_probe(
        extracted
            .iter()
            .map(|(_, _, raw, class)| (*class, raw.text.as_str())),
        &facts,
        probe_hosts,
    );
    facts.probes = sources::probe(&to_probe).await;

    let mut new_claims = Vec::new();
    for (rel, is_project, raw, class) in extracted {
        let (verdict, layer, evidence) =
            judge(class, &raw.text, &repo, is_project, &newest_tag, &facts);
        new_claims.push(Claim {
            id: String::new(),
            file: rel,
            lines: raw.lines,
            class,
            text: raw.text,
            verdict,
            layer,
            evidence,
            suggested_edit: None,
            eval: Vec::new(),
        });
    }

    let mut saved = load_state(&review_file);

    let layer3_run = layer_three(
        &mut new_claims,
        &mut new_file_states,
        &saved,
        &contents,
        Layer3Inputs {
            repo: &repo,
            newest_tag: &newest_tag,
            facts: &facts,
            all,
            max_calls: layer3,
            scopes: &scopes,
        },
    )
    .await;

    // Merge with whatever the last run held: a `[FILE]`-restricted run must
    // not make the other files' claims and hashes disappear from the
    // stored report, since `show` and any later run still need them.
    let processed: HashSet<&str> = candidates.iter().map(String::as_str).collect();
    let mut claims: Vec<Claim> = saved
        .report
        .as_ref()
        .map(|r| r.claims.clone())
        .unwrap_or_default()
        .into_iter()
        .filter(|c| !processed.contains(c.file.as_str()))
        .collect();
    claims.extend(new_claims);
    claims.sort_by(|a, b| a.file.cmp(&b.file).then(a.lines[0].cmp(&b.lines[0])));
    for (i, c) in claims.iter_mut().enumerate() {
        c.id = format!("t{}", i + 1);
    }
    for (rel, state) in new_file_states {
        saved.files.insert(rel, state);
    }

    // The worker's newest report, beside every claim this review holds,
    // asked only of a server that has just answered.
    let read = if facts.server.answered {
        reports::newest(&cfg).await
    } else {
        reports::Read::NoServer
    };
    for c in claims.iter_mut() {
        c.eval.clear();
    }
    if let reports::Read::Newest(id, findings) = &read {
        reports::beside(&mut claims, id, findings, |file| {
            recall_hooks::scope::route(&scopes, file).map(|(s, path)| (s.key.clone(), path))
        });
    }

    let mut unavailable = Vec::new();
    let mut missing = |source: &str, reason: String| {
        unavailable.push(UnavailableSource {
            source: source.to_string(),
            reason,
        })
    };
    if repo.root.is_none() {
        missing("repository", "this is not a git repository".to_string());
    }
    match (&facts.server.url, facts.server.answered) {
        (None, _) => missing(
            "server",
            "no server is configured on this machine".to_string(),
        ),
        (Some(url), false) => missing(
            "server",
            format!(
                "/health at {url} did not answer ({})",
                facts.server.error.as_deref().unwrap_or("no reason given")
            ),
        ),
        (Some(_), true) => {}
    }
    if facts.compose.is_none() {
        missing(
            "compose",
            "the checkout has no deploy/docker-compose*.yml that reads as YAML".to_string(),
        );
    }
    if !probe_hosts {
        let named = sources::hosts_to_probe(
            claims.iter().map(|c| (c.class, c.text.as_str())),
            &facts,
            true,
        )
        .len();
        if named > 0 {
            missing(
                "probe",
                format!(
                    "{named} host(s) named in memory were not asked anything; --probe-hosts asks \
                     them"
                ),
            );
        }
    }
    if let reports::Read::Unreadable(why) = &read {
        missing("evaluation", why.clone());
    }
    if layer3.is_none() && layer3_run.waiting > 0 {
        missing(
            "claude",
            format!(
                "{} file(s) hold claims only layer 3 can decide; --claude asks this machine's \
                 claude CLI about them",
                layer3_run.waiting
            ),
        );
    }
    let lag = repo.lag();
    let report = Report {
        reviewed_at: now_rfc3339(),
        evidence: SourcesRead {
            repository_head: repo.head_short(),
            repository_detached: lag.detached,
            repository_upstream: lag.upstream,
            repository_behind: lag.behind,
            server_version: facts.server.version.clone(),
            server_commit: facts.server.commit.clone(),
            compose_files: facts
                .compose
                .as_ref()
                .map(|c| c.files.clone())
                .unwrap_or_default(),
            probed: facts.probes.keys().cloned().collect(),
            unavailable,
            claude: layer3.map(|_| layer3_run.run),
            evaluation: match read {
                reports::Read::Newest(id, _) => Some(id),
                _ => None,
            },
        },
        claims,
    };

    // Saved before it is printed, and a failed save is only a warning: the
    // report the owner is looking at never depends on the disk write
    // (decision 4: the exit code stays 0 whenever the review ran), and a
    // reader that stops early (`recall review run | head`) ends the process
    // at the first write to a closed pipe, which must not cost `recall
    // review show` the report.
    saved.report = Some(report);
    if let Err(e) = save_state(&review_file, &saved) {
        eprintln!(
            "recall review: this report was not saved ({e}); recall review show will not have \
             it until the next run succeeds"
        );
    }
    let report = saved.report.as_ref().expect("just set");
    output.print(report)?;
    Ok(exit::OK)
}

/// How a report is printed: `--json`, or text with or without `--details`.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Output {
    Json,
    Text { details: bool },
}

impl Output {
    fn of(json: bool, details: bool) -> Self {
        if json {
            Output::Json
        } else {
            Output::Text { details }
        }
    }

    fn print(self, report: &Report) -> anyhow::Result<()> {
        match self {
            Output::Json => println!("{}", serde_json::to_string_pretty(report)?),
            Output::Text { details } => print_text(report, details),
        }
        Ok(())
    }
}

/// What layer 3 reads besides the claims themselves.
struct Layer3Inputs<'a> {
    repo: &'a Repo,
    newest_tag: &'a Option<(u64, u64, u64, String)>,
    facts: &'a sources::Facts,
    /// `--all`: ask about every file again.
    all: bool,
    /// `--max-calls`, when `--claude` asked for layer 3 at all.
    max_calls: Option<u32>,
    /// The scopes that are on, to say which scope's file an edit is to.
    scopes: &'a [recall_hooks::Scope],
}

/// What [`layer_three`] did.
struct Layer3Done {
    /// For the report, when `--claude` asked.
    run: ClaudeRun,
    /// Files with claims only layer 3 can decide and no answer that still
    /// holds: what `--claude` would ask about.
    waiting: usize,
}

/// A file layer 3 still has to ask about.
struct ToAsk<'a> {
    rel: &'a String,
    /// Its claims to decide, as the prompt numbers them.
    asked: Vec<claude::Asked>,
    /// Its fact sheet: what can be cited, and context that cannot.
    facts: Vec<String>,
    context: Vec<String>,
    /// An earlier answer that still holds (under `--all`, or partial), to
    /// show if the file is not asked about after all.
    fallback: Option<claude::Reviewed>,
    /// An earlier answer about this same content that no longer holds
    /// (a fact it cited was not observed this run): not shown, but kept,
    /// so a run that cannot ask never throws a paid answer away.
    kept: Option<claude::Reviewed>,
}

/// Whether layers 1 and 2 left `c` for layer 3: an `unsure` claim, or a
/// `present` one they could not decide.
fn undecided(c: &Claim) -> bool {
    c.class == Class::Unsure
        || (c.class == Class::Present && matches!(c.verdict, None | Some(Verdict::CantTell)))
}

/// Layer 3's fact sheet for the file `rel`: what this machine and its
/// checkout are, then everything layer 2 observed about this file's claims,
/// including each anchor of a claim it left `unsure`. An observation that
/// decided something can be cited; one that decided nothing ("not found on
/// this machine", "only --probe-hosts asks") is context, so `claude` cannot
/// turn what layer 2 deliberately left `cant_tell` into a verdict.
fn fact_sheet(
    (global, global_context): (&[String], &[String]),
    claims: &[Claim],
    rel: &str,
    inputs: &Layer3Inputs<'_>,
    is_project: bool,
) -> (Vec<String>, Vec<String>) {
    let mut facts = global.to_vec();
    let mut context = global_context.to_vec();
    for c in claims.iter().filter(|c| c.file == rel) {
        if c.class == Class::Unsure {
            for a in anchors(&c.text) {
                let o = evidence_for(
                    &a,
                    inputs.repo,
                    is_project,
                    inputs.newest_tag,
                    &c.text,
                    inputs.facts,
                );
                match o.signal {
                    Signal::Unknown => context.push(o.detail),
                    _ => facts.push(o.detail),
                }
            }
        } else {
            for e in c.evidence.iter().filter(|e| e.source != claude::SOURCE) {
                if e.citable {
                    facts.push(e.detail.clone());
                } else {
                    context.push(e.detail.clone());
                }
            }
        }
    }
    let facts = claude::dedup(facts);
    let context = claude::dedup(context)
        .into_iter()
        .filter(|c| !facts.contains(c))
        .collect();
    (facts, context)
}

/// A file as an edit names it: its content, and its scope's key and path.
struct EditBase<'a> {
    content: &'a str,
    /// The scope's key and the path within it; [`None`] when no scope that
    /// is on owns the file, and no edit can be made to it.
    target: Option<(String, String)>,
}

impl<'a> EditBase<'a> {
    fn of(rel: &str, content: &'a str, scopes: &[recall_hooks::Scope]) -> Self {
        EditBase {
            content,
            target: recall_hooks::scope::route(scopes, rel)
                .map(|(scope, path)| (scope.key.clone(), path)),
        }
    }
}

/// Applies layer 3's answers about `rel` to the claims they were given for,
/// each held to the rules again first, with the edit a stale claim's
/// rewrite comes to.
fn apply_decided(
    claims: &mut [Claim],
    rel: &str,
    decided: &[claude::Decided],
    base: &EditBase<'_>,
) {
    for d in decided.iter().map(claude::Decided::checked) {
        if let Some(c) = claims
            .iter_mut()
            .find(|c| c.file == rel && c.lines == d.lines && c.text == d.text && undecided(c))
        {
            c.class = d.class;
            c.verdict = d.verdict;
            c.layer = Some(3);
            c.evidence.push(d.evidence);
            c.suggested_edit = match (&d.rewrite, &base.target) {
                (Some(rewrite), Some((key, path))) => {
                    apply::build(base.content, c.lines, &c.text, (key, path), rewrite).ok()
                }
                _ => None,
            };
        }
    }
}

/// Layer 3 over the files this run read: an earlier answer is reused while
/// it holds, and, only when `--claude` asked, `claude` is called about each
/// file that still has claims to decide, up to `--max-calls`, the files
/// never asked about first and then those asked about longest ago.
async fn layer_three(
    claims: &mut [Claim],
    states: &mut BTreeMap<String, FileState>,
    saved: &SavedState,
    contents: &BTreeMap<String, (String, bool)>,
    inputs: Layer3Inputs<'_>,
) -> Layer3Done {
    let mut global = Vec::new();
    if let Some(head) = inputs.repo.head_short() {
        global.push(format!("The project's repository is at commit {head}"));
    }
    if let Some((_, _, _, tag)) = inputs.newest_tag {
        global.push(format!(
            "The newest release tag in the project's repository is {tag}"
        ));
    }
    let (server_facts, global_context) = inputs.facts.sheet();
    global.extend(server_facts);

    let asking = inputs.max_calls.is_some();
    let mut run = ClaudeRun::default();
    let mut to_ask: Vec<ToAsk<'_>> = Vec::new();
    for (rel, (_, is_project)) in contents {
        let asked: Vec<claude::Asked> = claims
            .iter()
            .filter(|c| &c.file == rel && undecided(c))
            .map(|c| claude::Asked {
                lines: c.lines,
                text: c.text.clone(),
                class: c.class,
            })
            .collect();
        if asked.is_empty() {
            continue;
        }
        let (facts, context) = fact_sheet(
            (&global, &global_context),
            claims,
            rel,
            &inputs,
            *is_project,
        );
        let sha = states[rel].content_sha256.clone();
        let stored = saved
            .files
            .get(rel)
            .and_then(|f| f.claude.clone())
            .filter(|r| r.content_sha256 == sha);
        let (fallback, kept) = match stored {
            Some(r) if r.holds(&sha, &facts) => {
                if r.complete && !(inputs.all && asking) {
                    apply_decided(
                        claims,
                        rel,
                        &r.decided,
                        &EditBase::of(rel, &contents[rel].0, inputs.scopes),
                    );
                    states.get_mut(rel).expect("read this run").claude = Some(r);
                    run.reused += 1;
                    continue;
                }
                (Some(r), None)
            }
            other => (None, other),
        };
        to_ask.push(ToAsk {
            rel,
            asked,
            facts,
            context,
            fallback,
            kept,
        });
    }
    let waiting = to_ask.len();
    // Never asked first, then asked longest ago: `--max-calls` reaches
    // every file in turn rather than the same first few by name.
    to_ask.sort_by_cached_key(|t| {
        t.fallback
            .as_ref()
            .or(t.kept.as_ref())
            .map(|r| r.reviewed_at.clone())
    });

    let mut cannot_run: Option<String> = None;
    let merger = claude::merger();
    // One local check, which costs nothing, before the first call: a
    // machine without claude, or one that is definitely not logged in, is
    // said once, in words that say what to do, not once per file as an
    // exit code.
    if asking && !to_ask.is_empty() {
        let status = merger.check_status().await;
        if !status.available {
            cannot_run = Some(format!(
                "claude is not installed here ({}); install Claude Code, or leave out --claude",
                status.error
            ));
        } else if !status.logged_in && status.error.is_empty() {
            cannot_run = Some(
                "claude is not logged in on this machine; run claude and log in, then try again"
                    .to_string(),
            );
        }
        if cannot_run.is_some() {
            run.failure = cannot_run.clone();
            run.binary = claude::binary();
        }
    }
    let redactor = asking.then(|| {
        // Every file this run read teaches the redactor its secrets, so one
        // quoted in another note is masked too.
        let files: Vec<recall_wire::EvaluateFile> = contents
            .iter()
            .map(|(rel, (content, _))| recall_wire::EvaluateFile {
                file_path: rel.clone(),
                content: content.clone(),
                ..Default::default()
            })
            .collect();
        recall_worker::Redactor::new(&files)
    });

    for t in to_ask {
        let rel = t.rel;
        let answer = match (inputs.max_calls, &redactor) {
            (Some(max_calls), Some(redactor)) => {
                let (content, is_project) = &contents[rel];
                if let Some(why) = &cannot_run {
                    Err(why.clone())
                } else if run.calls >= max_calls {
                    Err(format!(
                        "--max-calls {max_calls} reached; a later run asks about it"
                    ))
                } else {
                    let scope = if *is_project {
                        "project scope: about this repository"
                    } else {
                        "global or machine scope: not about this repository"
                    };
                    let prompt = claude::prompt(
                        rel,
                        scope,
                        content,
                        (&t.facts, &t.context),
                        &t.asked,
                        redactor,
                    );
                    if prompt.len() > claude::MAX_PROMPT_BYTES {
                        Err(format!(
                            "its prompt is {} bytes, more than one call is handed ({})",
                            prompt.len(),
                            claude::MAX_PROMPT_BYTES
                        ))
                    } else {
                        eprintln!(
                            "recall review: asking claude about {}",
                            sanitize_for_terminal(rel)
                        );
                        match merger.ask(claude::SYSTEM_PROMPT, &prompt).await {
                            Ok(text) => {
                                run.calls += 1;
                                claude::decide(&text, &t.asked, &t.facts)
                                    .map(|decided| {
                                        decided
                                            .into_iter()
                                            .map(|mut d| {
                                                // A claim holding a secret is
                                                // never rewritten: claude saw
                                                // it masked, and its rewrite
                                                // would write the mask in.
                                                if redactor.text(&d.text) != d.text {
                                                    d.rewrite = None;
                                                }
                                                d
                                            })
                                            .collect::<Vec<_>>()
                                    })
                                    .ok_or_else(|| {
                                        "claude's answer was not the JSON layer 3 asks for"
                                            .to_string()
                                    })
                            }
                            Err(recall_worker::merge::Error::Unavailable(why)) => {
                                let why = format!("claude cannot run on this machine: {why}");
                                run.failure = Some(why.clone());
                                run.binary = claude::binary();
                                cannot_run = Some(why.clone());
                                Err(why)
                            }
                            Err(e) => {
                                run.calls += 1;
                                // A failure of the CLI itself (a login, a
                                // usage limit, a flag it does not know)
                                // fails every file the same way: the rest
                                // are not asked, and say why.
                                let why = e.to_string();
                                run.failure = Some(why.clone());
                                run.binary = claude::binary();
                                cannot_run =
                                    Some(format!("not asked, after claude failed on {rel}"));
                                Err(why)
                            }
                        }
                    }
                }
            }
            // Not asked to ask: whatever still holds is shown, and nothing
            // is listed as skipped.
            _ => Err(String::new()),
        };
        let state = states.get_mut(rel).expect("read this run");
        match answer {
            Ok(decided) => {
                apply_decided(
                    claims,
                    rel,
                    &decided,
                    &EditBase::of(rel, &contents[rel].0, inputs.scopes),
                );
                state.claude = Some(claude::Reviewed {
                    content_sha256: state.content_sha256.clone(),
                    complete: decided.len() == t.asked.len(),
                    decided,
                    reviewed_at: now_rfc3339(),
                });
            }
            Err(reason) => {
                if !reason.is_empty() {
                    run.skipped.push(SkippedFile {
                        file: rel.clone(),
                        reason,
                    });
                }
                if let Some(r) = t.fallback {
                    apply_decided(
                        claims,
                        rel,
                        &r.decided,
                        &EditBase::of(rel, &contents[rel].0, inputs.scopes),
                    );
                    state.claude = Some(r);
                } else {
                    state.claude = t.kept;
                }
            }
        }
    }
    Layer3Done { run, waiting }
}

fn show_last(output: Output) -> anyhow::Result<i32> {
    let here = proj::resolve();
    let saved = load_state(&here.review_file());
    let Some(report) = saved.report else {
        // Valid JSON either way: a bare `null` is a complete JSON document,
        // and a script that reads `recall review show --json` before any
        // run has happened sees exactly that rather than an empty string or
        // an error.
        if output == Output::Json {
            println!("null");
        } else {
            println!("No review yet. recall review run makes one.");
        }
        return Ok(exit::OK);
    };
    output.print(&report)?;
    Ok(exit::OK)
}

/// Layer 2, for a `present` or `rule` claim with anchors; everything else
/// gets no verdict at all in this PR (see [`Class`]'s doc). A `present`
/// claim's anchors are aggregated into one verdict; a `rule`'s are not —
/// each [`Evidence`] entry carries its own.
fn judge(
    class: Class,
    text: &str,
    repo: &Repo,
    is_project: bool,
    newest_tag: &Option<(u64, u64, u64, String)>,
    facts: &sources::Facts,
) -> (Option<Verdict>, Option<u8>, Vec<Evidence>) {
    if !matches!(class, Class::Present | Class::Rule) {
        // Layer 1's guard: a candidate in a record is dropped, not
        // verdicted, whatever it would otherwise look like. An unsure claim
        // waits for layer 3. A conflict is reported, not judged.
        return (None, None, Vec::new());
    }
    let found = anchors(text);
    if found.is_empty() {
        return (None, None, Vec::new());
    }
    let observed: Vec<Observed> = found
        .iter()
        .map(|a| evidence_for(a, repo, is_project, newest_tag, text, facts))
        .collect();
    let evidence: Vec<Evidence> = observed
        .iter()
        .map(|o| Evidence {
            source: o.source.clone(),
            detail: o.detail.clone(),
            verdict: verdict_of_signal(o.signal, class),
            citable: o.signal != Signal::Unknown,
        })
        .collect();
    let verdict = match class {
        Class::Present => verdict_from(&observed),
        // A rule's substance is never judged as one claim; each anchor's
        // own verdict is already in `evidence` above.
        _ => None,
    };
    (verdict, Some(2), evidence)
}

// ---------------------------------------------------------------------------
// Claim extraction
// ---------------------------------------------------------------------------

/// One claim as extracted, before classification.
struct RawClaim {
    lines: [u32; 2],
    text: String,
    /// Whether the nearest heading above it reads like History, Previously
    /// or Correction — or is nested under one, at a deeper heading level.
    in_record_section: bool,
}

/// The line index just after the closing `---` of YAML front matter, or `0`
/// when the file has none.
fn front_matter_end(lines: &[&str]) -> usize {
    if lines.first().map(|l| l.trim()) != Some("---") {
        return 0;
    }
    for (i, line) in lines.iter().enumerate().skip(1) {
        if line.trim() == "---" {
            return i + 1;
        }
    }
    0
}

/// The front matter's `type:` value, if the file has front matter and a
/// `type:` line in it.
fn front_matter_type(content: &str) -> Option<String> {
    let lines: Vec<&str> = content.lines().collect();
    let end = front_matter_end(&lines);
    if end == 0 {
        return None;
    }
    for line in &lines[..end] {
        if let Some(value) = line.trim().strip_prefix("type:") {
            return Some(value.trim().trim_matches(['"', '\'']).to_string());
        }
    }
    None
}

fn is_list_marker(t: &str) -> bool {
    if t.starts_with("- ") || t.starts_with("* ") || t.starts_with("+ ") {
        return true;
    }
    let digits: String = t.chars().take_while(char::is_ascii_digit).collect();
    if digits.is_empty() {
        return false;
    }
    let rest = &t[digits.len()..];
    rest.starts_with(". ") || rest.starts_with(") ")
}

fn is_block_boundary(t: &str) -> bool {
    t.is_empty() || t.starts_with('#') || t.starts_with("```") || t.starts_with("~~~")
}

/// Whether a heading's text reads like a section of history rather than
/// current state.
fn is_history_heading(heading: &str) -> bool {
    let lower = heading.to_ascii_lowercase();
    ["history", "previously", "correction", "corrections"]
        .iter()
        .any(|w| lower.contains(w))
}

/// A heading's level: how many leading `#` it has.
fn heading_level(trimmed: &str) -> usize {
    trimmed.chars().take_while(|&c| c == '#').count()
}

/// Splits a paragraph's lines into sentence-sized claims, each with the line
/// range it spans. Wrapped lines are joined with a single space, matching
/// how Markdown itself reads a soft-wrapped paragraph.
fn split_sentences(lines: &[&str], first_line: u32, in_record_section: bool) -> Vec<RawClaim> {
    let mut joined = String::new();
    let mut line_of: Vec<u32> = Vec::new();
    for (idx, l) in lines.iter().enumerate() {
        if idx > 0 {
            joined.push(' ');
            line_of.push(first_line + idx as u32);
        }
        for ch in l.chars() {
            joined.push(ch);
            line_of.push(first_line + idx as u32);
        }
    }
    let chars: Vec<char> = joined.chars().collect();
    let mut out = Vec::new();
    let mut start = 0usize;
    let mut i = 0usize;
    while i < chars.len() {
        let c = chars[i];
        let at_boundary =
            (c == '.' || c == '!' || c == '?') && (i + 1 == chars.len() || chars[i + 1] == ' ');
        if at_boundary {
            push_sentence(&chars, &line_of, start, i, in_record_section, &mut out);
            start = (i + 2).min(chars.len());
            i = start;
            continue;
        }
        i += 1;
    }
    if start < chars.len() {
        push_sentence(
            &chars,
            &line_of,
            start,
            chars.len() - 1,
            in_record_section,
            &mut out,
        );
    }
    out
}

fn push_sentence(
    chars: &[char],
    line_of: &[u32],
    start: usize,
    end: usize,
    in_record_section: bool,
    out: &mut Vec<RawClaim>,
) {
    if start > end || start >= chars.len() {
        return;
    }
    let end = end.min(chars.len() - 1);
    let text: String = chars[start..=end]
        .iter()
        .collect::<String>()
        .trim()
        .to_string();
    if text.is_empty() {
        return;
    }
    let l1 = line_of[start];
    let l2 = line_of[end];
    out.push(RawClaim {
        lines: [l1, l2],
        text,
        in_record_section,
    });
}

/// Extracts every claim from a memory file's body: one per list item, one
/// per sentence of a paragraph, one per fenced block. Front matter is
/// skipped.
fn extract_claims(content: &str) -> Vec<RawClaim> {
    let lines: Vec<&str> = content.lines().collect();
    let mut out = Vec::new();
    let mut i = front_matter_end(&lines);
    let mut in_record_section = false;
    // The level of the History-like heading currently in force, so a
    // nested `###` under a `## History` stays part of it, and a sibling
    // `##` heading correctly ends it.
    let mut record_heading_level: Option<usize> = None;
    while i < lines.len() {
        let raw = lines[i];
        let trimmed = raw.trim();
        if trimmed.is_empty() {
            i += 1;
            continue;
        }
        if trimmed.starts_with('#') {
            let level = heading_level(trimmed);
            let heading = trimmed.trim_start_matches('#').trim();
            if is_history_heading(heading) {
                in_record_section = true;
                record_heading_level = Some(level);
            } else if record_heading_level.is_some_and(|rlevel| level > rlevel) {
                // A subheading nested under History — still history.
                in_record_section = true;
            } else {
                in_record_section = false;
                record_heading_level = None;
            }
            i += 1;
            continue;
        }
        if trimmed.starts_with("```") || trimmed.starts_with("~~~") {
            let fence = &trimmed[..3];
            let open = i;
            let mut close = i;
            let mut j = i + 1;
            while j < lines.len() {
                if lines[j].trim_start().starts_with(fence) {
                    close = j;
                    break;
                }
                close = j;
                j += 1;
            }
            let text = lines[open..=close].join("\n");
            out.push(RawClaim {
                lines: [open as u32 + 1, close as u32 + 1],
                text,
                in_record_section,
            });
            i = close + 1;
            continue;
        }
        if is_list_marker(trimmed) {
            let open = i;
            let mut close = i;
            let mut j = i + 1;
            while j < lines.len() {
                let t = lines[j].trim();
                if is_block_boundary(t) || is_list_marker(t) {
                    break;
                }
                if lines[j].starts_with(' ') || lines[j].starts_with('\t') {
                    close = j;
                    j += 1;
                    continue;
                }
                break;
            }
            let joined = lines[open..=close]
                .join(" ")
                .split_whitespace()
                .collect::<Vec<_>>()
                .join(" ");
            let text = strip_leading_marker(&joined).to_string();
            out.push(RawClaim {
                lines: [open as u32 + 1, close as u32 + 1],
                text,
                in_record_section,
            });
            i = close + 1;
            continue;
        }
        // A paragraph: every consecutive non-blank, non-list, non-heading,
        // non-fence line.
        let open = i;
        let mut close = i;
        let mut j = i + 1;
        while j < lines.len() {
            let t = lines[j].trim();
            if is_block_boundary(t) || is_list_marker(t) {
                break;
            }
            close = j;
            j += 1;
        }
        out.extend(split_sentences(
            &lines[open..=close],
            open as u32 + 1,
            in_record_section,
        ));
        i = close + 1;
    }
    out
}

// ---------------------------------------------------------------------------
// Classification
// ---------------------------------------------------------------------------

const RECORD_MARKERS: &[&str] = &[
    "moved",
    "renamed",
    "replaced",
    "deleted",
    "retired",
    "no longer",
    "used to",
    "until ",
    "formerly",
    "was at",
    "is now",
    "since 0.",
    "since v",
];

const PRESENT_MARKERS: &[&str] = &[
    "is at",
    "is live",
    "lives in",
    "runs on",
    "deployed via",
    "is deployed",
    "is the sync server",
    "is currently",
    "currently uses",
    "is hosted",
];

fn looks_like_record(text: &str) -> bool {
    let lower = text.to_ascii_lowercase();
    if lower.contains("not `") || lower.contains("not \"") {
        return true;
    }
    RECORD_MARKERS.iter().any(|m| lower.contains(m))
}

fn strip_leading_marker(text: &str) -> &str {
    let t = text.trim_start();
    for prefix in ["- ", "* ", "+ "] {
        if let Some(rest) = t.strip_prefix(prefix) {
            return rest.trim_start();
        }
    }
    let digits: String = t.chars().take_while(char::is_ascii_digit).collect();
    if !digits.is_empty() {
        let rest = &t[digits.len()..];
        if let Some(after) = rest.strip_prefix(". ").or_else(|| rest.strip_prefix(") ")) {
            return after.trim_start();
        }
    }
    t
}

fn looks_like_present(text: &str) -> bool {
    let lower = text.to_ascii_lowercase();
    if PRESENT_MARKERS.iter().any(|m| lower.contains(m)) {
        return true;
    }
    let body = strip_leading_marker(text);
    if body.starts_with("Run `") || body.starts_with("run `") {
        return true;
    }
    // A line that is nothing but `NAME=value` states what a variable is
    // set to now: the design's own worked example has one
    // (`CLAUDE_CODE_REMOTE_MEMORY_DIR=/home/user/.claude`).
    let bare = body.trim().trim_end_matches('.').trim_matches('`');
    bare.split_once('=')
        .is_some_and(|(name, value)| is_envvarish(name) && !value.is_empty())
        && !bare.contains(char::is_whitespace)
}

/// Classifies one claim, given the note's own front-matter `type:` (if any)
/// and whether it sits under a history-like heading.
///
/// Order is load-bearing: a conflict marker wins outright; a record signal
/// (a heading, a change verb, a negated anchor) is checked *before* the
/// note's own `type:`, so a correction written inside a `type: feedback`
/// note — "not `lib.sh`, it was deleted" — reads as history and never gets
/// a stale verdict, rather than being treated as a rule whose anchors get
/// checked as if they were still being asserted.
fn classify(text: &str, in_record_section: bool, note_type: Option<&str>) -> Class {
    if text.contains("[CONFLICT") {
        return Class::Conflict;
    }
    if in_record_section || looks_like_record(text) {
        return Class::Record;
    }
    if matches!(note_type, Some("user") | Some("feedback")) {
        return Class::Rule;
    }
    if looks_like_present(text) {
        return Class::Present;
    }
    Class::Unsure
}

// ---------------------------------------------------------------------------
// Anchors
// ---------------------------------------------------------------------------

/// What kind of thing an anchor names, which decides how layer 2 checks it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum AnchorKind {
    /// A repository path, or an absolute/`~/`/Windows-drive path on this
    /// machine.
    Path,
    /// A dotted hostname or a URL. Not checked until a later PR adds the
    /// server and discovery sources.
    Hostname,
    /// An `UPPER_SNAKE` variable, with or without `=value`. Not checked
    /// until a later PR adds the environment source.
    EnvVar,
    /// A SemVer version, checked against the newest release tag.
    SemVer,
    /// A `recall` subcommand or flag, or any other inline code whose
    /// referent might be a name in the tracked tree (`git grep`, excluding
    /// documentation).
    Code,
}

struct Anchor {
    kind: AnchorKind,
    value: String,
}

const KNOWN_EXTENSIONS: &[&str] = &[
    "sh", "bash", "zsh", "md", "rs", "py", "js", "ts", "json", "yml", "yaml", "toml", "ps1", "sql",
    "txt", "log", "service", "conf", "env", "lock", "ini", "cfg", "html", "css", "rb", "go",
];

fn has_file_extension(tok: &str) -> bool {
    tok.rfind('.')
        .map(|pos| &tok[pos + 1..])
        .is_some_and(|ext| {
            !ext.is_empty() && KNOWN_EXTENSIONS.contains(&ext.to_ascii_lowercase().as_str())
        })
}

/// A handful of `word/word` idioms and `number/unit` fractions that are not
/// paths, so `and/or` and `10/min` are not flagged as anchors just for
/// containing a slash.
fn looks_like_a_real_path_segment(tok: &str) -> bool {
    const NOT_PATHS: &[&str] = &[
        "and/or",
        "his/her",
        "he/she",
        "yes/no",
        "on/off",
        "true/false",
        "either/or",
        "pass/fail",
    ];
    if NOT_PATHS.contains(&tok.to_ascii_lowercase().as_str()) {
        return false;
    }
    if let Some((a, b)) = tok.split_once('/') {
        let numeric = |s: &str| !s.is_empty() && s.chars().all(|c| c.is_ascii_digit());
        if numeric(a) || numeric(b) {
            return false;
        }
    }
    true
}

/// A Windows absolute path: a drive letter, a colon, then a separator
/// (`C:\Users\x` or `C:/Users/x`).
fn is_windows_path(tok: &str) -> bool {
    let b = tok.as_bytes();
    b.len() >= 3 && b[0].is_ascii_alphabetic() && b[1] == b':' && (b[2] == b'\\' || b[2] == b'/')
}

/// A path meaningful only on this machine: absolute, `~/`, or a Windows
/// drive path — never a repository path, whatever the checkout holds.
fn is_machine_absolute(value: &str) -> bool {
    value.starts_with('/') || value.starts_with("~/") || is_windows_path(value)
}

fn is_pathish(tok: &str) -> bool {
    // "`a.yml` / `b.yml`": a slash between two names is punctuation, and
    // the root directory is never what a note means by it.
    if tok.chars().all(|c| c == '/') {
        return false;
    }
    tok.starts_with('/')
        || tok.starts_with("~/")
        || tok.starts_with("./")
        || tok.starts_with("../")
        || is_windows_path(tok)
        || (tok.contains('/') && !tok.contains("://") && looks_like_a_real_path_segment(tok))
        || has_file_extension(tok)
}

fn is_semverish(tok: &str) -> bool {
    let t = tok.strip_prefix('v').unwrap_or(tok);
    let parts: Vec<&str> = t.splitn(4, '.').collect();
    parts.len() >= 3
        && parts[..3]
            .iter()
            .all(|p| !p.is_empty() && p.chars().all(|c| c.is_ascii_digit()))
}

fn is_envvarish(tok: &str) -> bool {
    let name = tok.split('=').next().unwrap_or(tok);
    name.len() >= 3
        && name.contains('_')
        && name.chars().next().is_some_and(|c| c.is_ascii_uppercase())
        && name
            .chars()
            .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_')
}

fn is_hostish(tok: &str) -> bool {
    if tok.starts_with("http://") || tok.starts_with("https://") {
        return true;
    }
    if tok.contains("://") {
        return false;
    }
    let t = tok.trim_end_matches('/');
    let parts: Vec<&str> = t.split('.').collect();
    parts.len() >= 2
        && parts
            .iter()
            .all(|p| !p.is_empty() && p.chars().all(|c| c.is_ascii_alphanumeric() || c == '-'))
        && parts
            .last()
            .is_some_and(|tld| tld.len() >= 2 && tld.chars().all(|c| c.is_ascii_alphabetic()))
}

/// Classifies one token (the inside of a backtick span when `in_code`, or a
/// bare word otherwise) as an anchor, if it is one at all. Outside code,
/// only the shapes explicitly named by the design carry meaning; a bare
/// English word is not an anchor just for being a word.
fn classify_anchor(tok: &str, in_code: bool) -> Option<Anchor> {
    let kind = if is_envvarish(tok) {
        AnchorKind::EnvVar
    } else if is_semverish(tok) {
        AnchorKind::SemVer
    } else if is_pathish(tok) {
        AnchorKind::Path
    } else if is_hostish(tok) {
        AnchorKind::Hostname
    } else if in_code || tok.starts_with("--") {
        // Inline code of no more specific shape (a script name, a crate, a
        // recall subcommand or flag) is still checkable: layer 2 asks
        // whether it is still referenced anywhere in the tracked tree,
        // outside documentation.
        AnchorKind::Code
    } else {
        return None;
    };
    Some(Anchor {
        kind,
        value: tok.to_string(),
    })
}

fn trim_token(tok: &str) -> &str {
    let tok = tok.trim_matches(|c: char| {
        !(c.is_ascii_alphanumeric() || matches!(c, '/' | '.' | '~' | '_' | '-' | '='))
    });
    tok.strip_suffix('.').unwrap_or(tok)
}

/// Every anchor a claim's text carries: backtick-delimited spans, always;
/// bare words outside them, only when they carry a recognisable shape.
/// De-duplicated by kind and value, so a claim naming the same anchor twice
/// gets one piece of evidence, not two identical ones.
fn anchors(text: &str) -> Vec<Anchor> {
    let mut out = Vec::new();
    let mut rest = text;
    let mut plain = String::new();
    while let Some(start) = rest.find('`') {
        plain.push_str(&rest[..start]);
        plain.push(' ');
        let after = &rest[start + 1..];
        let Some(end) = after.find('`') else {
            plain.push_str(after);
            rest = "";
            break;
        };
        let inner = after[..end].trim();
        if !inner.is_empty() {
            if inner.contains(' ') {
                if inner.starts_with("recall ") {
                    out.push(Anchor {
                        kind: AnchorKind::Code,
                        value: inner.to_string(),
                    });
                }
            } else if let Some(a) = classify_anchor(inner, true) {
                out.push(a);
            }
        }
        rest = &after[end + 1..];
    }
    plain.push_str(rest);
    for tok in plain.split_whitespace() {
        let tok = trim_token(tok);
        if tok.is_empty() {
            continue;
        }
        if let Some(a) = classify_anchor(tok, false) {
            out.push(a);
        }
    }
    out.sort_by(|a, b| (a.kind as u8, &a.value).cmp(&(b.kind as u8, &b.value)));
    out.dedup_by(|a, b| a.kind == b.kind && a.value == b.value);
    out
}

// ---------------------------------------------------------------------------
// Layer 2: evidence from the checkout and git
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Signal {
    /// A value the claim states matches what is observed.
    Confirms,
    Contradicts,
    /// What the anchor names is there: a path at HEAD or on this machine, a
    /// name in the tracked tree, a variable something reads. That is what a
    /// rule's anchor asks, and all it gets. It says nothing about what a
    /// `present` claim asserts *of* the thing: "`RECALL_HOST` sets the bind
    /// address" names a variable that appears in the code and is still
    /// false. So it never makes a present claim `still_true`, but it is
    /// still a fact layer 3 may cite, either way. A path the note itself
    /// says is gone, which git agrees was deleted, is the same kind of fact:
    /// it matches what the note says of the thing, and decides no more.
    Exists,
    Unknown,
}

/// One anchor's own verdict. [`Signal::Exists`] decides a rule's anchor and
/// nothing else.
fn verdict_of_signal(s: Signal, class: Class) -> Verdict {
    match s {
        Signal::Confirms => Verdict::StillTrue,
        Signal::Exists if class == Class::Rule => Verdict::StillTrue,
        Signal::Contradicts => Verdict::Stale,
        Signal::Exists | Signal::Unknown => Verdict::CantTell,
    }
}

struct Observed {
    signal: Signal,
    source: String,
    detail: String,
}

fn observed(signal: Signal, source: &str, detail: String) -> Observed {
    Observed {
        signal,
        source: source.to_string(),
        detail,
    }
}

/// A pathspec for `value`, safe to pass to `git` after `--`.
///
/// A value with a slash is matched literally: git's default pathspec
/// matching treats `*`, `?` and `[` as wildcards even without `:(glob)`, so
/// a claim that happens to *quote* a glob such as `` `hooks/recall-*` ``
/// must not be matched against every file under `hooks/`. A bare filename —
/// what a note actually writes, most of the time — is matched anywhere in
/// the tree instead of only at the repository root, since `lib.sh` living
/// at `hooks/lib.sh` is exactly the case this exists for; a bare value that
/// itself contains a wildcard character falls back to a literal match,
/// which simply never exists, rather than glob-matching more than it
/// should.
fn pathspec_for(value: &str) -> String {
    if value.contains('/') || value.contains(['*', '?', '[']) {
        format!(":(literal){value}")
    } else {
        format!(":(glob)**/{value}")
    }
}

/// A thin wrapper over `git`, run in the project root. `root` is [`None`]
/// outside a git repository, in which case every check reads as
/// [`Signal::Unknown`] rather than running `git` at all.
///
/// Every invocation passes `stdin(Stdio::null())`: `git grep` in particular
/// has flags (`-f-`, `-O...`) that read from or act on things other than
/// its pattern, and a term taken verbatim from someone's memory file must
/// never be able to make this hang waiting on input that will never come.
struct Repo {
    root: Option<PathBuf>,
}

/// Where the checkout stands against what it tracks. See [`Repo::lag`].
#[derive(Default)]
struct Lag {
    detached: bool,
    upstream: Option<String>,
    behind: Option<u32>,
}

impl Repo {
    fn at(root: Option<PathBuf>) -> Self {
        Repo { root }
    }

    fn git(&self, args: &[&str]) -> Option<String> {
        let root = self.root.as_ref()?;
        let out = Command::new("git")
            .args(args)
            .current_dir(root)
            .stdin(Stdio::null())
            .output()
            .ok()?;
        if !out.status.success() {
            return None;
        }
        Some(String::from_utf8_lossy(&out.stdout).into_owned())
    }

    fn head_short(&self) -> Option<String> {
        self.git(&["rev-parse", "--short", "HEAD"])
            .map(|s| s.trim().to_string())
            .filter(|s| !s.is_empty())
    }

    /// Whether `HEAD` is detached, and how far behind it is: behind its
    /// branch's upstream, or behind the remote's default branch when it is
    /// on no branch. As last fetched: nothing here touches the network.
    fn lag(&self) -> Lag {
        if self.root.is_none() || self.head_short().is_none() {
            return Lag::default();
        }
        let detached = self.git(&["symbolic-ref", "-q", "HEAD"]).is_none();
        let upstream = if detached {
            self.git(&["rev-parse", "--abbrev-ref", "origin/HEAD"])
        } else {
            self.git(&[
                "rev-parse",
                "--abbrev-ref",
                "--symbolic-full-name",
                "@{upstream}",
            ])
        }
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty() && s != "origin/HEAD");
        let behind = upstream.as_deref().and_then(|u| {
            self.git(&["rev-list", "--count", &format!("HEAD..{u}")])
                .and_then(|s| s.trim().parse().ok())
        });
        Lag {
            detached,
            upstream,
            behind,
        }
    }

    /// Whether `path` is tracked at `HEAD`.
    fn tracked(&self, path: &str) -> bool {
        let spec = pathspec_for(path);
        self.git(&["ls-files", "--", &spec])
            .is_some_and(|s| !s.trim().is_empty())
    }

    /// The commit and date `path` was deleted in, if git's history has one.
    fn deleted(&self, path: &str) -> Option<(String, String)> {
        let spec = pathspec_for(path);
        let out = self.git(&[
            "log",
            "--diff-filter=D",
            "-1",
            "--format=%h %cs",
            "--",
            &spec,
        ])?;
        let out = out.trim();
        if out.is_empty() {
            return None;
        }
        let (hash, date) = out.split_once(' ')?;
        Some((hash.to_string(), date.to_string()))
    }

    /// Whether `term` still appears anywhere in the tracked tree, outside
    /// Markdown documentation: a name mentioned only in `docs/**`,
    /// `ROADMAP.md` or `CHANGELOG.md` — including in the sentence *this*
    /// review is checking — is prose about the name, not the name still
    /// being used.
    ///
    /// `-e` marks `term` unambiguously as the pattern, never an option:
    /// without it, a term shaped like `-f-` makes `git grep` read patterns
    /// from standard input, `-fLICENSE` from a file, and `-O...` opens a
    /// pager — each on text taken verbatim from a memory file. `--w -F`
    /// (word-bounded, fixed-string) matches how this is documented; the
    /// trailing `--` closes off the option list before `-e`'s argument,
    /// belt-and-braces alongside `-e` itself.
    fn references(&self, term: &str) -> Option<bool> {
        let root = self.root.as_ref()?;
        let out = Command::new("git")
            .args(["grep", "-l", "-w", "-F", "-e", term, "--"])
            .current_dir(root)
            .stdin(Stdio::null())
            .output()
            .ok()?;
        // Exit 0: found in at least one file, listed on stdout. Exit 1:
        // ran, found nothing. Anything else (2+): the search itself failed
        // and says nothing about whether the term is still used.
        match out.status.code() {
            Some(0) => {
                let files = String::from_utf8_lossy(&out.stdout);
                Some(
                    files
                        .lines()
                        .any(|f| !f.trim().to_ascii_lowercase().ends_with(".md")),
                )
            }
            Some(1) => Some(false),
            _ => None,
        }
    }

    /// The newest tag that parses as a version, as `(major, minor, patch,
    /// the tag's own text)`.
    fn newest_tag(&self) -> Option<(u64, u64, u64, String)> {
        let out = self.git(&["tag"])?;
        out.lines()
            .filter_map(parse_semver_tag)
            .max_by_key(|t| (t.0, t.1, t.2))
    }
}

fn parse_semver(text: &str) -> Option<(u64, u64, u64)> {
    let t = text.strip_prefix('v').unwrap_or(text);
    let mut parts = t.splitn(3, '.');
    let major = parts.next()?.parse().ok()?;
    let minor = parts.next()?.parse().ok()?;
    let patch_str = parts.next()?;
    let patch_digits: String = patch_str.chars().take_while(char::is_ascii_digit).collect();
    let patch = patch_digits.parse().ok()?;
    Some((major, minor, patch))
}

fn parse_semver_tag(tag: &str) -> Option<(u64, u64, u64, String)> {
    let (major, minor, patch) = parse_semver(tag.trim())?;
    Some((major, minor, patch, tag.trim().to_string()))
}

/// Whether the claim's own words assert that this *is* the current
/// version, rather than merely mentioning one — "shipped in 0.4.5" stays
/// true forever, even once 0.4.8 is out, and must never be marked stale
/// just for naming an older number.
fn asserts_current_version(claim_text: &str) -> bool {
    let lower = claim_text.to_ascii_lowercase();
    [
        "current version",
        "currently on",
        "is at version",
        "is on version",
        "is at v",
        "latest version",
        "version is",
        "recall is at",
    ]
    .iter()
    .any(|p| lower.contains(p))
}

fn machine_path_exists(p: &str) -> bool {
    let expanded = match p.strip_prefix("~/") {
        Some(rest) => match std::env::var("HOME") {
            Ok(home) if !home.is_empty() => format!("{home}/{rest}"),
            _ => return false,
        },
        None => p.to_string(),
    };
    Path::new(&expanded).exists()
}

/// Whether a sentence of `claim` that names `value` also says it is gone:
/// retired, deleted, removed, renamed, moved, replaced, superseded, or no
/// longer there. Only the sentences naming the path count, so a paragraph
/// that retires one file does not excuse another it still relies on.
fn says_it_is_gone(claim: &str, value: &str) -> bool {
    const GONE: [&str; 9] = [
        "retired",
        "deleted",
        "removed",
        "renamed",
        "moved",
        "replaced",
        "superseded",
        "no longer",
        "gone",
    ];
    // A sentence ends at `.`, `!` or `?` followed by whitespace, or at a
    // line break: the `.` inside `PROMPT.md` ends nothing.
    let mut sentences = Vec::new();
    let mut start = 0;
    let mut chars = claim.char_indices().peekable();
    while let Some((i, c)) = chars.next() {
        let next_is_space = chars.peek().is_none_or(|(_, n)| n.is_whitespace());
        if c == '\n' || (matches!(c, '.' | '!' | '?') && next_is_space) {
            sentences.push(&claim[start..i + c.len_utf8()]);
            start = i + c.len_utf8();
        }
    }
    sentences.push(&claim[start..]);
    sentences
        .into_iter()
        .filter(|sentence| sentence.contains(value))
        .any(|sentence| {
            let lower = sentence.to_lowercase();
            GONE.iter().any(|w| {
                lower.match_indices(w).any(|(i, _)| {
                    let before = lower[..i].chars().next_back();
                    let after = lower[i + w.len()..].chars().next();
                    !before.is_some_and(char::is_alphanumeric)
                        && !after.is_some_and(char::is_alphanumeric)
                })
            })
        })
}

fn evidence_for_path(repo: &Repo, value: &str, is_project: bool, claim_text: &str) -> Observed {
    if is_machine_absolute(value) {
        return if machine_path_exists(value) {
            observed(
                Signal::Exists,
                "machine",
                format!("`{value}` exists on this machine"),
            )
        } else {
            observed(
                Signal::Unknown,
                "machine",
                format!(
                    "`{value}` was not found on this machine; the claim may be about another one"
                ),
            )
        };
    }
    if !is_project {
        return observed(
            Signal::Unknown,
            "repository",
            format!(
                "`{value}` names a repository path, but this note is outside the project scope; \
                 the checkout only speaks for the project"
            ),
        );
    }
    if repo.root.is_none() {
        return observed(
            Signal::Unknown,
            "repository",
            "this is not a git repository, so its history cannot be read".to_string(),
        );
    }
    if repo.tracked(value) {
        return observed(
            Signal::Exists,
            "repository",
            format!("`{value}` exists at HEAD"),
        );
    }
    match repo.deleted(value) {
        // "It lived in `PROMPT.md`; that file was retired" is not made stale
        // by the deletion it reports.
        Some((hash, date)) if says_it_is_gone(claim_text, value) => observed(
            Signal::Exists,
            "git",
            format!("`{value}` was deleted in {hash} ({date}), as the note says"),
        ),
        Some((hash, date)) => observed(
            Signal::Contradicts,
            "git",
            format!("`{value}` was deleted in {hash} ({date}) and is not at HEAD"),
        ),
        None => observed(
            Signal::Unknown,
            "git",
            format!("`{value}` is not at HEAD and git has no record of it ever being tracked"),
        ),
    }
}

fn evidence_for_semver(
    newest_tag: &Option<(u64, u64, u64, String)>,
    value: &str,
    is_project: bool,
    claim_text: &str,
) -> Observed {
    if !is_project {
        return observed(
            Signal::Unknown,
            "repository",
            format!(
                "`{value}` would be checked against this project's release tags; this note is \
                 outside the project scope"
            ),
        );
    }
    let Some(claimed) = parse_semver(value) else {
        return observed(
            Signal::Unknown,
            "git",
            format!("`{value}` is not a version this can parse"),
        );
    };
    match newest_tag {
        Some((major, minor, patch, tag)) => {
            let newest = (*major, *minor, *patch);
            if claimed == newest {
                observed(
                    Signal::Confirms,
                    "git",
                    format!("matches the newest release tag {tag}"),
                )
            } else if claimed < newest && asserts_current_version(claim_text) {
                observed(
                    Signal::Contradicts,
                    "git",
                    format!("the newest release tag is {tag}"),
                )
            } else if claimed < newest {
                observed(
                    Signal::Unknown,
                    "git",
                    format!(
                        "older than the newest release tag {tag}; the claim may be about when \
                         something shipped, not the current version"
                    ),
                )
            } else {
                observed(
                    Signal::Unknown,
                    "git",
                    format!("newer than the newest release tag {tag}; nothing here can tell why"),
                )
            }
        }
        None => observed(Signal::Unknown, "git", "no release tags found".to_string()),
    }
}

fn evidence_for_code(repo: &Repo, value: &str, is_project: bool) -> Observed {
    if !is_project {
        return observed(
            Signal::Unknown,
            "repository",
            format!(
                "`{value}` would be checked against this project's tracked tree; this note is \
                 outside the project scope"
            ),
        );
    }
    match repo.references(value) {
        // Absence is weak evidence — a name can be real and simply not
        // grep-able (a different casing, a generated file) — so it is
        // never enough on its own to call a claim stale.
        Some(true) => observed(
            Signal::Exists,
            "git",
            format!("`{value}` is still referenced in the tracked tree, outside documentation"),
        ),
        Some(false) => observed(
            Signal::Unknown,
            "git",
            format!(
                "`{value}` was not found outside documentation in the tracked tree; that alone \
                 does not make it gone"
            ),
        ),
        None => observed(
            Signal::Unknown,
            "git",
            "this is not a git repository, so it cannot be searched".to_string(),
        ),
    }
}

fn evidence_for(
    anchor: &Anchor,
    repo: &Repo,
    is_project: bool,
    newest_tag: &Option<(u64, u64, u64, String)>,
    claim_text: &str,
    facts: &sources::Facts,
) -> Observed {
    let value = anchor.value.as_str();
    match anchor.kind {
        AnchorKind::Path => evidence_for_path(repo, value, is_project, claim_text),
        // A version in a claim about the server is about what the server
        // runs, whatever the scope: the server is this machine's, not the
        // project's. Any other version is about this project's releases.
        AnchorKind::SemVer => parse_semver(value)
            .and_then(|v| sources::evidence_for_server_version(v, claim_text, facts))
            .unwrap_or_else(|| evidence_for_semver(newest_tag, value, is_project, claim_text)),
        AnchorKind::Code => sources::evidence_for_name(value, facts, is_project)
            .unwrap_or_else(|| evidence_for_code(repo, value, is_project)),
        AnchorKind::Hostname => sources::evidence_for_host(value, claim_text, facts),
        AnchorKind::EnvVar => {
            if let Some(o) = sources::evidence_for_env_value(value, claim_text, facts) {
                return o;
            }
            // Any other variable is judged by its name: a value it is given
            // in a note may be a secret, and is never read or compared.
            let name = value.split('=').next().unwrap_or(value);
            sources::evidence_for_env_name(name, facts, is_project)
                .unwrap_or_else(|| evidence_for_code(repo, name, is_project))
        }
    }
}

fn verdict_from(observed: &[Observed]) -> Option<Verdict> {
    if observed.is_empty() {
        return None;
    }
    let any = |s: Signal| observed.iter().any(|o| o.signal == s);
    if any(Signal::Contradicts) {
        Some(Verdict::Stale)
    } else if any(Signal::Confirms) && !any(Signal::Unknown) {
        // At least one stated value matched, and every other anchor is at
        // least there. Existence alone, however many anchors, is not enough.
        Some(Verdict::StillTrue)
    } else {
        Some(Verdict::CantTell)
    }
}

// ---------------------------------------------------------------------------
// Human output
// ---------------------------------------------------------------------------

fn lines_desc(l: &[u32; 2]) -> String {
    if l[0] == l[1] {
        format!("L{}", l[0])
    } else {
        format!("L{}-{}", l[0], l[1])
    }
}

/// Memory text, made safe to write to a terminal: a control character
/// (other than a tab) becomes a space, so a note nobody has looked at
/// cannot plant an escape sequence that moves the cursor or rewrites what
/// came before it. Never applied to the stored or `--json` text — only to
/// what actually reaches a terminal.
fn sanitize_for_terminal(s: &str) -> String {
    crate::edit::printable(s).replace('\n', " ")
}

/// How wide a claim's text may run before it is clipped.
const CLAIM_WIDTH: usize = 96;
/// How wide one line of evidence may run.
const DETAIL_WIDTH: usize = 104;

/// `✗ stale`, `✓ still true`, `? can't tell`, in their colour.
fn verdict_mark(v: Verdict) -> String {
    let (mark, tone) = match v {
        Verdict::Stale => ("✗", ui::Tone::Bad),
        Verdict::StillTrue => ("✓", ui::Tone::Good),
        Verdict::CantTell => ("?", ui::Tone::Warn),
    };
    ui::toned(tone, mark)
}

/// One claim's first line: its mark, its id, its lines and its text.
fn claim_line(mark: &str, c: &Claim) {
    anstream::println!(
        "  {mark} {}  {}  {}",
        ui::bold(&format!("{:<4}", c.id)),
        ui::dim(&format!("{:<7}", lines_desc(&c.lines))),
        sanitize_for_terminal(&ui::clip(&c.text, CLAIM_WIDTH))
    );
}

/// One line under a claim: a piece of evidence, marked by its own verdict,
/// or a note.
fn under_claim(mark: &str, text: &str) {
    anstream::println!(
        "           {mark} {}",
        sanitize_for_terminal(&ui::clip(text, DETAIL_WIDTH))
    );
}

/// What a stale claim can do next: its suggested edit, or the lines to
/// edit. `--claude` is not offered here: it is asked only about what the
/// checks could not decide, so a claim they found stale never gets a
/// suggestion from it.
fn next_for_stale(c: &Claim) -> String {
    match &c.suggested_edit {
        Some(_) => format!("recall review apply {}", c.id),
        None => format!("edit {} {}", c.file, lines_desc(&c.lines)),
    }
}

/// Which of a claim's verdicts count toward the summary: a present claim's
/// one verdict, or each of a rule's anchors.
fn verdicts_of(c: &Claim) -> Vec<Verdict> {
    match c.class {
        Class::Present => c.verdict.into_iter().collect(),
        Class::Rule => c.evidence.iter().map(|e| e.verdict).collect(),
        _ => Vec::new(),
    }
}

/// Whether a claim is something the owner has to act on: a merge conflict,
/// a stale present claim, or a rule with a stale anchor.
fn needs_action(c: &Claim) -> bool {
    match c.class {
        Class::Conflict => true,
        Class::Present => c.verdict == Some(Verdict::Stale),
        Class::Rule => c.evidence.iter().any(|e| e.verdict == Verdict::Stale),
        _ => false,
    }
}

/// A warning about the run itself, printed before any claim: something
/// that makes every verdict below it less trustworthy, with what to do.
struct Warning {
    text: String,
    fix: String,
}

/// What makes this report less trustworthy than it looks: a checkout that
/// is not the code as it is now, and a `claude` that could not answer.
fn warnings(rep: &Report) -> Vec<Warning> {
    let mut out = Vec::new();
    let ev = &rep.evidence;
    let behind = ev.repository_behind.unwrap_or(0);
    if behind > 0 || (ev.repository_detached && ev.repository_behind.is_none()) {
        let head = ev.repository_head.as_deref().unwrap_or("HEAD");
        let at = if ev.repository_detached {
            format!("a detached HEAD at {head}")
        } else {
            format!("at {head}")
        };
        let lag = match (&ev.repository_upstream, behind) {
            (Some(up), n) if n > 0 => format!(", {n} commit(s) behind {up} as last fetched"),
            _ => String::new(),
        };
        let branch = ev
            .repository_upstream
            .as_deref()
            .and_then(|u| u.split_once('/').map(|(_, b)| b.to_string()))
            .unwrap_or_else(|| "main".to_string());
        out.push(Warning {
            text: format!(
                "This checkout is {at}{lag}. Claims are checked against it, not against the \
                 code as it is now, so a verdict below can be wrong."
            ),
            fix: if ev.repository_detached {
                format!("git switch {branch} && git pull, then review again")
            } else {
                "git pull, then review again".to_string()
            },
        });
    }
    if let Some(run) = &ev.claude {
        if let Some(why) = &run.failure {
            let not_asked = run.skipped.len();
            let ran = run
                .binary
                .as_deref()
                .map(|b| format!(" It ran {b} on this machine."))
                .unwrap_or_default();
            out.push(Warning {
                text: format!(
                    "claude could not answer, so {not_asked} file(s) got no answer: {why}.{ran}"
                ),
                fix: "claude -p \"hello\" in this terminal shows the same error; fix it there \
                      (a login is /login in claude), then recall review run --claude"
                    .to_string(),
            });
        } else if !run.skipped.is_empty() {
            out.push(Warning {
                text: format!(
                    "claude was not asked about {} file(s): {}.",
                    run.skipped.len(),
                    run.skipped[0].reason
                ),
                fix: "recall review show --details lists them".to_string(),
            });
        }
    }
    out
}

fn print_text(rep: &Report, details: bool) {
    let mut about = Vec::new();
    if let Some(head) = &rep.evidence.repository_head {
        about.push(format!("checkout {head}"));
    }
    if let Some(v) = &rep.evidence.server_version {
        about.push(format!("server {v}"));
    }
    if let Some(id) = &rep.evidence.evaluation {
        about.push(format!("report {id}"));
    }
    ui::title("recall review", &about.join(" · "));

    // What undermines the whole report comes before any of it.
    let warned = warnings(rep);
    let mut next: Vec<String> = Vec::new();
    for w in &warned {
        anstream::println!();
        anstream::println!(
            "{} {}",
            ui::toned(ui::Tone::Warn, "!"),
            sanitize_for_terminal(&w.text)
        );
        anstream::println!("  {}", ui::accent(&format!("→ {}", w.fix)));
    }

    if rep.claims.is_empty() {
        anstream::println!();
        anstream::println!("Nothing to review: no memory files with checkable content were found.");
        return;
    }

    let count = |f: &dyn Fn(&Claim) -> bool| rep.claims.iter().filter(|c| f(c)).count();
    let tally = |v: Verdict| {
        rep.claims
            .iter()
            .map(|c| verdicts_of(c).iter().filter(|x| **x == v).count())
            .sum::<usize>()
    };
    let (stale, still_true, cant_tell) = (
        tally(Verdict::Stale),
        tally(Verdict::StillTrue),
        tally(Verdict::CantTell),
    );
    let records = count(&|c| c.class == Class::Record);
    let conflicts = count(&|c| c.class == Class::Conflict);
    let to_act = count(&needs_action);
    let undecided =
        count(&|c| c.class == Class::Unsure || (c.class == Class::Present && c.verdict.is_none()));

    // The answer first, in words: whether anything needs the owner.
    anstream::println!();
    if to_act == 0 {
        anstream::println!(
            "{}",
            ui::toned(ui::Tone::Good, "Nothing to fix: no claim is stale.")
        );
    } else {
        anstream::println!(
            "{}",
            ui::toned(
                ui::Tone::Bad,
                &format!("{to_act} claim(s) need a look: they say something that is no longer so.")
            )
        );
    }
    let mut parts = vec![
        ui::toned(
            if stale > 0 {
                ui::Tone::Bad
            } else {
                ui::Tone::Quiet
            },
            &format!("✗ {stale} stale"),
        ),
        ui::toned(
            if still_true > 0 {
                ui::Tone::Good
            } else {
                ui::Tone::Quiet
            },
            &format!("✓ {still_true} still true"),
        ),
        ui::toned(
            if cant_tell > 0 {
                ui::Tone::Warn
            } else {
                ui::Tone::Quiet
            },
            &format!("? {cant_tell} can't tell"),
        ),
    ];
    if conflicts > 0 {
        parts.push(ui::toned(
            ui::Tone::Warn,
            &format!("! {conflicts} conflict(s)"),
        ));
    }
    anstream::println!("  {}", parts.join("   "));
    // What the three counts leave out, said in words rather than as two
    // more numbers to decode.
    let mut rest = Vec::new();
    if records > 0 {
        rest.push(format!("{records} line(s) of history"));
    }
    if undecided > 0 {
        rest.push(format!("{undecided} with nothing a check can test"));
    }
    if !rest.is_empty() {
        anstream::println!(
            "  {}",
            ui::dim(&format!(
                "Also read, and left as written: {}.",
                rest.join(", ")
            ))
        );
    }

    let mut by_file: BTreeMap<&str, Vec<&Claim>> = BTreeMap::new();
    for c in &rep.claims {
        by_file.entry(c.file.as_str()).or_default().push(c);
    }
    let has_findings = |claims: &[&Claim]| claims.iter().any(|c| !c.eval.is_empty());
    // Files with something to act on first, the worst first; files with
    // nothing any check could decide are one line at the end.
    let worst = |claims: &[&Claim]| -> u8 {
        let vs: Vec<Verdict> = claims.iter().flat_map(|c| verdicts_of(c)).collect();
        if claims.iter().any(|c| needs_action(c)) {
            0
        } else if vs.contains(&Verdict::CantTell) {
            1
        } else if !vs.is_empty() || has_findings(claims) {
            2
        } else {
            3
        }
    };
    let mut files: Vec<(&str, &Vec<&Claim>)> = by_file.iter().map(|(f, c)| (*f, c)).collect();
    files.sort_by_key(|(f, c)| (worst(c), *f));

    let mut quiet_files = Vec::new();
    let mut cant_tell_files = 0;
    for (file, claims) in &files {
        if worst(claims) == 3 {
            quiet_files.push(*file);
            continue;
        }
        if claims
            .iter()
            .any(|c| verdicts_of(c).contains(&Verdict::CantTell))
        {
            cant_tell_files += 1;
        }
        // Without --details, a file is shown only for what needs the owner.
        if !details && worst(claims) != 0 && !has_findings(claims) {
            continue;
        }
        anstream::println!();
        anstream::println!("{}", ui::bold(&sanitize_for_terminal(file)));

        let mut order: Vec<&&Claim> = claims
            .iter()
            .filter(|c| {
                if !details {
                    return needs_action(c);
                }
                matches!(c.class, Class::Conflict | Class::Rule)
                    || (c.class == Class::Present && c.verdict.is_some())
                    || (c.class == Class::Unsure && c.layer == Some(3))
            })
            .collect();
        let rank = |c: &Claim| match (c.class, c.verdict) {
            (Class::Conflict, _) => 0,
            (_, Some(Verdict::Stale)) => 1,
            (Class::Rule, _) if c.evidence.iter().any(|e| e.verdict == Verdict::Stale) => 1,
            (_, Some(Verdict::CantTell)) => 2,
            (Class::Rule, _) => 3,
            (_, Some(Verdict::StillTrue)) => 4,
            _ => 5,
        };
        order.sort_by_key(|c| (rank(c), c.lines[0]));

        for c in order {
            match (c.class, c.verdict) {
                (Class::Conflict, _) => {
                    claim_line(&ui::toned(ui::Tone::Warn, "!"), c);
                    under_claim(
                        &ui::toned(ui::Tone::Warn, "!"),
                        "a merge left a conflict here; edit the file to keep one version",
                    );
                }
                (Class::Rule, _) => {
                    claim_line(&ui::dim("§"), c);
                    // Without --details, only the anchors that are why it
                    // is shown.
                    for e in c
                        .evidence
                        .iter()
                        .filter(|e| details || e.verdict == Verdict::Stale)
                    {
                        under_claim(&verdict_mark(e.verdict), &e.detail);
                    }
                    if c.evidence.iter().any(|e| e.verdict == Verdict::Stale) {
                        let step = format!("edit {} {}", c.file, lines_desc(&c.lines));
                        under_claim(&ui::accent("→"), &step);
                    }
                }
                (Class::Unsure, _) => {
                    claim_line(&ui::dim("·"), c);
                    for e in &c.evidence {
                        under_claim(&ui::dim("·"), &e.detail);
                    }
                }
                (_, Some(v)) => {
                    claim_line(&verdict_mark(v), c);
                    // The evidence that decided it; the rest is --details.
                    let shown: Vec<&Evidence> = c
                        .evidence
                        .iter()
                        .filter(|e| details || e.verdict == v)
                        .collect();
                    for e in &shown {
                        under_claim(&verdict_mark(e.verdict), &e.detail);
                    }
                    if v == Verdict::Stale {
                        if let Some(edit) = &c.suggested_edit {
                            under_claim(
                                &ui::accent("→"),
                                &format!("suggested: {}", edit.replacement.trim()),
                            );
                        }
                        let step = next_for_stale(c);
                        under_claim(&ui::accent("→"), &step);
                        next.push(step);
                    }
                }
                _ => {}
            }
        }

        if details {
            let file_records = claims.iter().filter(|c| c.class == Class::Record).count();
            let file_undecided = claims
                .iter()
                .filter(|c| {
                    (c.class == Class::Unsure && c.layer != Some(3))
                        || (c.class == Class::Present && c.verdict.is_none())
                })
                .count();
            let mut counted = Vec::new();
            if file_records > 0 {
                counted.push(format!("{file_records} line(s) of history"));
            }
            if file_undecided > 0 {
                counted.push(format!("{file_undecided} with nothing a check can test"));
            }
            if !counted.is_empty() {
                anstream::println!("  {}", ui::dim(&format!("· also {}", counted.join(", "))));
            }
        }
        // The worker's findings on this file, each with the claims it
        // covers.
        let mut found: BTreeMap<(&str, &str), (&reports::EvalFinding, Vec<String>)> =
            BTreeMap::new();
        for c in claims.iter() {
            for e in &c.eval {
                found
                    .entry((e.evaluation.as_str(), e.finding.as_str()))
                    .or_insert((e, Vec::new()))
                    .1
                    .push(format!("{} ({})", c.id, lines_desc(&c.lines)));
            }
        }
        for (e, ids) in found.values() {
            let tone = match e.severity.as_str() {
                "high" => ui::Tone::Bad,
                "medium" => ui::Tone::Warn,
                _ => ui::Tone::Quiet,
            };
            anstream::println!(
                "  {} {} {} {} ({}), on {}  {}",
                ui::toned(tone, "◆"),
                sanitize_for_terminal(&e.evaluation),
                sanitize_for_terminal(&e.finding),
                ui::toned(tone, &sanitize_for_terminal(&e.kind)),
                sanitize_for_terminal(&e.severity),
                ids.join(", "),
                ui::accent(&format!(
                    "→ recall eval show {}",
                    sanitize_for_terminal(&e.evaluation)
                ))
            );
        }
    }

    if details {
        if !quiet_files.is_empty() {
            anstream::println!();
            anstream::println!(
                "{}",
                ui::dim(&format!(
                    "Nothing a check could decide in: {}",
                    quiet_files
                        .iter()
                        .map(|f| sanitize_for_terminal(f))
                        .collect::<Vec<_>>()
                        .join(", ")
                ))
            );
        }
        // Layer 3's own account: what it asked, and what it did not, never
        // silently cut.
        if let Some(run) = &rep.evidence.claude {
            anstream::println!();
            anstream::println!(
                "{}  {}",
                ui::bold("claude"),
                ui::dim(&format!(
                    "{} call(s), {} file(s) unchanged since it was last asked",
                    run.calls, run.reused
                ))
            );
            for s in &run.skipped {
                anstream::println!(
                    "  {} {}: {}",
                    ui::toned(ui::Tone::Warn, "!"),
                    sanitize_for_terminal(&s.file),
                    sanitize_for_terminal(&ui::clip(&s.reason, DETAIL_WIDTH))
                );
            }
        }
        for u in rep
            .evidence
            .unavailable
            .iter()
            .filter(|u| !matches!(u.source.as_str(), "claude" | "compose"))
        {
            anstream::println!(
                "{} {} {}",
                ui::toned(ui::Tone::Quiet, "○"),
                ui::dim(&format!("{} not read:", u.source)),
                ui::dim(&sanitize_for_terminal(&ui::clip(&u.reason, DETAIL_WIDTH)))
            );
        }
    } else if cant_tell > 0 || still_true > 0 {
        // Everything not shown, in one line, and how to see it.
        anstream::println!();
        let mut hidden = Vec::new();
        if cant_tell > 0 {
            hidden.push(format!(
                "{cant_tell} claim(s) in {cant_tell_files} file(s) could not be checked from here"
            ));
        }
        if still_true > 0 {
            hidden.push(format!("{still_true} still hold"));
        }
        anstream::println!(
            "{}",
            ui::dim(&format!(
                "{}. Nothing to do about them; recall review show --details lists each with why.",
                hidden.join(", and ")
            ))
        );
    }

    // What to run next, in one place.
    let waiting = rep
        .evidence
        .unavailable
        .iter()
        .any(|u| u.source == "claude");
    if waiting && undecided > 0 {
        next.push(format!(
            "recall review run --claude, to decide what no check could ({undecided} claim(s))"
        ));
    }
    if !next.is_empty() {
        anstream::println!();
        anstream::println!("{}", ui::bold("Next"));
        for step in next.iter().take(8) {
            anstream::println!("  {}", ui::accent(&format!("→ {step}")));
        }
        if next.len() > 8 {
            anstream::println!("  {}", ui::dim(&format!("… and {} more", next.len() - 8)));
        }
    }
}

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

    fn claims_of(content: &str) -> Vec<(Class, String, [u32; 2])> {
        let note_type = front_matter_type(content);
        extract_claims(content)
            .into_iter()
            .map(|raw| {
                let class = classify(&raw.text, raw.in_record_section, note_type.as_deref());
                (class, raw.text, raw.lines)
            })
            .collect()
    }

    /// A local git repository with `git config` already set, for tests that
    /// need real commits.
    fn git_fixture() -> tempfile::TempDir {
        let dir = tempfile::tempdir().unwrap();
        for args in [
            vec!["init", "-q"],
            vec!["config", "user.email", "t@example.com"],
            vec!["config", "user.name", "Test"],
        ] {
            assert!(Command::new("git")
                .args(&args)
                .current_dir(dir.path())
                .status()
                .unwrap()
                .success());
        }
        dir
    }

    fn git_commit(dir: &Path, message: &str) {
        assert!(Command::new("git")
            .args(["add", "-A"])
            .current_dir(dir)
            .status()
            .unwrap()
            .success());
        assert!(Command::new("git")
            .args(["commit", "-q", "--allow-empty", "-m", message])
            .current_dir(dir)
            .status()
            .unwrap()
            .success());
    }

    #[test]
    fn a_list_item_is_one_claim_with_its_line_range() {
        let content = "- The server is at `x`.\n- Second one.\n";
        let claims = claims_of(content);
        assert_eq!(claims.len(), 2, "{claims:?}");
        assert_eq!(claims[0].2, [1, 1]);
        assert_eq!(claims[1].2, [2, 2]);
    }

    #[test]
    fn a_fenced_block_is_one_claim() {
        let content = "Some text.\n\n```sh\nrecall status\necho hi\n```\n";
        let claims = claims_of(content);
        let fence = claims
            .iter()
            .find(|c| c.1.contains("```"))
            .expect("a fenced claim");
        assert_eq!(fence.2, [3, 6], "{:?}", fence.2);
    }

    #[test]
    fn front_matter_is_never_a_claim() {
        let content = "---\nname: x\ntype: user\n---\n\nPrefers tabs.\n";
        let claims = claims_of(content);
        assert!(claims.iter().all(|c| !c.1.contains("type: user")));
    }

    #[test]
    fn a_type_user_note_classifies_every_claim_as_rule() {
        let content = "---\ntype: user\n---\n\nPrefers tabs over spaces.\n";
        let claims = claims_of(content);
        assert_eq!(claims.len(), 1);
        assert_eq!(claims[0].0, Class::Rule);
    }

    /// The order classification checks in: a record signal wins over the
    /// note's own `type:`, so a correction inside feedback is never treated
    /// as a rule whose anchors get judged as still-current.
    #[test]
    fn a_correction_inside_a_feedback_note_is_a_record_not_a_rule() {
        let content =
            "---\ntype: feedback\n---\n\nNot `lib.sh` any more, it was deleted in the rewrite.\n";
        let claims = claims_of(content);
        assert_eq!(claims.len(), 1);
        assert_eq!(claims[0].0, Class::Record, "{:?}", claims[0]);
    }

    #[test]
    fn a_history_heading_makes_every_claim_under_it_a_record() {
        let content = "It is at `x`.\n\n## History\n\nIt used to be at `y`.\n";
        let claims = claims_of(content);
        assert_eq!(claims.len(), 2);
        assert_eq!(claims[0].0, Class::Present, "{:?}", claims[0]);
        assert_eq!(claims[1].0, Class::Record, "{:?}", claims[1]);
    }

    /// A subsection nested under a History heading stays part of it, and a
    /// sibling heading at the same level correctly leaves it.
    #[test]
    fn a_nested_heading_under_history_stays_a_record() {
        let content =
            "## History\n\n### 2026-09\n\nIt used to be at `y`.\n\n## Now\n\nIt is at `x`.\n";
        let claims = claims_of(content);
        assert_eq!(claims.len(), 2);
        assert_eq!(
            claims[0].0,
            Class::Record,
            "nested under History: {:?}",
            claims[0]
        );
        assert_eq!(
            claims[1].0,
            Class::Present,
            "back to a sibling section: {:?}",
            claims[1]
        );
    }

    #[test]
    fn a_negated_anchor_is_a_record_even_without_a_heading() {
        let content =
            "Not the old `hooks/recall-pull` script, and not `lib.sh`: both were deleted.\n";
        let claims = claims_of(content);
        assert_eq!(claims.len(), 1);
        assert_eq!(claims[0].0, Class::Record);
    }

    #[test]
    fn a_conflict_marker_is_its_own_class_whatever_else_is_true() {
        let content = "The rate limit is `[CONFLICT: 10/min vs 100/min]` per minute.\n";
        let claims = claims_of(content);
        assert_eq!(claims.len(), 1);
        assert_eq!(claims[0].0, Class::Conflict);
    }

    #[test]
    fn plain_prose_with_no_present_or_record_signal_is_unsure() {
        let content = "Something about the weather today, which is nice.\n";
        let claims = claims_of(content);
        assert_eq!(claims.len(), 1);
        assert_eq!(claims[0].0, Class::Unsure);
    }

    /// The design's worked example writes one claim as a bare assignment
    /// (`CLAUDE_CODE_REMOTE_MEMORY_DIR=/home/user/.claude`): that states
    /// what a variable is set to now. Prose that merely contains one does
    /// not become present for it.
    #[test]
    fn a_bare_assignment_is_a_present_claim() {
        for line in [
            "- CLAUDE_CODE_REMOTE_MEMORY_DIR=/home/user/.claude\n",
            "- `RECALL_URL=https://recall.example.com`.\n",
        ] {
            assert_eq!(claims_of(line)[0].0, Class::Present, "{line:?}");
        }
        for line in [
            "- Maybe try FOO_BAR=1 when it misbehaves.\n",
            "- FOO_BAR=\n",
        ] {
            assert_eq!(claims_of(line)[0].0, Class::Unsure, "{line:?}");
        }
    }

    #[test]
    fn anchors_recognise_every_kind_the_design_names() {
        let text =
            "`lib.sh` `recall.pimlabs.id` `RECALL_URL` `0.4.8` `--json` `/home/user/.claude`";
        let found = anchors(text);
        let kinds: Vec<AnchorKind> = found.iter().map(|a| a.kind).collect();
        assert!(kinds.contains(&AnchorKind::Path), "{kinds:?}");
        assert!(kinds.contains(&AnchorKind::Hostname), "{kinds:?}");
        assert!(kinds.contains(&AnchorKind::EnvVar), "{kinds:?}");
        assert!(kinds.contains(&AnchorKind::SemVer), "{kinds:?}");
        assert!(kinds.contains(&AnchorKind::Code), "{kinds:?}");
    }

    #[test]
    fn a_bare_english_word_outside_code_is_not_an_anchor() {
        let found = anchors("recall is a tool that syncs memory reliably across machines");
        assert!(
            found.is_empty(),
            "{:?}",
            found.iter().map(|a| &a.value).collect::<Vec<_>>()
        );
    }

    /// The cheap false positives a bare slash-based path rule would create.
    #[test]
    fn common_idioms_and_fractions_are_not_path_anchors() {
        for tok in ["and/or", "10/min", "on/off", "1/2", "/", "//"] {
            assert!(!is_pathish(tok), "{tok:?} should not look like a path");
        }
        assert!(is_pathish("hooks/recall-pull"), "a real path still does");
    }

    #[test]
    fn a_windows_drive_path_is_a_path_anchor_not_code() {
        for tok in [r"C:\Users\x\.claude", "C:/Users/x/.claude"] {
            let found = anchors(&format!("`{tok}`"));
            assert_eq!(
                found.len(),
                1,
                "{tok:?}: {:?}",
                found.iter().map(|a| &a.value).collect::<Vec<_>>()
            );
            assert_eq!(found[0].kind, AnchorKind::Path, "{tok:?}");
        }
    }

    /// With no server configured there is nothing to compare a hostname
    /// with, and nothing is asked of it.
    #[test]
    fn a_hostname_with_no_server_configured_cant_tell() {
        let repo = Repo::at(None);
        let o = evidence_for(
            &Anchor {
                kind: AnchorKind::Hostname,
                value: "recall.pimlabs.id".into(),
            },
            &repo,
            true,
            &None,
            "",
            &sources::Facts::default(),
        );
        assert_eq!(o.signal, Signal::Unknown);
        assert_eq!(o.source, "server");
    }

    /// The mutation this pins against: a record's anchors must never reach
    /// [`judge`]'s evidence-gathering at all, whatever the evidence would
    /// say. Dropping the class gate in `judge` — treating a layer 1
    /// candidate as if it were a verdict-worthy present claim — must make
    /// this fail.
    #[test]
    fn a_record_never_gets_a_verdict() {
        let repo = Repo::at(None);
        let (verdict, layer, evidence) = judge(
            Class::Record,
            "Not the old `hooks/recall-pull` script, and not `lib.sh`.",
            &repo,
            true,
            &None,
            &sources::Facts::default(),
        );
        assert_eq!(verdict, None);
        assert_eq!(layer, None);
        assert!(evidence.is_empty());
    }

    #[test]
    fn an_unsure_claim_gets_no_verdict_in_this_pr() {
        let repo = Repo::at(None);
        let (verdict, layer, _) = judge(
            Class::Unsure,
            "`lib.sh` is mentioned here.",
            &repo,
            true,
            &None,
            &sources::Facts::default(),
        );
        assert_eq!(verdict, None);
        assert_eq!(layer, None);
    }

    /// The design's own distinction: a `present` claim gets one verdict for
    /// the whole claim, but a `rule`'s substance is never judged — only its
    /// anchors are, each with a verdict of its own.
    #[test]
    fn a_rule_gets_no_claim_level_verdict_but_each_anchor_does() {
        let dir = git_fixture();
        std::fs::write(dir.path().join("lib.sh"), "echo hi\n").unwrap();
        git_commit(dir.path(), "add");
        std::fs::remove_file(dir.path().join("lib.sh")).unwrap();
        git_commit(dir.path(), "remove");
        let repo = Repo::at(Some(dir.path().to_path_buf()));
        let (verdict, _layer, evidence) = judge(
            Class::Rule,
            "Use `lib.sh` for this.",
            &repo,
            true,
            &None,
            &sources::Facts::default(),
        );
        assert_eq!(verdict, None, "a rule's substance is never judged as one");
        assert_eq!(evidence.len(), 1);
        assert_eq!(evidence[0].verdict, Verdict::Stale, "{evidence:?}");
    }

    /// Existence answers a rule's anchor and nothing more. The case that
    /// found this: "`RECALL_HOST` sets the bind address" named a variable
    /// that appears in the code, only in a doc comment, and was
    /// `still_true` while false. A present claim whose anchors only exist
    /// is `cant_tell`, and each anchor stays a fact layer 3 may cite; the
    /// same anchor in a rule is `still_true`. Mutation: let
    /// [`Signal::Exists`] count as [`Signal::Confirms`] in [`verdict_from`].
    #[test]
    fn existence_decides_a_rule_anchor_but_not_a_present_claim() {
        let dir = git_fixture();
        std::fs::write(dir.path().join("config.rs"), "// RECALL_HOST\n").unwrap();
        git_commit(dir.path(), "add");
        let repo = Repo::at(Some(dir.path().to_path_buf()));
        let judged =
            |class, text| judge(class, text, &repo, true, &None, &sources::Facts::default());

        let (verdict, _, evidence) = judged(
            Class::Present,
            "`config.rs` reads `RECALL_HOST` to pick the bind address.",
        );
        assert_eq!(verdict, Some(Verdict::CantTell), "{evidence:?}");
        assert_eq!(evidence.len(), 2, "{evidence:?}");
        for e in &evidence {
            assert_eq!(e.verdict, Verdict::CantTell, "{e:?}");
            assert!(e.citable, "existence is still a fact: {e:?}");
        }

        let (verdict, _, evidence) = judged(Class::Rule, "Keep `config.rs` as it is.");
        assert_eq!(verdict, None);
        assert_eq!(evidence[0].verdict, Verdict::StillTrue, "{evidence:?}");
    }

    /// A stated value that matches decides a present claim, and anchors that
    /// merely exist beside it do not hold it back; one anchor nothing here
    /// can speak to does.
    #[test]
    fn a_matching_value_decides_a_present_claim_whose_other_anchors_exist() {
        let exists = observed(Signal::Exists, "repository", String::new());
        let confirms = observed(Signal::Confirms, "git", String::new());
        let unknown = observed(Signal::Unknown, "git", String::new());
        let both = [exists, confirms];
        assert_eq!(verdict_from(&both), Some(Verdict::StillTrue));
        assert_eq!(verdict_from(&both[..1]), Some(Verdict::CantTell));
        let [_, confirms] = both;
        assert_eq!(verdict_from(&[confirms, unknown]), Some(Verdict::CantTell));
    }

    /// Scope gating: a global or machine note is not about this
    /// repository, so a repository-shaped check on it is `cant_tell`
    /// whatever the checkout actually shows.
    #[test]
    fn a_non_project_scope_gets_cant_tell_from_repository_checks() {
        let dir = git_fixture();
        std::fs::write(dir.path().join("lib.sh"), "echo hi\n").unwrap();
        git_commit(dir.path(), "add");
        std::fs::remove_file(dir.path().join("lib.sh")).unwrap();
        git_commit(dir.path(), "remove");
        let repo = Repo::at(Some(dir.path().to_path_buf()));
        let o = evidence_for_path(&repo, "lib.sh", false, "Run `lib.sh`.");
        assert_eq!(
            o.signal,
            Signal::Unknown,
            "{o:?}",
            o = (o.source.clone(), o.detail.clone())
        );
    }

    /// A note that reports a file's retirement is not made stale by that
    /// file being gone; one that still relies on it is. Seen live: "It
    /// lived in `PROMPT.md` when this was written; that file was retired"
    /// came back `stale` because `PROMPT.md` was deleted.
    #[test]
    fn a_deleted_path_the_note_says_is_gone_is_not_stale() {
        let dir = git_fixture();
        std::fs::write(dir.path().join("PROMPT.md"), "brief\n").unwrap();
        git_commit(dir.path(), "add");
        std::fs::remove_file(dir.path().join("PROMPT.md")).unwrap();
        git_commit(dir.path(), "remove");
        let repo = Repo::at(Some(dir.path().to_path_buf()));

        let retired = "It lived in `PROMPT.md` when this was written; that file was \
                       retired on 2026-08-12 once the project was built.";
        let o = evidence_for_path(&repo, "PROMPT.md", true, retired);
        assert_eq!(o.signal, Signal::Exists, "{}", o.detail);
        assert!(o.detail.contains("as the note says"), "{}", o.detail);

        let relied_on = "The ground rules live in `PROMPT.md`.";
        let o = evidence_for_path(&repo, "PROMPT.md", true, relied_on);
        assert_eq!(o.signal, Signal::Contradicts, "{}", o.detail);

        // Only the sentence naming the path counts: retiring something else
        // in the same paragraph excuses nothing.
        let other = "The old brief was retired. The ground rules live in `PROMPT.md`.";
        let o = evidence_for_path(&repo, "PROMPT.md", true, other);
        assert_eq!(o.signal, Signal::Contradicts, "{}", o.detail);

        // A word that merely contains one of the markers is not one.
        let unmoved = "The rules in `PROMPT.md` are unmoved.";
        let o = evidence_for_path(&repo, "PROMPT.md", true, unmoved);
        assert_eq!(o.signal, Signal::Contradicts, "{}", o.detail);
    }

    /// A version mentioned as history ("shipped in an older version") must
    /// never be marked stale just because a newer release exists now.
    #[test]
    fn an_older_version_is_only_stale_when_the_claim_asserts_its_current() {
        let dir = git_fixture();
        git_commit(dir.path(), "x");
        assert!(Command::new("git")
            .args(["tag", "v0.4.8"])
            .current_dir(dir.path())
            .status()
            .unwrap()
            .success());
        let newest = Repo::at(Some(dir.path().to_path_buf())).newest_tag();

        let historical = evidence_for_semver(
            &newest,
            "0.4.5",
            true,
            "`--contradictions` shipped in 0.4.5.",
        );
        assert_eq!(historical.signal, Signal::Unknown, "{}", historical.detail);

        let current = evidence_for_semver(&newest, "0.4.5", true, "Recall is at version 0.4.5.");
        assert_eq!(current.signal, Signal::Contradicts, "{}", current.detail);
    }

    #[test]
    fn semver_evidence_confirms_the_newest_tag() {
        let dir = git_fixture();
        git_commit(dir.path(), "x");
        assert!(Command::new("git")
            .args(["tag", "v0.4.8"])
            .current_dir(dir.path())
            .status()
            .unwrap()
            .success());
        let newest = Repo::at(Some(dir.path().to_path_buf())).newest_tag();
        let current = evidence_for_semver(&newest, "0.4.8", true, "Recall is at version 0.4.8.");
        assert_eq!(current.signal, Signal::Confirms, "{}", current.detail);
    }

    /// The blocker this pins against: none of these is a `git grep` option,
    /// whatever it looks like — `-e` makes each one an ordinary pattern,
    /// which is why every one of them correctly reads as "not found"
    /// rather than hanging on stdin, reading a file, opening a pager, or
    /// making `references` misreport "not a git repository".
    #[test]
    fn hostile_terms_are_never_interpreted_as_git_options() {
        let dir = git_fixture();
        std::fs::write(dir.path().join("code.rs"), "fn main() {}\n").unwrap();
        git_commit(dir.path(), "x");
        let repo = Repo::at(Some(dir.path().to_path_buf()));
        for hostile in [
            "-f-",
            "-fLICENSE",
            "--contradictions",
            "-O/bin/sh",
            "-x",
            "-h",
        ] {
            let result = repo.references(hostile);
            assert_eq!(
                result,
                Some(false),
                "hostile term {hostile:?} must read as not-found, not as a git option"
            );
        }
    }

    /// A flag this codebase actually uses is found — proving `references`
    /// can say a name exists at all, not just fail safe.
    #[test]
    fn a_flag_that_is_still_referenced_is_found() {
        let dir = git_fixture();
        std::fs::write(dir.path().join("code.rs"), "let flag = \"--keep-open\";\n").unwrap();
        git_commit(dir.path(), "x");
        let repo = Repo::at(Some(dir.path().to_path_buf()));
        assert_eq!(repo.references("--keep-open"), Some(true));
    }

    /// A name mentioned only in a Markdown file — documentation talking
    /// about something, not code using it — must not count as "still
    /// referenced", or every dead name this design exists to catch would
    /// read as still true because the note itself (or the ROADMAP, or
    /// history docs) says its name somewhere.
    #[test]
    fn a_name_mentioned_only_in_markdown_is_not_found() {
        let dir = git_fixture();
        std::fs::write(
            dir.path().join("notes.md"),
            "hooks/recall-pull used to exist\n",
        )
        .unwrap();
        git_commit(dir.path(), "x");
        let repo = Repo::at(Some(dir.path().to_path_buf()));
        assert_eq!(repo.references("recall-pull"), Some(false));
    }

    /// Absence of a code term is weak evidence: it must read `cant_tell`,
    /// never `stale`, however confidently `git grep` comes back empty.
    #[test]
    fn an_absent_code_term_is_cant_tell_never_stale() {
        let dir = git_fixture();
        git_commit(dir.path(), "x");
        let repo = Repo::at(Some(dir.path().to_path_buf()));
        let o = evidence_for_code(&repo, "never-existed-anywhere", true);
        assert_eq!(o.signal, Signal::Unknown, "{}", o.detail);
    }

    /// A bare filename in a note (what people actually write) still finds
    /// the real file, wherever it lives in the tree — this is the failure
    /// the design's own worked example depends on: `lib.sh` really lived at
    /// `hooks/lib.sh`.
    #[test]
    fn a_bare_filename_matches_the_real_file_in_a_subdirectory() {
        let dir = git_fixture();
        std::fs::create_dir_all(dir.path().join("hooks")).unwrap();
        std::fs::write(dir.path().join("hooks").join("lib.sh"), "echo hi\n").unwrap();
        git_commit(dir.path(), "add");
        let repo = Repo::at(Some(dir.path().to_path_buf()));
        assert!(
            repo.tracked("lib.sh"),
            "bare lib.sh should find hooks/lib.sh"
        );
        std::fs::remove_file(dir.path().join("hooks").join("lib.sh")).unwrap();
        git_commit(dir.path(), "remove");
        assert!(!repo.tracked("lib.sh"));
        assert!(
            repo.deleted("lib.sh").is_some(),
            "the deletion should still be found by name"
        );
    }

    /// A value that happens to quote a glob (`hooks/recall-*`) is matched
    /// literally, never expanded into every file under `hooks/`.
    #[test]
    fn a_quoted_glob_is_matched_literally_not_expanded() {
        let dir = git_fixture();
        std::fs::create_dir_all(dir.path().join("hooks")).unwrap();
        std::fs::write(dir.path().join("hooks").join("recall-pull"), "x\n").unwrap();
        git_commit(dir.path(), "add");
        let repo = Repo::at(Some(dir.path().to_path_buf()));
        assert!(
            !repo.tracked("hooks/recall-*"),
            "a literal glob-looking path must not match every file under hooks/"
        );
    }

    /// Every request a review makes goes through `sources`: `/health` and
    /// discovery at the configured server, inside `status`'s collection,
    /// and a host's discovery document with `--probe-hosts`. This file
    /// opens no connection of its own. The forbidden words are built at
    /// runtime so this assertion cannot trivially match itself.
    #[test]
    fn this_module_never_touches_the_network() {
        let src = include_str!("review.rs");
        let forbidden = [
            ["req", "west"].concat(),
            ["std::", "net::"].concat(),
            ["Tcp", "Stream"].concat(),
        ];
        for word in &forbidden {
            assert!(!src.contains(word.as_str()), "found {word:?} in review.rs");
        }
    }
}