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
//! `recall doctor` — the command that answers "why isn't this working",
//! and is allowed to say so with an exit code.
//!
//! `recall status` reports. This judges. The distinction earned itself: in
//! this repository's own cloud environment, the hooks were wired and the
//! binary installed, but `RECALL_URL` and `RECALL_TOKEN` were never set on
//! the environment. `recall pull` ran at every session start for a full day,
//! synced nothing, and exited `0` every time — correctly, because a hook
//! that fails a session is worse than one that does nothing. `recall status`
//! printed `(unset)` and also exited `0`. So nothing anywhere — no exit
//! code, no log line, no failing check — distinguished "never configured"
//! from "nothing new to sync", and a day's work went unsynced unnoticed.
//!
//! That is the gap this fills, and it is why the exit code is the feature
//! rather than the formatting. `status` keeps exiting `0`; it is
//! informational and scripts read its `--json`. Doctor carries the bad news.
//!
//! Every finding below is a reading of [`status::Report`], never a second
//! collection. A question worth asking is worth both commands knowing about.

use recall_hooks::config::Source;
use recall_hooks::{exit, ClientConfig};

use crate::project as proj;
use crate::status::{self, Report};
use crate::ui;

/// How much a finding matters, which is also the exit code's input.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Level {
    /// Working.
    Ok,
    /// Recall runs, but something is not doing what it looks like it does.
    /// Never fails the command: a laptop with no machine scope is not
    /// broken, and a doctor that exits non-zero on taste would stop being
    /// read.
    Warn,
    /// Memory is not syncing, or is syncing somewhere you did not ask for.
    Fail,
}

/// One answered question.
#[derive(Debug, serde::Serialize)]
pub struct Finding {
    /// How much it matters.
    pub level: Level,
    /// The short name of what was checked, e.g. `RECALL_URL`.
    pub check: &'static str,
    /// What was found.
    pub detail: String,
    /// What to do about it. Present on anything that is not `Ok`, because a
    /// finding a reader cannot act on is a finding that trains them to skip
    /// the output.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub fix: Option<String>,
}

fn ok(check: &'static str, detail: impl Into<String>) -> Finding {
    Finding {
        level: Level::Ok,
        check,
        detail: detail.into(),
        fix: None,
    }
}

fn warn(check: &'static str, detail: impl Into<String>, fix: impl Into<String>) -> Finding {
    Finding {
        level: Level::Warn,
        check,
        detail: detail.into(),
        fix: Some(fix.into()),
    }
}

fn fail(check: &'static str, detail: impl Into<String>, fix: impl Into<String>) -> Finding {
    Finding {
        level: Level::Fail,
        check,
        detail: detail.into(),
        fix: Some(fix.into()),
    }
}

/// Where a variable has to be set, which differs by environment in a way
/// that is not guessable and cost this project a day.
const WHERE_TO_SET: &str =
    "cloud environment: the \"Add/Edit cloud environment\" dialog; laptop: recall connect <url>";

/// Reads the report into findings, most fundamental first.
///
/// Ordered so the first `FAIL` is the one worth fixing first: there is no
/// point reporting an unreachable server above an unset URL, because the
/// second explains the first.
pub(crate) fn findings(rep: &Report) -> Vec<Finding> {
    let mut out = Vec::new();

    // ---- can it reach a server at all
    if rep.url_set {
        out.push(ok("RECALL_URL", source_detail(rep, rep.url_source)));
    } else {
        out.push(fail("RECALL_URL", "not set anywhere", WHERE_TO_SET));
    }

    if rep.token_set {
        out.push(ok("RECALL_TOKEN", source_detail(rep, rep.token_source)));
    } else if rep.device.is_some() {
        out.push(ok(
            "RECALL_TOKEN",
            "not needed, this machine signs its requests with its device key",
        ));
    } else if rep.authkey_set {
        out.push(ok(
            "RECALL_TOKEN",
            "not needed, RECALL_AUTHKEY enrols this session as a device",
        ));
    } else {
        out.push(fail("RECALL_TOKEN", "not set anywhere", WHERE_TO_SET));
    }

    credentials_findings(rep, &mut out);
    device_findings(rep, &mut out);

    // Only asked once there is somewhere to ask. Reporting "unreachable"
    // when no URL is set would be true and useless.
    if rep.url_set {
        match (&rep.server_error, &rep.git_commit) {
            (Some(err), _) => out.push(fail(
                "server",
                format!("unreachable: {err}"),
                "check RECALL_URL. A cloud environment also needs the domain under \
                 Allowed domains",
            )),
            (None, _) if rep.server_version.is_some() => out.push(ok(
                "server",
                format!(
                    "answered, {}{}",
                    rep.server_version.as_deref().unwrap_or_default(),
                    if rep.server_channel.as_deref() == Some("dev") {
                        " (not a release build)"
                    } else {
                        ""
                    }
                ),
            )),
            (None, Some(commit)) => out.push(ok("server", format!("answered, commit {commit}"))),
            (None, None) => out.push(ok("server", "answered")),
        }
        version_findings(rep, &mut out);
    }

    let quiet = worker_quiet(rep).filter(|_| rep.server_ok);
    if let Some(quiet) = quiet {
        // Before the CLI: what the worker last said about it is only as
        // current as the worker.
        out.push(warn(
            "merge",
            format!(
                "the merge worker has not asked for work in {} minutes, so conflicting \
                 edits wait in its queue unmerged, unless the server's own Claude CLI \
                 can merge them",
                quiet.whole_minutes()
            ),
            "on the server: docker logs recall-worker, and check it is running",
        ));
    } else if rep.server_ok && !rep.merge_ready && rep.merge_worker {
        out.push(warn(
            "merge",
            "the merge worker's Claude CLI is not logged in, so conflicting edits wait \
             in its queue unmerged",
            "on the server: docker exec -it -u node recall-worker claude setup-token",
        ));
    } else if rep.server_ok && !rep.merge_ready {
        out.push(warn(
            "merge",
            "the server's Claude CLI is not logged in, so conflicting edits use \
             last-write-wins",
            "on the server: docker exec -it -u node recall-server claude setup-token",
        ));
    }
    if rep.server_ok {
        queue_finding(rep, &mut out);
    }

    // ---- can Claude Code see the memory at all
    //
    // Unwired hooks are a problem in a project and nothing at all outside
    // one. Checking your connection from a home directory is an ordinary
    // thing to do, and the first version of this failed for it — which is
    // how a command teaches people to stop reading its output.
    match (rep.hooks_wired, rep.in_git_repo) {
        (true, _) => out.push(ok("hooks", "wired in .claude/settings.json")),
        (false, true) => out.push(fail(
            "hooks",
            "this project's .claude/settings.json has no Recall hooks",
            "recall init",
        )),
        (false, false) => out.push(ok("hooks", "not in a git repository")),
    }

    // Windows only: Claude Code runs hook commands through Git Bash there
    // and falls back to PowerShell without it, which cannot run the
    // bash-form command `recall init` writes at all — the hook silently does
    // nothing on every edit, and nothing else in this report would explain
    // why. Nothing to check on Unix, where the hook command runs directly.
    #[cfg(windows)]
    out.push(git_bash_finding());

    // `CLAUDE_CODE_REMOTE` answers the question that made this a permanent
    // warning in both directions: unset is correct on a laptop and means
    // Claude Code's auto-memory is off entirely in a remote session, where
    // Recall then has nothing to sync no matter what else is right.
    match (rep.remote_session, rep.remote_memory_dir_set) {
        (true, false) => out.push(fail(
            "CLAUDE_CODE_REMOTE_MEMORY_DIR",
            "not set, so auto-memory is off in this remote session",
            // The one value in the whole setup that cannot be reasoned out.
            "set it to /home/user/.claude on the cloud environment (not $HOME)",
        )),
        (true, true) => out.push(ok("CLAUDE_CODE_REMOTE_MEMORY_DIR", "set")),
        (false, true) => out.push(ok(
            "CLAUDE_CODE_REMOTE_MEMORY_DIR",
            "set, memory lives here instead of ~/.claude",
        )),
        (false, false) => out.push(ok(
            "CLAUDE_CODE_REMOTE_MEMORY_DIR",
            "not needed outside a remote session",
        )),
    }

    out.push(ok(
        "memory dir",
        format!("{} ({} files)", rep.memory_dir, rep.memory_files),
    ));

    offbox_finding(rep, &mut out);
    audit_finding(rep, &mut out);

    // ---- is anything quietly going nowhere
    reserved_findings(rep, &mut out);

    if let Some(mis) = &rep.miscased_dir {
        out.push(fail(
            "reserved directory",
            format!(
                "{}/ should be {}/ (case matters), so nothing under it syncs",
                mis.found, mis.reserved
            ),
            format!("rename {}/ to {}/", mis.found, mis.reserved),
        ));
    }

    for var in &rep.rejected_vars {
        out.push(fail(
            "rejected value",
            format!("{var} is set to a value Recall refused, so it did nothing"),
            format!("recall status names the file behind {var}"),
        ));
    }

    for file in &rep.unreadable_settings {
        out.push(fail(
            "settings file",
            format!("{file} is not readable JSON, so nothing it declares is in effect"),
            "fix the JSON, Claude Code cannot read it either".to_string(),
        ));
    }

    for ig in &rep.ignored_env {
        out.push(warn(
            "ignored value",
            format!(
                "{} is declared in {} but its value is not a string, so it was skipped",
                ig.name, ig.file
            ),
            "quote the value".to_string(),
        ));
    }

    out
}

/// Whether this machine is an enrolled device, and whether it should be.
///
/// Two warnings carry the move off the shared token (Part 2 of
/// `docs/design/handshake.md`): one while a machine that could enrol has
/// not, and one while a machine that has still holds the token it no longer
/// sends. Neither fails the command: the token still works.
fn device_findings(rep: &Report, out: &mut Vec<Finding>) {
    let key_file = rep.device_file.as_deref().unwrap_or("~/.recall/device.key");
    // A failure rather than a warning: the hooks send nothing at all while
    // it lasts, not even `RECALL_TOKEN` in the key's place.
    if let Some(err) = &rep.device_error {
        out.push(fail(
            "device key",
            format!("{err}, so this machine sends nothing to the server"),
            "move it aside and run recall connect to enrol again",
        ));
    }
    if rep.device_file_exposed {
        out.push(warn(
            "device key",
            format!("{key_file} is readable by other users"),
            format!("chmod 600 {key_file}"),
        ));
    }

    let Some(d) = &rep.device else {
        match (rep.server_devices, rep.remote_session) {
            (Some(true), true) if rep.authkey_set => out.push(warn(
                "device",
                "RECALL_AUTHKEY is set, but this session has not enrolled yet",
                "recall pull enrols it, and says why when it cannot",
            )),
            (Some(true), true) if rep.token_set => out.push(warn(
                "device",
                "this session uses the shared RECALL_TOKEN",
                "on an admin device: recall authkey create --tag cloud --expires 90d, \
                 then set RECALL_AUTHKEY on the cloud environment and remove RECALL_TOKEN",
            )),
            (Some(true), false) if rep.token_set => out.push(warn(
                "device",
                "not enrolled, so this machine still uses the shared RECALL_TOKEN",
                "recall connect",
            )),
            (Some(false), _) => out.push(ok(
                "device",
                "not available, the server does not enrol devices",
            )),
            _ => {}
        }
        return;
    };

    let what = format!(
        "{} ({}{})",
        d.name,
        d.scope,
        if d.ephemeral { ", ephemeral" } else { "" }
    );
    let reenroll = if rep.remote_session && rep.authkey_set {
        "the next session start enrols again with RECALL_AUTHKEY"
    } else {
        "recall connect"
    };
    match d.confirmed {
        Some(true) => out.push(ok(
            "device",
            format!(
                "enrolled as {what}, key in {} ({})",
                d.key_file,
                key_protection(&d.key_file)
            ),
        )),
        Some(false) if d.gone => out.push(fail(
            "device",
            format!(
                "the server no longer accepts this machine's device {}: {}",
                d.name,
                d.check_error.as_deref().unwrap_or("unknown device")
            ),
            reenroll,
        )),
        Some(false) if rep.server_devices == Some(false) => out.push(fail(
            "device",
            format!(
                "this machine signs its requests as {}, and the server does not accept \
                 device signatures",
                d.name
            ),
            "upgrade the server to 0.4.1 or later",
        )),
        Some(false) => out.push(warn(
            "device",
            format!(
                "{what}: the server did not confirm it: {}",
                d.check_error.as_deref().unwrap_or("no answer")
            ),
            "run recall doctor again; if it persists, recall connect",
        )),
        None => out.push(ok(
            "device",
            format!("enrolled as {what}, key in {} (not checked)", d.key_file),
        )),
    }

    // The token is never sent while there is a device key, so a copy of it
    // left on the machine protects nothing and can still leak.
    if rep.token_set {
        let (detail, fix) = match rep.token_source {
            Source::CredentialsFile => (
                format!(
                    "RECALL_TOKEN is still saved in {}, though this machine never sends it",
                    rep.credentials_file
                        .as_deref()
                        .unwrap_or("the credentials file")
                ),
                "recall connect removes it".to_string(),
            ),
            _ => {
                let from = rep
                    .declared_env
                    .iter()
                    .find(|d| d.name == "RECALL_TOKEN")
                    .map(|d| d.file.clone())
                    .unwrap_or_else(|| {
                        if rep.remote_session {
                            "the cloud environment's variables".to_string()
                        } else {
                            "your shell profile".to_string()
                        }
                    });
                (
                    "RECALL_TOKEN is still set, though this machine never sends it".to_string(),
                    format!("remove RECALL_TOKEN from {from}"),
                )
            }
        };
        out.push(warn("shared token", detail, fix));
    }
}

/// How the device key file is protected, said plainly: a file, and what
/// keeps others out of it on this platform. Not the OS keychain, and the
/// report does not pretend otherwise; `recall_hooks::home` says why.
#[cfg(unix)]
fn key_protection(_key_file: &str) -> &'static str {
    "a file readable by you only"
}

/// On Windows, what keeps others out is the user profile's access list,
/// which covers only what is inside the profile: a `RECALL_HOME` elsewhere
/// gets whatever that directory allows, which nothing here reads.
#[cfg(not(unix))]
fn key_protection(key_file: &str) -> &'static str {
    let profile = std::env::var("USERPROFILE").unwrap_or_default();
    if recall_hooks::home::inside_profile(std::path::Path::new(key_file), &profile) {
        "a file in your user profile, which only you and administrators can read"
    } else {
        "a file outside your user profile, so who else can read it is up to that directory"
    }
}

/// Whether this client and the server can talk at all, from the server's
/// discovery document. Silent against a server too old to publish one:
/// such a server speaks protocol 1, which is what this client speaks.
fn version_findings(rep: &Report, out: &mut Vec<Finding>) {
    if !rep.server_protocols.is_empty() && !rep.server_protocols.contains(&recall_wire::PROTOCOL) {
        out.push(fail(
            "version",
            format!(
                "the server speaks protocol {:?} and this client speaks {}",
                rep.server_protocols,
                recall_wire::PROTOCOL
            ),
            "upgrade whichever side is older",
        ));
    }
    let too_old = rep.min_client.as_deref().and_then(|min| {
        let min_v = recall_wire::discovery::Version::parse(min)?;
        let mine = recall_wire::discovery::Version::parse(&rep.client_version)?;
        (mine < min_v).then(|| min.to_string())
    });
    if let Some(min) = too_old {
        out.push(fail(
            "version",
            format!(
                "this client is {} and the server needs at least {min}",
                rep.client_version
            ),
            "upgrade recall: brew upgrade recall, or npm install -g @pimlabs/recall",
        ));
    }
}

/// Whether Claude Code has a Git Bash to run hook commands through.
///
/// Checked the same way Claude Code itself is documented to resolve it:
/// `CLAUDE_CODE_GIT_BASH_PATH` first, then `bash.exe` actually belonging to
/// Git for Windows on `PATH` (not WSL's `System32\bash.exe`, which answers to
/// the same name but is a different thing), then the two locations Git for
/// Windows' own installer offers by default. **Not verified against a real
/// Windows Claude Code install** — the env var name and the fallback order
/// are the best-documented guess, not a confirmed contract. See
/// docs/reference/install.md's Windows section.
#[cfg(windows)]
fn git_bash_finding() -> Finding {
    if git_bash_available() {
        ok("Git Bash", "found")
    } else {
        fail(
            "Git Bash",
            "not found, so Claude Code cannot run the hooks recall init writes \
             (it falls back to PowerShell, which the committed hook command \
             cannot run)",
            "install Git for Windows: https://git-scm.com/download/win",
        )
    }
}

#[cfg(windows)]
fn git_bash_available() -> bool {
    if let Ok(path) = std::env::var("CLAUDE_CODE_GIT_BASH_PATH") {
        if !path.is_empty() && std::path::Path::new(&path).is_file() {
            return true;
        }
    }
    if path_bash_is_git_bash() {
        return true;
    }
    // Git for Windows' installer offers to skip adding itself to PATH, so a
    // working install can still miss the check above.
    for candidate in [
        r"C:\Program Files\Git\bin\bash.exe",
        r"C:\Program Files (x86)\Git\bin\bash.exe",
    ] {
        if std::path::Path::new(candidate).is_file() {
            return true;
        }
    }
    false
}

/// `bash.exe` on `PATH` might be WSL's launcher (`System32\bash.exe`) rather
/// than Git for Windows' — same name, and WSL's answers to `bash -c` too, so
/// it cannot be told apart by running it. Only a path that plainly names a
/// Git installation is trusted.
#[cfg(windows)]
fn path_bash_is_git_bash() -> bool {
    std::env::var_os("PATH")
        .map(|paths| {
            std::env::split_paths(&paths).any(|dir| {
                dir.join("bash.exe").is_file()
                    && dir.to_string_lossy().to_ascii_lowercase().contains("git")
            })
        })
        .unwrap_or(false)
}

/// Where a value came from, in the words a finding uses.
fn source_detail(rep: &Report, source: Source) -> String {
    match source {
        Source::CredentialsFile => format!(
            "saved in {}",
            rep.credentials_file
                .as_deref()
                .unwrap_or("the credentials file")
        ),
        Source::ConfigFile => format!(
            "saved in {}",
            rep.config_file.as_deref().unwrap_or("the config file")
        ),
        _ => "set".to_string(),
    }
}

/// Where the token lives, which matters as much as whether it is set.
///
/// The warning speaks on a laptop and never in a remote session. A cloud
/// environment's variables are a secret store and the right place for the
/// token there; a shell profile is a dotfile that every subprocess inherits
/// from, that gets committed to dotfiles repositories, and whose `export`
/// line sits in shell history. The same `CLAUDE_CODE_REMOTE` signal decides
/// the memory-dir check below.
fn credentials_findings(rep: &Report, out: &mut Vec<Finding>) {
    // With a device key the token is never sent, and `device_findings`
    // says so instead.
    if rep.token_source == Source::Environment && !rep.remote_session && rep.device.is_none() {
        // A settings file can be named because it was read. The shell
        // cannot: by the time a process sees a variable, which profile
        // exported it is gone, and naming a guess would send someone to
        // edit the wrong file and believe they were done.
        let (detail, remove_from) = match rep.declared_env.iter().find(|d| d.name == "RECALL_TOKEN")
        {
            Some(d) => (
                format!("RECALL_TOKEN is set in {}, in plain text", d.file),
                d.file.clone(),
            ),
            None => (
                "RECALL_TOKEN is exported by your shell, so every program you start \
                 can read it"
                    .to_string(),
                "your shell profile".to_string(),
            ),
        };
        out.push(warn(
            "token storage",
            detail,
            format!(
                "run recall connect to save it in ~/.recall/credentials.toml, then \
                 remove RECALL_TOKEN from {remove_from}"
            ),
        ));
    }

    let config_file = rep
        .config_file
        .as_deref()
        .unwrap_or("~/.recall/config.toml");
    for problem in &rep.config_problems {
        out.push(warn(
            "config file",
            problem.clone(),
            format!("edit {config_file}"),
        ));
    }
    // The environment wins over the file, deliberately — but on a laptop
    // that has run `recall connect`, a different value left in the shell is
    // almost always a leftover, and it silently decides which machine this
    // is.
    for o in &rep.overridden {
        let from = rep
            .declared_env
            .iter()
            .find(|d| d.name == o.variable)
            .map(|d| d.file.clone())
            .unwrap_or_else(|| "your shell profile".to_string());
        out.push(warn(
            "config overridden",
            format!(
                "{}={} wins over {} = {:?} in {config_file}",
                o.variable, o.environment, o.setting, o.config
            ),
            format!(
                "remove {} from {from}, or change {} to match",
                o.variable, o.setting
            ),
        ));
    }

    if let Some(err) = &rep.credentials_error {
        out.push(warn(
            "credentials file",
            format!("{err}, so nothing in it is in effect"),
            "move it aside and run recall connect again",
        ));
    }

    if rep.credentials_exposed {
        let file = rep
            .credentials_file
            .as_deref()
            .unwrap_or("~/.recall/credentials.toml");
        out.push(warn(
            "credentials file",
            format!("{file} is readable by other users"),
            format!("chmod 600 {file}"),
        ));
    }
}

/// How long an off-box copy may be missing before it is worth saying so.
///
/// Generous against the cadence `deploy/README.md` recommends — six-hourly,
/// so eight runs would have to fail before this speaks. That asymmetry is
/// deliberate: a false alarm here costs the credibility of every other line
/// in the report, and a real stoppage stays true for days.
const OFFBOX_STALE_AFTER: time::Duration = time::Duration::days(2);

/// Whether a copy has recently reached somewhere the loss of the server does
/// not reach.
///
/// Nothing watched this before. The server's own snapshots surface as
/// `last_backup_at` and go stale visibly, but they sit on the disk they
/// protect; the copy that survives losing the machine ran from cron, and a
/// cron job that dies mails its error to a mailbox nobody reads. A transient
/// 403 from the bucket looked exactly like a quiet night.
///
/// Silence when no stamp exists at all, rather than a standing complaint: a
/// deployment with no off-box backup configured is not broken, and warning
/// it forever is how a report teaches people to skip it.
fn offbox_finding(rep: &Report, out: &mut Vec<Finding>) {
    let Some(stamp) = rep.last_offbox_at.as_deref() else {
        return;
    };

    let Some(age) = age_of(stamp) else {
        out.push(warn(
            "off-box backup",
            format!("the server reported a stamp this cannot read: {stamp}"),
            "expected the API's timestamp format, e.g. 2026-09-22T00:17:03.000Z",
        ));
        return;
    };

    if age > OFFBOX_STALE_AFTER {
        out.push(warn(
            "off-box backup",
            format!(
                "last verified copy is {} days old ({stamp}), anything newer exists \
                 only on the server",
                age.whole_days()
            ),
            "on the server: check the cron job's mail, then run \
             RECALL_BACKUP_REMOTE=... ./deploy/backup-offbox.sh by hand",
        ));
    } else {
        out.push(ok("off-box backup", format!("verified {stamp}")));
    }
}

/// Whether the server's audit log still extends every checkpoint this
/// machine saved: the plan's "`recall doctor` asks for a consistency proof
/// from it to the current tree and fails loudly without one".
///
/// It fails on a rewrite found, now or earlier, until `recall audit
/// reset`; on an `audit.json` it cannot read, which may hold the only
/// record of one; on a server that answered without a proof, or no longer
/// keeps the log it was witnessed keeping; on checkpoints dropped unchecked;
/// and, while anything is saved, on checks that have gone unanswered for
/// too long (the oldest waiting [`recall_hooks::audit::STALE_DAYS`] days,
/// no check finished in as many, or
/// [`recall_hooks::audit::UNANSWERED_LIMIT`] checks in a row). A server
/// that did not answer this once only warns, and so does one that refused
/// this machine's credential, and checkpoints that were not checked this
/// time: nothing about the log follows from any of those, yet.
fn audit_finding(rep: &Report, out: &mut Vec<Finding>) {
    use recall_hooks::audit::{STALE_DAYS, UNANSWERED_LIMIT};
    const CHECK: &str = "audit log";
    let Some(audit) = &rep.audit else {
        return;
    };
    if let Some(found) = &audit.inconsistent {
        let unsaved = match &audit.unsaved {
            Some(why) => format!(" (and it could not be written into audit.json: {why})"),
            None => String::new(),
        };
        out.push(fail(
            CHECK,
            format!(
                "the server's log no longer extends a checkpoint saved here (found {}): {}{unsaved}",
                found.found_at, found.detail
            ),
            crate::audit::AFTER_A_REWRITE,
        ));
        return;
    }
    if let Some(why) = &audit.file_error {
        out.push(fail(
            CHECK,
            format!(
                "{why}; it may hold the only record of a rewrite, so nothing is checked or \
                 saved until it can be read"
            ),
            format!(
                "look at {} first; move it aside only once you know what it held",
                audit.file
            ),
        ));
        return;
    }
    if let Some(why) = &audit.unproven {
        out.push(fail(
            CHECK,
            format!("the server did not prove its log extends the checkpoints saved here: {why}"),
            "recall audit verify; if it persists, recall audit export -o audit.jsonl and \
             recall audit verify audit.jsonl",
        ));
        return;
    }
    if audit.dropped > 0 {
        out.push(fail(
            CHECK,
            format!(
                "{} checkpoint(s) were dropped before they were checked, a gap a rewrite could \
                 go unseen in",
                audit.dropped
            ),
            "recall audit verify checks the rest; recall audit reset once you have decided \
             to trust the log as it is",
        ));
        return;
    }
    match (audit.server_log, audit.saved()) {
        (Some(false), 0) => {
            out.push(ok(CHECK, "not kept by this server (older than 0.4.2)"));
            return;
        }
        (Some(false), saved) => {
            out.push(fail(
                CHECK,
                format!(
                    "the server keeps no audit log, and this machine saved {saved} \
                     checkpoint(s) of one: a server that went back to before 0.4.2 lost it"
                ),
                crate::audit::AFTER_A_REWRITE,
            ));
            return;
        }
        _ => {}
    }
    // How long, when that is a week or more. A stamp more than a day ahead
    // of this clock was written under one set wrong: it would never grow a
    // week old, so it counts as stale rather than as recent.
    let stale = |at: Option<&str>| {
        let age = at.and_then(age_of)?;
        if age < -time::Duration::days(1) {
            return Some(
                "an unknown time (it is stamped in the future: a clock was wrong)".to_string(),
            );
        }
        (age >= time::Duration::days(STALE_DAYS)).then(|| format!("{} days", age.whole_days()))
    };
    if let Some(waited) = stale(audit.unchecked_since.as_deref()) {
        out.push(fail(
            CHECK,
            format!(
                "{} checkpoint(s) saved here have waited {waited} to be checked, the oldest \
                 since {}",
                audit.unchecked,
                audit.unchecked_since.as_deref().unwrap_or_default()
            ),
            "recall audit verify; a server that never answers the proofs is not proving its \
             log",
        ));
        return;
    }
    // However the checks were cut short (unanswered, refused, preempted,
    // or never run for want of a credential), a week without one finishing
    // is a log not proven for a week.
    let unproven_for = stale(audit.last_proven_at.as_deref());
    if let Some(age) = unproven_for.filter(|_| audit.saved() > 0) {
        out.push(fail(
            CHECK,
            format!(
                "no check of the server's log has finished in {age}, the last on {}; {} \
                 checkpoint(s) are saved here",
                audit.last_proven_at.as_deref().unwrap_or_default(),
                audit.saved()
            ),
            "recall audit verify; a server that never answers the proofs is not proving its \
             log",
        ));
        return;
    }
    if audit.saved() > 0 && audit.unanswered >= UNANSWERED_LIMIT {
        out.push(fail(
            CHECK,
            format!(
                "the server has left the last {} checks of its log unanswered",
                audit.unanswered
            ),
            "recall audit verify; a server that never answers the proofs is not proving its \
             log",
        ));
        return;
    }
    if let (Some(err), true) = (&audit.error, audit.refused) {
        out.push(warn(
            CHECK,
            format!(
                "the server refused this machine's credential for its audit log ({err}): the \
                 device may have been revoked, or not be allowed the audit routes; {} \
                 checkpoint(s) saved here were not checked",
                audit.saved()
            ),
            "recall status says whether this device is still enrolled; recall connect enrols \
             it again",
        ));
    } else if let Some(err) = &audit.error {
        out.push(warn(
            CHECK,
            format!(
                "could not check the {} checkpoint(s) saved here: {err}",
                audit.saved()
            ),
            "recall audit verify, once the server answers",
        ));
    } else if audit.extends == Some(true) {
        out.push(ok(
            CHECK,
            format!(
                "extends every checkpoint saved here ({} kept, newest {})",
                audit.checkpoints,
                audit.newest.as_deref().unwrap_or("none")
            ),
        ));
    } else if audit.saved() > 0 {
        out.push(warn(
            CHECK,
            format!(
                "{} checkpoint(s) saved here, and none was checked this time",
                audit.saved()
            ),
            "recall audit verify",
        ));
    }
}

/// How long the oldest merge may wait before it is worth saying so. A
/// worker drains a job within seconds of the push; an hour means it is not
/// running, or cannot merge.
const QUEUE_STALE_AFTER: time::Duration = time::Duration::hours(1);

/// How long a merge worker may go without asking for work before it is
/// worth saying so. A running one asks at least every half minute.
const WORKER_QUIET_AFTER: time::Duration = time::Duration::minutes(2);

/// How long the merge worker has gone without asking for work, when that is
/// long enough to say so: [`None`] without a worker, or with one that asks.
pub(crate) fn worker_quiet(rep: &Report) -> Option<time::Duration> {
    if !rep.merge_worker {
        return None;
    }
    rep.merge_worker_seen_at
        .as_deref()
        .and_then(age_of)
        .filter(|quiet| *quiet >= WORKER_QUIET_AFTER)
}

/// The merge worker's queue, when there is a worker: silent while it
/// drains, loud once the oldest job has waited an hour, the way a merge
/// that degrades to last-write-wins is made visible rather than silent.
fn queue_finding(rep: &Report, out: &mut Vec<Finding>) {
    let Some(q) = &rep.merge_queue else {
        return;
    };
    let waited = q.oldest_queued_at.as_deref().and_then(age_of);
    match waited {
        Some(age) if age >= QUEUE_STALE_AFTER => out.push(warn(
            "merge queue",
            format!(
                "{} merge{} waiting, the oldest for {} minutes; pushes still land, \
                 unmerged, until the worker takes them",
                q.queued,
                if q.queued == 1 { "" } else { "s" },
                age.whole_minutes()
            ),
            "on the server: docker logs recall-worker, and check it is running",
        )),
        _ => out.push(ok(
            "merge queue",
            match q.queued {
                0 => "nothing waiting".to_string(),
                n => format!("{n} waiting"),
            },
        )),
    }
    // A failed merge left the newest push standing and kept the merge in
    // its job, where nothing retries it by itself.
    if q.failed > 0 {
        out.push(warn(
            "failed merges",
            format!(
                "{} merge{} failed; for each, the newest push stands and the merge is kept \
                 in its job",
                q.failed,
                if q.failed == 1 { "" } else { "s" },
            ),
            "list them with GET /v1/jobs?state=failed and retry one with \
             POST /v1/jobs/{id}/retry, both with the operator token",
        ));
    }
}

/// How long ago a timestamp in the API's format was.
///
/// [`None`] rather than a guess when it cannot be parsed — a report that
/// invents an age is worse than one that admits it cannot read the value.
pub(crate) fn age_of(stamp: &str) -> Option<time::Duration> {
    let fmt = time::macros::format_description!(
        "[year]-[month]-[day]T[hour]:[minute]:[second].[subsecond digits:3]Z"
    );
    let at = time::PrimitiveDateTime::parse(stamp, &fmt)
        .ok()?
        .assume_utc();
    Some(time::OffsetDateTime::now_utc() - at)
}

/// The two reserved scopes, asked the same two questions each.
///
/// Both questions exist because both have already been shipped wrong: files
/// under a scope that is switched off go nowhere, and files under one that
/// is on are still never read unless `MEMORY.md` links them.
fn reserved_findings(rep: &Report, out: &mut Vec<Finding>) {
    let scopes: [(&'static str, &'static str, &Option<String>, usize, bool); 2] = [
        (
            "global scope",
            "RECALL_GLOBAL_KEY",
            &rep.global_key,
            rep.global_files,
            rep.global_linked,
        ),
        (
            "machine scope",
            "RECALL_MACHINE_KEY",
            &rep.machine_key,
            rep.machine_files,
            rep.machine_linked,
        ),
    ];

    for (name, var, key, files, linked) in scopes {
        match key {
            // Off with files sitting under it: they are not filed under the
            // project either, so they sync nowhere at all, and silently.
            None if files > 0 => out.push(warn(
                name,
                format!("off, but {files} file(s) are on disk under it and sync nowhere"),
                format!("set {var}, or move the files out"),
            )),
            None => out.push(ok(name, "off")),
            Some(k) if files > 0 && !linked => out.push(fail(
                name,
                format!(
                    "{k}: {files} file(s) synced, but MEMORY.md links none of them, so \
                     Claude Code never reads them"
                ),
                "recall pull".to_string(),
            )),
            Some(k) => out.push(ok(name, format!("{k} ({files} files)"))),
        }
    }
}

/// Collects, judges, prints, and exits accordingly.
pub async fn run(as_json: bool) -> anyhow::Result<i32> {
    let here = proj::resolve();
    let cfg = here.config();
    let rep = status::collect(&here, &cfg).await;
    let found = findings(&rep);

    if as_json {
        println!("{}", serde_json::to_string_pretty(&found)?);
    } else {
        print_text(&cfg, &rep, &found);
    }
    Ok(verdict(&found))
}

/// [`exit::CONFIG`] on any failure — "a misconfiguration only the user can
/// fix", which is exactly what every `Fail` above is.
///
/// Warnings never reach this. A command that exits non-zero over a scope
/// someone deliberately left off is a command that gets `|| true` appended
/// to it, and then it is not checking anything.
pub(crate) fn verdict(found: &[Finding]) -> i32 {
    if found.iter().any(|f| f.level == Level::Fail) {
        exit::CONFIG
    } else {
        exit::OK
    }
}

/// The groups a report is read in, in order. A check belongs to the first
/// group that names it; anything unlisted lands in the last, so a check
/// added later is never silently left out of the report.
const SECTIONS: &[(&str, &[&str])] = &[
    (
        "Connection",
        &[
            "RECALL_URL",
            "RECALL_TOKEN",
            "server",
            "version",
            "merge",
            "merge queue",
            "failed merges",
            "token storage",
            "credentials file",
            "device",
            "device key",
            "shared token",
            "config file",
            "config overridden",
        ],
    ),
    (
        "This project",
        &[
            "hooks",
            "Git Bash",
            "memory dir",
            "CLAUDE_CODE_REMOTE_MEMORY_DIR",
            "settings file",
            "ignored value",
            "rejected value",
            "reserved directory",
        ],
    ),
    ("Scopes", &["global scope", "machine scope"]),
    ("Backup", &["off-box backup"]),
    ("History", &["audit log"]),
];

const OTHER: &str = "Other";

fn section_of(check: &str) -> &'static str {
    SECTIONS
        .iter()
        .find(|(_, checks)| checks.contains(&check))
        .map(|(name, _)| *name)
        .unwrap_or(OTHER)
}

/// How a finding is marked. An `ok` that describes something switched off
/// or not applicable is quiet rather than green: "global scope: off" is not
/// an achievement, and marking it like one dilutes the marks that are.
fn tone_of(f: &Finding) -> ui::Tone {
    match f.level {
        Level::Fail => ui::Tone::Bad,
        Level::Warn => ui::Tone::Warn,
        Level::Ok
            if f.detail == "off"
                || f.detail.starts_with("not needed")
                || f.detail.starts_with("not available")
                || f.detail.starts_with("not in a git repository")
                || f.detail.starts_with("not kept by this server") =>
        {
            ui::Tone::Quiet
        }
        Level::Ok => ui::Tone::Good,
    }
}

fn print_text(cfg: &ClientConfig, rep: &Report, found: &[Finding]) {
    ui::title("recall doctor", &status::about(cfg));

    let names = SECTIONS.iter().map(|(n, _)| *n).chain([OTHER]);
    for name in names {
        let items: Vec<&Finding> = found
            .iter()
            .filter(|f| section_of(f.check) == name)
            .collect();
        if items.is_empty() {
            continue;
        }
        let about = if name == "This project" {
            rep.project_key.as_str()
        } else {
            ""
        };
        ui::section(name, about);
        // Aligned within the section rather than across the report: one
        // long name, `CLAUDE_CODE_REMOTE_MEMORY_DIR`, would otherwise push
        // every detail in every section thirty columns to the right.
        let width = items.iter().map(|f| f.check.len()).max().unwrap_or(0);
        for f in items {
            ui::check_fitted(
                tone_of(f),
                f.check,
                width,
                &shown(rep, &f.detail),
                f.fix.as_deref().map(|fix| shown(rep, fix)).as_deref(),
            );
        }
    }

    let fails = found.iter().filter(|f| f.level == Level::Fail).count();
    let warns = found.iter().filter(|f| f.level == Level::Warn).count();
    match (fails, warns) {
        (0, 0) => ui::verdict(ui::Tone::Good, "Everything checks out."),
        // Named plainly, because the whole point is that this state used to
        // look identical to a healthy one.
        (0, w) => ui::verdict(
            ui::Tone::Warn,
            &format!(
                "Nothing broken. {w} {} worth a look.",
                if w == 1 { "thing" } else { "things" }
            ),
        ),
        (f, _) => ui::verdict(
            ui::Tone::Bad,
            &format!(
                "{f} {}. {}",
                if f == 1 { "problem" } else { "problems" },
                if cfg.url.is_empty() {
                    "Nothing syncs here."
                } else {
                    "Some of it is not syncing."
                }
            ),
        ),
    }
}

/// A finding's text as a person reads it: home as `~`, and the audit
/// checkpoint and the server's commit cut short. The findings themselves,
/// and so `--json`, keep every value whole.
fn shown(rep: &Report, text: &str) -> String {
    let mut text = ui::tilde(text);
    if let Some(newest) = rep.audit.as_ref().and_then(|a| a.newest.as_deref()) {
        text = text.replace(newest, &status::short_checkpoint(newest));
    }
    if let Some(commit) = rep.git_commit.as_deref().filter(|c| !c.is_empty()) {
        text = text.replace(commit, &status::short_commit(commit));
    }
    text
}

#[cfg(test)]
pub(crate) mod tests {
    use super::*;
    use crate::status::{KeySource, MiscasedDir};

    /// Everything configured and working, for a test to break one thing in.
    ///
    /// Built healthy rather than empty on purpose: a fixture that starts
    /// broken makes it far too easy to write a test that passes because of
    /// a failure it was not looking at.
    pub(crate) fn healthy() -> Report {
        Report {
            project: "/w/app".into(),
            project_key: "acme/app".into(),
            project_key_source: KeySource::Remote,
            memory_dir: "/w/memory".into(),
            memory_files: 4,
            hooks_wired: true,
            // A wired project on a laptop — the ordinary case, and the one
            // where both of the checks below used to be wrong.
            in_git_repo: true,
            remote_session: false,
            declared_env: Vec::new(),
            ignored_env: Vec::new(),
            unreadable_settings: Vec::new(),
            global_key: None,
            rejected_vars: Vec::new(),
            global_files: 0,
            machine_key: None,
            machine_files: 0,
            machine_linked: false,
            miscased_dir: None,
            global_linked: false,
            remote_memory_dir_set: true,
            url_set: true,
            token_set: true,
            // Saved by `recall connect` — the setup that should raise
            // nothing at all.
            url_source: Source::ConfigFile,
            token_source: Source::CredentialsFile,
            credentials_file: Some("/h/.recall/credentials.json".into()),
            credentials_error: None,
            credentials_exposed: false,
            auth: "bearer",
            device: None,
            device_file: Some("/h/.recall/device.key".into()),
            device_error: None,
            device_file_exposed: false,
            authkey_set: false,
            // A server too old to say: the case that must raise nothing.
            server_devices: None,
            config_file: Some("/h/.recall/config.toml".into()),
            machine_source: Source::Unset,
            config_problems: Vec::new(),
            overridden: Vec::new(),
            server_ok: true,
            server_error: None,
            git_commit: Some("a1b2c3d".into()),
            server_version: Some("0.3.2".into()),
            server_channel: Some("release".into()),
            server_protocols: vec![1],
            min_client: Some("0.1.0".into()),
            client_version: "0.3.3".into(),
            merge_ready: true,
            merge_worker: false,
            merge_queue: None,
            merge_worker_seen_at: None,
            synced_files: 4,
            last_synced_at: None,
            // No stamp: the ordinary case for a deployment with no off-box
            // backup, and the one that must stay silent.
            last_offbox_at: None,
            audit: Some(crate::status::AuditReport {
                file: "/home/me/.recall/audit.json".into(),
                checkpoints: 3,
                newest: Some("1042 CsUYapGGPo4dkMgIAUqom/Xajj7h2fB2MPA3j2jxq2I=".into()),
                server_log: Some(true),
                extends: Some(true),
                ..Default::default()
            }),
            health: None,
            discovery: None,
        }
    }

    fn find<'a>(found: &'a [Finding], check: &str) -> Option<&'a Finding> {
        found.iter().find(|f| f.check == check)
    }

    #[test]
    fn a_healthy_setup_exits_zero_and_flags_nothing() {
        let found = findings(&healthy());
        assert_eq!(verdict(&found), exit::OK);
        assert!(
            found.iter().all(|f| f.level == Level::Ok),
            "{:?}",
            found
                .iter()
                .filter(|f| f.level != Level::Ok)
                .collect::<Vec<_>>()
        );
    }

    /// The case that cost a day: hooks wired, binary installed, nothing set.
    #[test]
    fn an_unconfigured_environment_fails_rather_than_looking_idle() {
        let mut rep = healthy();
        rep.url_set = false;
        rep.token_set = false;
        rep.server_ok = false;
        rep.git_commit = None;

        let found = findings(&rep);

        assert_eq!(find(&found, "RECALL_URL").unwrap().level, Level::Fail);
        assert_eq!(find(&found, "RECALL_TOKEN").unwrap().level, Level::Fail);
        assert_eq!(verdict(&found), exit::CONFIG);
    }

    /// With no URL there is nothing to be unreachable, and saying so anyway
    /// buries the finding that explains it.
    #[test]
    fn a_client_older_than_the_server_accepts_fails_and_says_to_upgrade() {
        let mut r = healthy();
        r.min_client = Some("0.4.0".into());
        let found = findings(&r);
        let v = found
            .iter()
            .find(|f| f.check == "version")
            .expect("a version finding");
        assert_eq!(v.level, Level::Fail);
        assert!(
            v.detail.contains("0.3.3") && v.detail.contains("0.4.0"),
            "{}",
            v.detail
        );
    }

    #[test]
    fn a_protocol_the_client_does_not_speak_fails() {
        let mut r = healthy();
        r.server_protocols = vec![2];
        let found = findings(&r);
        assert!(found
            .iter()
            .any(|f| f.check == "version" && f.level == Level::Fail));
    }

    /// A server too old to publish a discovery document says nothing about
    /// versions, and that is not a problem: it speaks protocol 1.
    #[test]
    fn a_server_without_discovery_raises_no_version_finding() {
        let mut r = healthy();
        r.server_version = None;
        r.server_channel = None;
        r.server_protocols = Vec::new();
        r.min_client = None;
        let found = findings(&r);
        assert!(!found.iter().any(|f| f.check == "version"));
        let server = found.iter().find(|f| f.check == "server").unwrap();
        assert!(server.detail.contains("a1b2c3d"), "{}", server.detail);
    }

    #[test]
    fn a_dev_server_is_named_as_one() {
        let mut r = healthy();
        r.server_version = Some("0.3.3-dev+ge100cfd".into());
        r.server_channel = Some("dev".into());
        let server = findings(&r)
            .into_iter()
            .find(|f| f.check == "server")
            .unwrap();
        assert!(
            server.detail.contains("not a release build"),
            "{}",
            server.detail
        );
    }

    #[test]
    fn the_server_is_not_reported_on_when_there_is_no_url() {
        let mut rep = healthy();
        rep.url_set = false;
        rep.server_ok = false;

        assert!(find(&findings(&rep), "server").is_none());
    }

    /// A token in the environment on a laptop is the thing `recall connect`
    /// exists to replace, so doctor says so — once, as a warning, and with
    /// the command that fixes it.
    #[test]
    fn a_shell_token_on_a_laptop_is_a_warning_that_names_the_fix() {
        let mut rep = healthy();
        rep.token_source = Source::Environment;

        let found = findings(&rep);
        let f = find(&found, "token storage").expect("a shell token is worth a word");

        assert_eq!(f.level, Level::Warn);
        assert!(f.detail.contains("shell"), "{}", f.detail);
        assert!(f.fix.as_deref().unwrap().contains("recall connect"));
        assert_eq!(
            verdict(&found),
            exit::OK,
            "a warning never fails the command"
        );
    }

    /// In a cloud environment the variables *are* the secret store, and a
    /// file written there is discarded with the container. Warning there
    /// would be wrong on every session start.
    #[test]
    fn a_token_in_the_environment_of_a_remote_session_is_fine() {
        let mut rep = healthy();
        rep.token_source = Source::Environment;
        rep.remote_session = true;

        assert!(find(&findings(&rep), "token storage").is_none());
    }

    /// A settings file was read, so it can be named. The shell cannot, and
    /// the finding must not pretend otherwise.
    #[test]
    fn a_token_from_a_settings_file_names_the_file() {
        let mut rep = healthy();
        rep.token_source = Source::Environment;
        rep.declared_env = vec![recall_hooks::declared_env::Declared {
            name: "RECALL_TOKEN".into(),
            file: "/w/app/.claude/settings.local.json".into(),
            shadows_shell: false,
            empty: false,
        }];

        let found = findings(&rep);
        let f = find(&found, "token storage").unwrap();
        assert!(f.detail.contains("settings.local.json"), "{}", f.detail);
        assert!(f.fix.as_deref().unwrap().contains("settings.local.json"));
    }

    #[test]
    fn a_credentials_file_others_can_read_is_a_warning_with_the_chmod() {
        let mut rep = healthy();
        rep.credentials_exposed = true;

        let found = findings(&rep);
        let f = find(&found, "credentials file").unwrap();
        assert_eq!(f.level, Level::Warn);
        assert!(f.fix.as_deref().unwrap().starts_with("chmod 600"));
    }

    /// A leftover shell variable deciding which machine this is, named with
    /// both values and a fix — but only a warning: the environment winning
    /// is the documented rule, and in a cloud session it is the point.
    #[test]
    fn an_environment_value_overriding_the_config_is_named() {
        let mut rep = healthy();
        rep.overridden = vec![crate::status::Override {
            variable: "RECALL_SOURCE_ENV",
            environment: "laptop".into(),
            setting: "machine.name",
            config: "jarvis".into(),
        }];
        let found = findings(&rep);
        let f = find(&found, "config overridden").unwrap();
        assert_eq!(f.level, Level::Warn);
        assert!(
            f.detail.contains("laptop") && f.detail.contains("jarvis"),
            "{}",
            f.detail
        );
        assert!(f.fix.as_deref().unwrap().contains("RECALL_SOURCE_ENV"));
        assert_eq!(verdict(&found), exit::OK);
    }

    #[test]
    fn a_config_problem_is_a_warning_with_the_file_to_edit() {
        let mut rep = healthy();
        rep.config_problems = vec!["`machine.nmae` is not a setting Recall knows".into()];
        let found = findings(&rep);
        let f = find(&found, "config file").unwrap();
        assert_eq!(f.level, Level::Warn);
        assert!(f.fix.as_deref().unwrap().contains("config.toml"));
    }

    /// Every check must earn its exit code. A laptop with no machine scope
    /// and no remote memory dir is not broken, and a doctor that says it is
    /// gets `|| true` appended to it and stops checking anything.
    #[test]
    fn warnings_alone_never_fail_the_command() {
        let mut rep = healthy();
        rep.remote_memory_dir_set = false;
        rep.merge_ready = false;

        let found = findings(&rep);

        assert!(found.iter().any(|f| f.level == Level::Warn));
        assert!(found.iter().all(|f| f.level != Level::Fail));
        assert_eq!(verdict(&found), exit::OK);
    }

    /// Files under a scope that is switched off are not filed under the
    /// project either. They sync nowhere, and nothing else in Recall says so.
    #[test]
    fn files_under_a_scope_that_is_off_are_reported() {
        let mut rep = healthy();
        rep.global_files = 3;

        let found = findings(&rep);
        let f = find(&found, "global scope").unwrap();

        assert_eq!(f.level, Level::Warn);
        assert!(f.detail.contains('3'), "{}", f.detail);
        assert!(
            f.fix.as_deref().unwrap().contains("RECALL_GLOBAL_KEY"),
            "the fix has to name the variable that switches it on"
        );
    }

    /// The bug this project shipped twice, asked as a question: synced is
    /// not the same as read.
    #[test]
    fn a_scope_whose_files_memory_md_does_not_link_is_a_failure() {
        let mut rep = healthy();
        rep.machine_key = Some("machine:mbp".into());
        rep.machine_files = 2;
        rep.machine_linked = false;

        let found = findings(&rep);
        let f = find(&found, "machine scope").unwrap();

        assert_eq!(f.level, Level::Fail);
        assert!(f.detail.contains("MEMORY.md"), "{}", f.detail);
    }

    #[test]
    fn a_linked_scope_with_files_is_fine() {
        let mut rep = healthy();
        rep.machine_key = Some("machine:mbp".into());
        rep.machine_files = 2;
        rep.machine_linked = true;

        assert_eq!(
            find(&findings(&rep), "machine scope").unwrap().level,
            Level::Ok
        );
    }

    /// Invisible on a case-insensitive filesystem, which is most laptops.
    #[test]
    fn a_miscased_reserved_directory_fails() {
        let mut rep = healthy();
        rep.miscased_dir = Some(MiscasedDir {
            found: "Global".into(),
            reserved: "global",
        });

        let found = findings(&rep);

        assert_eq!(
            find(&found, "reserved directory").unwrap().level,
            Level::Fail
        );
        assert_eq!(verdict(&found), exit::CONFIG);
    }

    /// A variable set to a value Recall refused did nothing, and the only
    /// other symptom is memory syncing somewhere you did not ask for.
    #[test]
    fn a_rejected_variable_fails_and_names_itself() {
        let mut rep = healthy();
        rep.rejected_vars = vec!["RECALL_PROJECT_KEY"];

        let found = findings(&rep);
        let f = find(&found, "rejected value").unwrap();

        assert_eq!(f.level, Level::Fail);
        assert!(f.detail.contains("RECALL_PROJECT_KEY"), "{}", f.detail);
    }

    /// Anything not `Ok` has to say what to do about it. A finding a reader
    /// cannot act on teaches them to skip the whole report.
    #[test]
    fn every_finding_that_is_not_ok_carries_a_fix() {
        let mut rep = healthy();
        rep.url_set = false;
        rep.token_set = false;
        rep.hooks_wired = false;
        rep.remote_memory_dir_set = false;
        rep.global_files = 3;
        rep.machine_key = Some("machine:mbp".into());
        rep.machine_files = 1;
        rep.machine_linked = false;
        rep.miscased_dir = Some(MiscasedDir {
            found: "Global".into(),
            reserved: "global",
        });
        rep.rejected_vars = vec!["RECALL_PROJECT_KEY"];
        rep.unreadable_settings = vec![".claude/settings.json".into()];

        for f in findings(&rep).iter().filter(|f| f.level != Level::Ok) {
            assert!(
                f.fix.as_deref().is_some_and(|s| !s.is_empty()),
                "{} has no fix",
                f.check
            );
        }
    }

    /// In a remote session an unset memory dir is not a nuance — Claude
    /// Code's auto-memory is off entirely, so nothing syncs however correct
    /// the rest is. It shipped as a `Warn`, which left the one case where it
    /// is fatal unable to change the exit code.
    ///
    /// The fix has to spell the value out. It is not `$HOME` — in a cloud
    /// session `$HOME` is `/root` while the answer is `/home/user/.claude` —
    /// and before this it appeared nowhere but a ROADMAP checkbox.
    #[test]
    fn an_unset_remote_memory_dir_fails_in_a_remote_session() {
        let mut rep = healthy();
        rep.remote_session = true;
        rep.remote_memory_dir_set = false;

        let found = findings(&rep);
        let f = find(&found, "CLAUDE_CODE_REMOTE_MEMORY_DIR").unwrap();

        assert_eq!(f.level, Level::Fail);
        assert!(
            f.fix.as_deref().unwrap().contains("/home/user/.claude"),
            "{:?}",
            f.fix
        );
        assert_eq!(verdict(&found), exit::CONFIG);
    }

    /// And on a laptop the same state is correct, so reporting it forever
    /// is noise — the kind that teaches someone to stop reading the output.
    #[test]
    fn an_unset_remote_memory_dir_is_fine_on_a_laptop() {
        let mut rep = healthy();
        rep.remote_session = false;
        rep.remote_memory_dir_set = false;

        let found = findings(&rep);

        assert_eq!(
            find(&found, "CLAUDE_CODE_REMOTE_MEMORY_DIR").unwrap().level,
            Level::Ok
        );
        assert_eq!(verdict(&found), exit::OK);
    }

    /// Checking your connection from a home directory is an ordinary thing
    /// to do. The first version of this exited 1 for it, because hooks are
    /// not wired there — true, and not a problem.
    #[test]
    fn unwired_hooks_outside_a_git_repository_are_not_a_failure() {
        let mut rep = healthy();
        rep.in_git_repo = false;
        rep.hooks_wired = false;

        let found = findings(&rep);

        assert_eq!(find(&found, "hooks").unwrap().level, Level::Ok);
        assert_eq!(verdict(&found), exit::OK);
    }

    /// The other side of it, which must keep failing: inside a repository,
    /// unwired hooks mean this project is not syncing at all.
    #[test]
    fn unwired_hooks_inside_a_git_repository_still_fail() {
        let mut rep = healthy();
        rep.in_git_repo = true;
        rep.hooks_wired = false;

        let found = findings(&rep);
        let f = find(&found, "hooks").unwrap();

        assert_eq!(f.level, Level::Fail);
        assert_eq!(f.fix.as_deref(), Some("recall init"));
        assert_eq!(verdict(&found), exit::CONFIG);
    }

    // ----------------------------------------------------------- merge queue

    fn with_worker(oldest: Option<String>, queued: u64) -> Report {
        let mut rep = healthy();
        rep.merge_worker = true;
        rep.merge_queue = Some(recall_wire::QueueStatus {
            queued,
            leased: 0,
            failed: 0,
            oldest_queued_at: oldest,
        });
        rep
    }

    fn stamp_minutes_ago(minutes: i64) -> String {
        let fmt = time::macros::format_description!(
            "[year]-[month]-[day]T[hour]:[minute]:[second].[subsecond digits:3]Z"
        );
        (time::OffsetDateTime::now_utc() - time::Duration::minutes(minutes))
            .format(&fmt)
            .unwrap()
    }

    #[test]
    fn no_worker_no_queue_finding() {
        assert!(find(&findings(&healthy()), "merge queue").is_none());
    }

    #[test]
    fn a_queue_that_drains_is_fine() {
        let found = findings(&with_worker(Some(stamp_minutes_ago(2)), 1));
        assert_eq!(find(&found, "merge queue").unwrap().level, Level::Ok);
        let found = findings(&with_worker(None, 0));
        assert_eq!(
            find(&found, "merge queue").unwrap().detail,
            "nothing waiting"
        );
    }

    /// The worker stopped: pushes keep landing, and the only sign is a job
    /// that keeps getting older.
    #[test]
    fn a_job_waiting_an_hour_is_a_warning() {
        let found = findings(&with_worker(Some(stamp_minutes_ago(61)), 3));
        let f = find(&found, "merge queue").unwrap();
        assert_eq!(f.level, Level::Warn);
        assert!(f.detail.starts_with("3 merges waiting"), "{}", f.detail);
        assert!(f.fix.as_deref().unwrap().contains("recall-worker"));
        assert_eq!(
            verdict(&found),
            exit::OK,
            "a warning never fails the command"
        );
    }

    /// A worker that stopped asking for work is not ready, whatever its
    /// last report of its CLI said.
    #[test]
    fn a_worker_that_stopped_asking_is_a_warning() {
        let mut rep = with_worker(None, 0);
        rep.merge_ready = true;
        rep.merge_worker_seen_at = Some(stamp_minutes_ago(1));
        assert!(worker_quiet(&rep).is_none());
        assert!(find(&findings(&rep), "merge").is_none());

        rep.merge_worker_seen_at = Some(stamp_minutes_ago(3));
        assert!(worker_quiet(&rep).is_some());
        let found = findings(&rep);
        let f = find(&found, "merge").unwrap();
        assert_eq!(f.level, Level::Warn);
        assert!(f.detail.contains("has not asked for work"), "{}", f.detail);
        assert!(f.fix.as_deref().unwrap().contains("logs recall-worker"));

        // Without a worker there is nothing to go quiet.
        rep.merge_worker = false;
        assert!(worker_quiet(&rep).is_none());
    }

    /// A failed merge is a warning however new: nothing retries it.
    #[test]
    fn a_failed_merge_is_a_warning() {
        let mut rep = with_worker(None, 0);
        assert!(find(&findings(&rep), "failed merges").is_none());
        rep.merge_queue.as_mut().unwrap().failed = 2;
        let found = findings(&rep);
        let f = find(&found, "failed merges").unwrap();
        assert_eq!(f.level, Level::Warn);
        assert!(f.detail.starts_with("2 merges failed"), "{}", f.detail);
        assert!(f.fix.as_deref().unwrap().contains("/v1/jobs"));
        // Also with no worker: a revoked worker's queue, failed here.
        rep.merge_worker = false;
        assert!(find(&findings(&rep), "failed merges").is_some());
    }

    #[test]
    fn a_worker_that_cannot_merge_names_the_worker() {
        let mut rep = with_worker(None, 0);
        rep.merge_ready = false;
        let found = findings(&rep);
        assert!(find(&found, "merge")
            .unwrap()
            .fix
            .as_deref()
            .unwrap()
            .contains("recall-worker claude setup-token"));
    }

    // ---------------------------------------------------------------- off-box

    /// The ordinary case for a deployment that has no off-box backup at all.
    /// A standing complaint here would be the same noise this command has
    /// already had to have removed twice.
    #[test]
    fn no_offbox_stamp_is_reported_as_nothing() {
        let found = findings(&healthy());
        assert!(find(&found, "off-box backup").is_none());
    }

    #[test]
    fn a_recent_offbox_copy_is_fine() {
        let mut rep = healthy();
        rep.last_offbox_at = Some(stamp_days_ago(1));

        let found = findings(&rep);

        assert_eq!(find(&found, "off-box backup").unwrap().level, Level::Ok);
        assert_eq!(verdict(&found), exit::OK);
    }

    /// The case a transient 403 from the bucket produced in production: the
    /// copy stopped, cron kept firing, and nothing anywhere said so.
    #[test]
    fn an_offbox_copy_that_stopped_is_reported_with_its_age() {
        let mut rep = healthy();
        rep.last_offbox_at = Some(stamp_days_ago(9));

        let found = findings(&rep);
        let f = find(&found, "off-box backup").unwrap();

        assert_eq!(f.level, Level::Warn);
        assert!(
            f.detail.contains('9'),
            "the age has to be in it: {}",
            f.detail
        );
        // A backup that stopped is serious and is still not "memory is not
        // syncing", which is what Fail means here. Warn keeps the exit code
        // honest.
        assert_eq!(verdict(&found), exit::OK);
    }

    /// Six-hourly is the recommended cadence, so eight runs have to fail
    /// before this speaks. One missed night must stay silent.
    #[test]
    fn a_single_missed_run_is_not_worth_reporting() {
        let mut rep = healthy();
        rep.last_offbox_at = Some(stamp_days_ago(1));

        assert_eq!(
            find(&findings(&rep), "off-box backup").unwrap().level,
            Level::Ok
        );
    }

    /// A report that invents an age is worse than one admitting it cannot
    /// read the value.
    #[test]
    fn an_unreadable_stamp_says_so_rather_than_guessing() {
        let mut rep = healthy();
        rep.last_offbox_at = Some("yesterday-ish".into());

        let found = findings(&rep);
        let f = find(&found, "off-box backup").unwrap();

        assert_eq!(f.level, Level::Warn);
        assert!(f.detail.contains("yesterday-ish"), "{}", f.detail);
    }

    fn stamp_days_ago(days: i64) -> String {
        let fmt = time::macros::format_description!(
            "[year]-[month]-[day]T[hour]:[minute]:[second].[subsecond digits:3]Z"
        );
        (time::OffsetDateTime::now_utc() - time::Duration::days(days))
            .format(&fmt)
            .unwrap()
    }

    // ---------------------------------------------------------------- audit log

    fn audit(edit: impl FnOnce(&mut crate::status::AuditReport)) -> Report {
        let mut rep = healthy();
        edit(rep.audit.as_mut().unwrap());
        rep
    }

    #[test]
    fn a_log_that_extends_what_was_saved_is_ok() {
        let found = findings(&healthy());
        let f = find(&found, "audit log").unwrap();
        assert_eq!(f.level, Level::Ok);
        assert!(f.detail.contains("3 kept, newest 1042"), "{}", f.detail);
    }

    /// The plan's "fails loudly": a rewrite found fails, now and on every
    /// run after, whatever else was checked, and says what to do.
    #[test]
    fn a_rewrite_found_fails_until_it_is_reset() {
        let rep = audit(|a| {
            a.extends = None;
            a.error = Some("could not reach the server".into());
            a.inconsistent = Some(recall_hooks::audit::Inconsistency {
                found_at: "2026-10-02T09:14:05.402Z".into(),
                saved: "r.example\n9\nAAAA\n".into(),
                seen: "r.example\n5\nBBBB\n".into(),
                detail: "the log has 5 leaves, fewer than the 9".into(),
            });
        });
        let found = findings(&rep);
        let f = find(&found, "audit log").unwrap();
        assert_eq!(f.level, Level::Fail);
        assert!(f.detail.contains("fewer than the 9"), "{}", f.detail);
        assert!(f.fix.as_deref().unwrap().contains("recall audit reset"));
        assert_eq!(verdict(&found), exit::CONFIG);
    }

    #[test]
    fn a_server_that_answers_without_a_proof_fails() {
        let rep = audit(|a| {
            a.extends = None;
            a.unproven = Some("server returned 500".into());
        });
        assert_eq!(
            find(&findings(&rep), "audit log").unwrap().level,
            Level::Fail
        );
    }

    /// A server that no longer keeps the log this machine witnessed it
    /// keeping lost its history; one that never kept one did not.
    #[test]
    fn a_log_that_went_away_fails_and_one_never_kept_does_not() {
        let rep = audit(|a| {
            a.extends = None;
            a.server_log = Some(false);
        });
        assert_eq!(
            find(&findings(&rep), "audit log").unwrap().level,
            Level::Fail
        );
        let rep = audit(|a| {
            *a = crate::status::AuditReport {
                server_log: Some(false),
                ..Default::default()
            }
        });
        let found = findings(&rep);
        let f = find(&found, "audit log").unwrap();
        assert_eq!(f.level, Level::Ok);
        assert_eq!(tone_of(f), ui::Tone::Quiet);
    }

    #[test]
    fn a_log_that_could_not_be_checked_only_warns() {
        let rep = audit(|a| {
            a.extends = None;
            a.error = Some("server returned 429".into());
        });
        let found = findings(&rep);
        assert_eq!(find(&found, "audit log").unwrap().level, Level::Warn);
        assert_eq!(verdict(&found), exit::OK);
    }

    fn audit_level(rep: &Report) -> Level {
        find(&findings(rep), "audit log").unwrap().level
    }

    /// A rewrite found that could not be written down still fails, and
    /// says it was not saved.
    #[test]
    fn a_rewrite_found_and_not_saved_still_fails() {
        let rep = audit(|a| {
            a.extends = Some(false);
            a.unsaved = Some("another recall held audit.json.lock for too long".into());
            a.inconsistent = Some(recall_hooks::audit::Inconsistency {
                found_at: "2026-10-02T09:14:05.402Z".into(),
                saved: "r.example\n9\nAAAA\n".into(),
                seen: "r.example\n5\nBBBB\n".into(),
                detail: "the log has 5 leaves, fewer than the 9".into(),
            });
        });
        let found = findings(&rep);
        let f = find(&found, "audit log").unwrap();
        assert_eq!(f.level, Level::Fail);
        assert!(f.detail.contains("could not be written"), "{}", f.detail);
    }

    /// `audit.json` that cannot be read may hold the only record of a
    /// rewrite: that fails, it is not a detail. Mutation: warn on it.
    #[test]
    fn an_audit_file_that_cannot_be_read_fails() {
        let rep = audit(|a| {
            a.extends = None;
            a.file_error = Some("~/.recall/audit.json is not a file Recall can read".into());
        });
        assert_eq!(audit_level(&rep), Level::Fail);
    }

    /// Checkpoints dropped unchecked are a gap in the witnessing, said out
    /// loud until reset. Mutation: say nothing of them.
    #[test]
    fn checkpoints_dropped_unchecked_fail() {
        let rep = audit(|a| a.dropped = 3);
        let found = findings(&rep);
        let f = find(&found, "audit log").unwrap();
        assert_eq!(f.level, Level::Fail);
        assert!(
            f.detail.starts_with("3 checkpoint(s) were dropped"),
            "{}",
            f.detail
        );
    }

    /// Checkpoints saved and not checked this time (no credential, or the
    /// discovery document failed before the fix) warn rather than pass
    /// quietly. Mutation: report them as ok.
    #[test]
    fn checkpoints_not_checked_this_time_warn() {
        let rep = audit(|a| {
            a.extends = None;
            a.server_log = None;
            a.unchecked = 2;
        });
        assert_eq!(audit_level(&rep), Level::Warn);
    }

    /// A server that keeps not answering cannot keep a check pending for
    /// ever: the oldest waiting a week, or ten checks unanswered in a row,
    /// fail. Mutation: only ever warn.
    #[test]
    fn checks_that_never_finish_fail_in_the_end() {
        let at = |days: i64| {
            let fmt = time::macros::format_description!(
                "[year]-[month]-[day]T[hour]:[minute]:[second].[subsecond digits:3]Z"
            );
            (time::OffsetDateTime::now_utc() - time::Duration::days(days))
                .format(&fmt)
                .unwrap()
        };
        let waiting = |days: i64| {
            audit(|a| {
                a.extends = None;
                a.error = Some("server returned 429".into());
                a.unchecked = 4;
                a.unchecked_since = Some(at(days));
            })
        };
        assert_eq!(audit_level(&waiting(6)), Level::Warn);
        assert_eq!(audit_level(&waiting(8)), Level::Fail);

        let unanswered = |n: u64| {
            audit(|a| {
                a.extends = None;
                a.error = Some("could not reach the server".into());
                a.unanswered = n;
            })
        };
        assert_eq!(
            audit_level(&unanswered(recall_hooks::audit::UNANSWERED_LIMIT - 1)),
            Level::Warn
        );
        assert_eq!(
            audit_level(&unanswered(recall_hooks::audit::UNANSWERED_LIMIT)),
            Level::Fail
        );
    }

    /// A time as `status` reports one, `days` ago.
    fn days_ago(days: i64) -> String {
        let fmt = time::macros::format_description!(
            "[year]-[month]-[day]T[hour]:[minute]:[second].[subsecond digits:3]Z"
        );
        (time::OffsetDateTime::now_utc() - time::Duration::days(days))
            .format(&fmt)
            .unwrap()
    }

    /// N2: however the checks were cut short, a week with none finished
    /// fails while anything is saved, and not before. The case the rules
    /// above miss: checks never asked at all (a server slow at everything
    /// else, no credential), which count nothing, with nothing unchecked.
    /// Mutation: no such rule.
    #[test]
    fn a_week_without_a_finished_check_fails() {
        let since = |days: i64, saved: usize| {
            audit(|a| {
                a.extends = None;
                a.checkpoints = saved;
                a.last_proven_at = Some(days_ago(days));
            })
        };
        assert_eq!(audit_level(&since(6, 3)), Level::Warn);
        let rep = since(8, 3);
        let found = findings(&rep);
        let f = find(&found, "audit log").unwrap();
        assert_eq!(f.level, Level::Fail);
        assert!(
            f.detail.starts_with("no check of the server's log"),
            "{}",
            f.detail
        );
        let found = findings(&since(8, 0));
        let level = find(&found, "audit log").map(|f| f.level);
        assert_ne!(level, Some(Level::Fail), "nothing saved");
    }

    /// A time stamped in the future, by a clock set wrong when it was
    /// written, never grows a week old: it counts as stale, not as recent,
    /// for both of the week's rules. A few hours ahead is drift. Mutation:
    /// read a future stamp as recent, as before.
    #[test]
    fn a_time_stamped_in_the_future_is_stale() {
        let proven = |at: &str| {
            audit(|a| {
                a.extends = None;
                a.last_proven_at = Some(at.into());
            })
        };
        let rep = proven("2099-01-01T00:00:00.000Z");
        let found = findings(&rep);
        let f = find(&found, "audit log").unwrap();
        assert_eq!(f.level, Level::Fail);
        assert!(f.detail.contains("in the future"), "{}", f.detail);
        assert_eq!(audit_level(&proven(&days_ago(0))), Level::Warn);

        let waiting = audit(|a| {
            a.extends = None;
            a.unchecked = 2;
            a.unchecked_since = Some("2099-01-01T00:00:00.000Z".into());
        });
        assert_eq!(audit_level(&waiting), Level::Fail);
    }

    /// Unanswered checks with nothing saved are no pending check. Mutation:
    /// fail on the count alone.
    #[test]
    fn unanswered_checks_with_nothing_saved_do_not_fail() {
        let rep = audit(|a| {
            *a = crate::status::AuditReport {
                unanswered: recall_hooks::audit::UNANSWERED_LIMIT,
                error: Some("could not reach the server".into()),
                ..Default::default()
            }
        });
        assert_ne!(audit_level(&rep), Level::Fail);
    }

    /// A credential the server refused warns with what to do about the
    /// credential, not "the server did not prove"; and it does not keep the
    /// week's rule from failing. Mutation: report it as any other error.
    #[test]
    fn a_refused_credential_warns_about_the_credential() {
        let refused = |days: i64| {
            audit(|a| {
                a.extends = None;
                a.refused = true;
                a.error = Some("server returned 403: forbidden".into());
                a.last_proven_at = Some(days_ago(days));
            })
        };
        let rep = refused(1);
        let found = findings(&rep);
        let f = find(&found, "audit log").unwrap();
        assert_eq!(f.level, Level::Warn);
        assert!(
            f.detail.contains("refused this machine's credential"),
            "{}",
            f.detail
        );
        let fix = f.fix.as_deref().unwrap_or_default();
        assert!(fix.contains("recall connect"), "{fix}");
        assert_eq!(audit_level(&refused(8)), Level::Fail);
    }

    /// Every audit finding reads as one sentence: no run of spaces left by
    /// a line continuation that lost its backslash. Mutation: drop one.
    /// One change to a healthy report's audit section.
    type Edit = dyn Fn(&mut crate::status::AuditReport);

    #[test]
    fn audit_findings_have_no_runs_of_spaces() {
        let finding = recall_hooks::audit::Inconsistency {
            found_at: "2026-10-02T09:14:05.402Z".into(),
            saved: "r.example\n9\nAAAA\n".into(),
            seen: "r.example\n5\nBBBB\n".into(),
            detail: "the log has 5 leaves".into(),
        };
        let edits: Vec<Box<Edit>> = vec![
            Box::new(|_| {}),
            Box::new(move |a| a.inconsistent = Some(finding.clone())),
            Box::new(|a| a.file_error = Some("unreadable".into())),
            Box::new(|a| a.unproven = Some("server returned 500".into())),
            Box::new(|a| a.dropped = 2),
            Box::new(|a| a.server_log = Some(false)),
            Box::new(|a| {
                *a = crate::status::AuditReport {
                    server_log: Some(false),
                    ..Default::default()
                }
            }),
            Box::new(|a| {
                a.extends = None;
                a.unchecked = 1;
                a.unchecked_since = Some("2000-01-01T00:00:00.000Z".into());
            }),
            Box::new(|a| {
                a.extends = None;
                a.unanswered = 99;
            }),
            Box::new(|a| {
                a.extends = None;
                a.last_proven_at = Some("2000-01-01T00:00:00.000Z".into());
            }),
            Box::new(|a| {
                a.extends = None;
                a.refused = true;
                a.error = Some("server returned 401".into());
            }),
            Box::new(|a| {
                a.extends = None;
                a.error = Some("server returned 429".into());
            }),
            Box::new(|a| a.extends = None),
        ];
        for edit in edits {
            let found = findings(&audit(edit));
            let f = find(&found, "audit log").unwrap();
            for text in [Some(&f.detail), f.fix.as_ref()].into_iter().flatten() {
                assert!(!text.contains("  "), "a run of spaces in {text:?}");
            }
        }
    }

    // ---------------------------------------------------------------- text

    /// The text shows the audit checkpoint and the server's commit cut
    /// short; the finding, which is what `--json` prints, keeps both whole.
    /// Mutation: shorten them in the finding instead.
    #[test]
    fn a_finding_is_shown_short_and_kept_whole() {
        let mut rep = healthy();
        rep.git_commit = Some("0fa9e05aa1b2c3d4e5f60718293a4b5c6d7e8f90".into());
        let found = findings(&rep);
        let audit = find(&found, "audit log").unwrap();
        assert!(
            audit
                .detail
                .contains("newest 1042 CsUYapGGPo4dkMgIAUqom/Xajj7h2fB2MPA3j2jxq2I="),
            "{}",
            audit.detail
        );
        let text = shown(&rep, &audit.detail);
        assert!(text.ends_with("newest 1042 CsUYapGGPo4d…)"), "{text}");
        assert_eq!(
            shown(&rep, "commit 0fa9e05aa1b2c3d4e5f60718293a4b5c6d7e8f90"),
            "commit 0fa9e05aa1b2"
        );
    }

    // ---------------------------------------------------------------- Git Bash

    /// Exercises the real environment rather than a stand-in: GitHub's
    /// `windows-latest` runner is documented to ship Git for Windows, so this
    /// pins that assumption down where a change to the runner image would be
    /// noticed, instead of only being noticed by someone hitting the failure
    /// on their own machine. Not verified anywhere but CI — there is no
    /// Windows machine in the environment this was written in.
    #[cfg(windows)]
    #[test]
    fn git_bash_is_found_on_this_runner() {
        assert!(
            git_bash_available(),
            "expected Git for Windows on this runner; if the image changed, \
             widen the search in git_bash_available()"
        );
    }

    #[cfg(windows)]
    #[test]
    fn a_healthy_windows_report_includes_a_git_bash_finding() {
        let found = findings(&healthy());
        let f = find(&found, "Git Bash").expect("a Git Bash finding on Windows");
        // Whichever it says, it has to be one of the two — never silently
        // absent, which is the whole point of this check existing.
        assert!(matches!(f.level, Level::Ok | Level::Fail));
    }
}