shellfirm 0.4.2

`shellfirm` will intercept any risky patterns (default or defined by you) and prompt you a small challenge for double verification, kinda like a captcha for your terminal.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
//! `shellfirm doctor`: is the current shell really protected?
//!
//! Static checks (binary, rc file, configuration) run in this process. The
//! live state of the shell hook (does Enter go through shellfirm, which
//! widgets/bindings are wrapped, known plugins) can only be seen from inside
//! the shell: `doctor` starts a fresh interactive shell that runs the
//! hook's probe function (`__shellfirm_doctor_probe`, the same name in
//! bash, zsh and fish). To check the shell you are typing in
//! (including bindings changed after startup) pipe the probe in:
//! `__shellfirm_doctor_probe | shellfirm doctor --stdin`.
//!
//! Whether the shell `doctor` was started from has loaded the hook at all is
//! told by `SHELLFIRM_HOOK_PID`, which every hook exports with its own pid.

use std::collections::BTreeMap;
use std::io::Read;
use std::path::PathBuf;
use std::process::{Command as Process, Stdio};
use std::time::{Duration, Instant};

use clap::{crate_version, Arg, ArgAction, ArgMatches, Command};
use serde_json::json;
use shellfirm::config::ascii_fallback;
use shellfirm::Config;

use super::init::{self, Shell, ShellSource, HOOK_VERSION};

/// How long a probe shell may take to start (rc files can be slow).
const PROBE_TIMEOUT: Duration = Duration::from_secs(15);

/// Version of the `--format json` output. Bumped when a field changes
/// meaning or is removed (new fields may be added without a bump).
const SCHEMA_VERSION: u32 = 1;

/// Exported by every hook with the pid of the shell that loaded it.
const HOOK_PID_ENV: &str = "SHELLFIRM_HOOK_PID";
/// Set by the hook to a new value every time it loads: after `exec`, a value
/// other than the one the shell started with means this shell loaded it.
const HOOK_LOAD_ENV: &str = "SHELLFIRM_HOOK_LOAD";

/// Exit code when a check failed (commands may run unchecked).
const EXIT_FAILED: i32 = 1;

pub fn command() -> Command {
    Command::new("doctor")
        .about("Check that the current shell really routes commands through shellfirm")
        .long_about(
            "Check the shell integration: which shell you use, whether this shell session \
             has loaded the hook, which shellfirm binary the hook runs, whether the rc file \
             loads the hook (once), whether Enter (and the other keys that run a command) go \
             through shellfirm in a new interactive shell, known plugin conflicts, \
             whether the configuration is valid, and the AI-agent hooks installed by \
             `shellfirm connect` (`agent_hook` findings: a hook that does not cover the \
             agent's shell tool or is turned off in the agent's settings is a warning).\n\n\
             The live check starts a new interactive shell, so it sees what your rc files \
             set up, not key bindings you changed by hand in this session. To check this \
             session, pipe the hook's probe in (bash, zsh and fish):\n\
             \x20 __shellfirm_doctor_probe | shellfirm doctor --stdin\n\n\
             Exit codes:\n\
             \x20 0   nothing is wrong (warnings may still be listed)\n\
             \x20 1   a check failed: commands typed in this shell may run unchecked (when no \
             shell hook is installed at all and the AI-agent hooks are in order, the shell \
             findings are warnings and the exit code is 0)\n\
             \x20 64  usage error (for example, the shell could not be detected)\n\n\
             `--format json` prints one object with `schema_version`, `ok`, \
             `session_hooked`, `enter_routes_through_shellfirm` and the findings.",
        )
        .arg(
            Arg::new("shell")
                .long("shell")
                .help("Shell to check (default: the shell that started shellfirm, then $SHELL)")
                .value_parser(clap::builder::PossibleValuesParser::new([
                    "bash", "zsh", "fish", "nushell", "nu", "powershell", "pwsh", "elvish",
                    "xonsh", "oils", "osh", "ysh",
                ]))
                .ignore_case(true),
        )
        .arg(
            Arg::new("stdin")
                .long("stdin")
                .help("Read the probe output of the live shell from stdin instead of starting a new shell")
                .action(ArgAction::SetTrue),
        )
        .arg(
            Arg::new("format")
                .long("format")
                .value_parser(["text", "json"])
                .default_value("text")
                .help("Output format"),
        )
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde_derive::Serialize)]
#[serde(rename_all = "lowercase")]
enum Status {
    Ok,
    Info,
    Warn,
    Fail,
}

impl Status {
    const fn symbol(self) -> &'static str {
        match self {
            Self::Ok => "ok",
            Self::Info => "--",
            Self::Warn => "!!",
            Self::Fail => "XX",
        }
    }
}

#[derive(Debug, Clone, serde_derive::Serialize)]
struct Finding {
    id: &'static str,
    status: Status,
    message: String,
}

#[derive(Default)]
struct Report {
    findings: Vec<Finding>,
}

impl Report {
    fn add(&mut self, id: &'static str, status: Status, message: impl Into<String>) {
        self.findings.push(Finding {
            id,
            status,
            message: message.into(),
        });
    }

    fn failed(&self) -> bool {
        self.findings.iter().any(|f| f.status == Status::Fail)
    }
}

/// Parse `key=value` lines printed by a hook's probe function.
fn parse_probe(text: &str) -> BTreeMap<String, String> {
    text.lines()
        .filter_map(|l| l.split_once('='))
        .map(|(k, v)| (k.trim().to_string(), v.trim().to_string()))
        .filter(|(k, _)| !k.is_empty() && k.chars().all(|c| c.is_ascii_alphanumeric() || c == '_'))
        .collect()
}

/// The probe command for shells that have one.
const fn probe_invocation(shell: Shell) -> Option<(&'static str, &'static [&'static str])> {
    match shell {
        Shell::Bash => Some(("bash", &["-i", "-c", "__shellfirm_doctor_probe"])),
        // Hooks before version 7 named the zsh probe `_shellfirm_doctor_probe`.
        Shell::Zsh => Some((
            "zsh",
            &[
                "-i",
                "-c",
                "if (( $+functions[__shellfirm_doctor_probe] )); then __shellfirm_doctor_probe; \
                 else _shellfirm_doctor_probe; fi",
            ],
        )),
        Shell::Fish => Some(("fish", &["-i", "-c", "__shellfirm_doctor_probe"])),
        _ => None,
    }
}

/// The probe function every hook defines (zsh also keeps the pre-7 name
/// `_shellfirm_doctor_probe`).
const fn probe_function(_shell: Shell) -> &'static str {
    "__shellfirm_doctor_probe"
}

/// Start a new interactive shell and run the hook's probe function.
fn run_probe(shell: Shell) -> Result<String, String> {
    let Some((bin, args)) = probe_invocation(shell) else {
        return Err(format!("no live probe for {shell}"));
    };
    let mut child = Process::new(bin)
        .args(args)
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        .spawn()
        .map_err(|e| format!("could not start {bin}: {e}"))?;
    let start = Instant::now();
    loop {
        match child.try_wait() {
            Ok(Some(_)) => break,
            Ok(None) if start.elapsed() > PROBE_TIMEOUT => {
                let _ = child.kill();
                let _ = child.wait();
                return Err(format!(
                    "{bin} did not finish starting within {}s",
                    PROBE_TIMEOUT.as_secs()
                ));
            }
            Ok(None) => std::thread::sleep(Duration::from_millis(20)),
            Err(e) => return Err(format!("waiting for {bin}: {e}")),
        }
    }
    let mut out = String::new();
    if let Some(mut stdout) = child.stdout.take() {
        let _ = stdout.read_to_string(&mut out);
    }
    Ok(out)
}

/// First `shellfirm` on PATH (what the hooks run).
fn shellfirm_on_path() -> Option<PathBuf> {
    let path = std::env::var_os("PATH")?;
    std::env::split_paths(&path)
        .map(|d| {
            d.join(if cfg!(windows) {
                "shellfirm.exe"
            } else {
                "shellfirm"
            })
        })
        .find(|p| p.is_file())
}

/// Whether the shell binary on PATH actually starts (a wrapper with a
/// missing interpreter, or a binary for another libc, is a file but exits
/// 126/127 before shellfirm runs).
fn binary_starts(path: &PathBuf) -> Result<(), String> {
    match Process::new(path)
        .arg("--version")
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status()
    {
        Ok(s) if s.success() => Ok(()),
        Ok(s) => Err(s
            .code()
            .map_or_else(|| "killed by a signal".to_string(), |c| format!("exit {c}"))),
        Err(e) => Err(e.to_string()),
    }
}

fn check_binary(report: &mut Report) -> serde_json::Value {
    let exe = std::env::current_exe().ok();
    let on_path = shellfirm_on_path();
    let mut starts = None;
    match &on_path {
        None => report.add(
            "binary",
            Status::Fail,
            "shellfirm is not on PATH: the shell hooks fail open (commands are NOT checked)",
        ),
        Some(p) => {
            let same = exe
                .as_ref()
                .zip(Some(p))
                .is_some_and(|(a, b)| a.canonicalize().ok() == b.canonicalize().ok());
            if same || exe.is_none() {
                starts = Some(true);
                report.add(
                    "binary",
                    Status::Ok,
                    format!("{} (v{})", p.display(), crate_version!()),
                );
            } else if let Err(e) = binary_starts(p) {
                starts = Some(false);
                report.add(
                    "binary",
                    Status::Fail,
                    format!(
                        "the hooks run {} but it does not start ({e}): commands are NOT checked \
                         (the hooks warn on every command)",
                        p.display()
                    ),
                );
            } else {
                starts = Some(true);
                report.add(
                    "binary",
                    Status::Warn,
                    format!(
                        "the hooks run {} but this is {}; they may be different versions",
                        p.display(),
                        exe.as_ref()
                            .map(|e| e.display().to_string())
                            .unwrap_or_default()
                    ),
                );
            }
        }
    }
    json!({
        "path_lookup": on_path,
        "current_exe": exe,
        "starts": starts,
        "version": crate_version!(),
    })
}

/// Whether the shell `doctor` runs in has loaded the hook.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Session {
    /// `SHELLFIRM_HOOK_PID` is the pid of this shell.
    Hooked,
    /// The marker is missing, or belongs to another (outer) shell.
    NotHooked { outer: Option<u32> },
    /// The marker is this shell's pid but it was already in the environment
    /// the shell started with: the shell replaced a hooked one with `exec`
    /// (same pid, same environment), so the marker says nothing about it.
    Inherited,
    /// Not known: doctor was not started from the shell it checks.
    Unknown,
}

/// `marker` is the value of `SHELLFIRM_HOOK_PID`, `parent` the pid of the
/// shell doctor was started from. A marker of another pid comes from an
/// outer shell (`zsh -f` started from a protected shell inherits it).
fn session_state(marker: Option<&str>, parent: Option<u32>) -> Session {
    let Some(parent) = parent else {
        return Session::Unknown;
    };
    match marker.and_then(|m| m.trim().parse::<u32>().ok()) {
        Some(m) if m == parent => Session::Hooked,
        other => Session::NotHooked { outer: other },
    }
}

fn detect_session() -> Session {
    #[cfg(unix)]
    let parent = Some(std::os::unix::process::parent_id());
    #[cfg(not(unix))]
    let parent = None;
    let session = session_state(std::env::var(HOOK_PID_ENV).ok().as_deref(), parent);
    if session == Session::Hooked && parent.is_some_and(started_with_marker) {
        // Restarted with `exec`: the hook loaded again when its load marker
        // is not the one the shell started with.
        let now = std::env::var(HOOK_LOAD_ENV).ok();
        let at_start = parent.and_then(|p| {
            std::fs::read(format!("/proc/{p}/environ"))
                .ok()
                .and_then(|env| environ_value(&env, HOOK_LOAD_ENV))
        });
        return inherited_or_reloaded(now.as_deref(), at_start.as_deref());
    }
    session
}

/// A shell started (by `exec`) with the marker of a hooked shell: `Hooked`
/// when its hook load marker changed since it started (it loaded the hook
/// itself), else `Inherited` (not known).
fn inherited_or_reloaded(now: Option<&str>, at_start: Option<&str>) -> Session {
    match now {
        Some(n) if !n.is_empty() && Some(n) != at_start => Session::Hooked,
        _ => Session::Inherited,
    }
}

/// The value of `name` in a `/proc/<pid>/environ` buffer.
fn environ_value(environ: &[u8], name: &str) -> Option<String> {
    let prefix = format!("{name}=");
    environ
        .split(|b| *b == 0)
        .find_map(|kv| kv.strip_prefix(prefix.as_bytes()))
        .map(|v| String::from_utf8_lossy(v).into_owned())
}

/// Whether the marker was already in the environment process `pid` started
/// with (Linux: `/proc/<pid>/environ`). A shell sets the marker after it
/// starts, so finding its own pid there means it came from `exec`.
fn started_with_marker(pid: u32) -> bool {
    std::fs::read(format!("/proc/{pid}/environ")).is_ok_and(|env| environ_has_marker(&env, pid))
}

fn environ_has_marker(environ: &[u8], pid: u32) -> bool {
    let want = format!("{HOOK_PID_ENV}={pid}");
    environ.split(|b| *b == 0).any(|kv| kv == want.as_bytes())
}

fn check_session(report: &mut Report, shell: Shell, session: Session) {
    match session {
        Session::Hooked => report.add(
            "session",
            Status::Ok,
            format!("this {shell} session has loaded the shellfirm hook"),
        ),
        Session::NotHooked { outer } => {
            let outer = outer
                .map(|p| {
                    format!(" (the hook is active in an outer shell, pid {p}, not in this one)")
                })
                .unwrap_or_default();
            report.add(
                "session",
                Status::Fail,
                format!(
                    "this {shell} session has NOT loaded the shellfirm hook{outer}: commands typed \
                     here are not checked. It was started before `shellfirm init`, or without \
                     its rc files ({}); start a new one: `{}`",
                    match shell {
                        Shell::Zsh => "`zsh -f`",
                        Shell::Bash => "`bash --norc`",
                        Shell::Fish => "`fish --no-config`",
                        _ => "no rc file",
                    },
                    shell.activate_hint()
                ),
            );
        }
        Session::Inherited => report.add(
            "session",
            Status::Warn,
            format!(
                "this {shell} was restarted with `exec` from a shell that had the hook; the \
                 marker it inherited cannot tell whether this one loaded the hook. Check it \
                 directly: `{} | shellfirm doctor --stdin`",
                probe_function(shell)
            ),
        ),
        Session::Unknown => {}
    }
}

/// A session restarted with `exec` from a hooked shell: judged by whether
/// a new interactive shell loads the hook (`exec` runs the same rc files).
fn check_inherited_session(report: &mut Report, shell: Shell, new_shell_hooked: bool) {
    if new_shell_hooked {
        report.add(
            "session",
            Status::Info,
            format!(
                "this {shell} was restarted with `exec`; a new {shell} loads the hook, so this \
                 one most likely did too (to be sure: `{} | shellfirm doctor --stdin`)",
                probe_function(shell)
            ),
        );
    } else {
        report.add(
            "session",
            Status::Fail,
            format!(
                "this {shell} was restarted with `exec` and a new {shell} does not load the hook: \
                 this session is most likely NOT protected (the inherited marker \
                 SHELLFIRM_HOOK_PID is stale)"
            ),
        );
    }
}

/// The rc file finding; `live_hooked` = a new shell (or this one) has the
/// hook, so a missing loader line means it is loaded from another file.
fn check_rc(
    report: &mut Report,
    shell: Shell,
    rc: &init::RcReport,
    live_hooked: bool,
    session_hooked: bool,
) {
    let path = rc
        .path
        .as_ref()
        .map_or_else(|| "?".to_string(), |p| p.display().to_string());
    if let Some(other) = &rc.loaded_from {
        report.add(
            "rc_file",
            Status::Ok,
            format!("{} loads the hook", other.display()),
        );
    } else if !rc.installed && live_hooked {
        report.add(
            "rc_file",
            Status::Info,
            format!(
                "{path} does not load the hook itself; a new {shell} loads it from another file \
                 (a sourced file or plugin manager), which is fine"
            ),
        );
    } else if !rc.installed && session_hooked {
        // Right after `init --uninstall`: the hook loaded in this shell keeps
        // working until the shell is restarted.
        report.add(
            "rc_file",
            Status::Fail,
            format!(
                "{path} does not load the shellfirm hook: this session still has the hook loaded \
                 and stays protected until you restart the shell, but new shells will not load \
                 it. Run `shellfirm init {shell}` to protect them"
            ),
        );
    } else if !rc.installed {
        report.add(
            "rc_file",
            Status::Fail,
            format!("{path} does not load the shellfirm hook: run `shellfirm init {shell}`"),
        );
    } else if rc.load_count > 1 {
        report.add(
            "rc_file",
            Status::Warn,
            format!(
                "{path} loads the hook {} times; keep one (double hooks prompt twice)",
                rc.load_count
            ),
        );
    } else {
        report.add("rc_file", Status::Ok, format!("{path} loads the hook"));
    }
    if let Some(line) = rc.legacy_hook_line {
        report.add(
            "legacy_hook",
            Status::Warn,
            format!("{path} line {line} has a hook from shellfirm 0.3.x; remove it"),
        );
    }
}

/// A non-failing warning when the settings leave default groups off.
fn check_default_groups(report: &mut Report, settings: &shellfirm::config::Settings) {
    let not_enabled = settings.default_groups_not_enabled();
    if !not_enabled.is_empty() {
        report.add(
            "groups",
            Status::Warn,
            format!(
                "default groups not enabled: {}; enable: `{}`",
                not_enabled.join(", "),
                shellfirm::config::enable_groups_command(&not_enabled)
            ),
        );
    }
}

/// `row` is only off because of `allowManagedHooksOnly`, and a working hook
/// of the same agent is in its managed settings.
fn covered_by_managed_hook(
    row: &super::connect_cmd::IntegrationStatus,
    rows: &[super::connect_cmd::IntegrationStatus],
) -> bool {
    !row.hook_off.is_empty()
        && row
            .hook_off
            .iter()
            .all(|o| o.starts_with(super::connect_cmd::MANAGED_HOOKS_ONLY))
        && rows.iter().any(|m| {
            m.tool == row.tool
                && m.scope == "managed"
                && m.hook_installed
                && m.hook_off.is_empty()
                && m.error.is_none()
        })
}

/// AI-agent hooks installed by `shellfirm connect`: one finding per hook
/// (a warning when it does not cover the agent's shell tool, is turned off
/// in the agent's settings, or its file cannot be read).
fn check_agent_hooks(report: &mut Report, rows: &[super::connect_cmd::IntegrationStatus]) {
    let mut any = false;
    for r in rows {
        let file = r.hook_file.as_deref().unwrap_or("?");
        if let Some(e) = &r.error {
            // Maybe installed: not "no AI-agent hook installed".
            any = true;
            report.add(
                "agent_hook",
                Status::Warn,
                format!(
                    "{} ({}): could not read its configuration: {e}",
                    r.tool, r.scope
                ),
            );
            continue;
        }
        if !r.hook_present {
            // A file at shellfirm's hook path that it did not write.
            if !r.notes.is_empty() {
                report.add(
                    "agent_hook",
                    Status::Warn,
                    format!("{} ({}): {}", r.tool, r.scope, r.notes.join("; ")),
                );
            }
            continue;
        }
        any = true;
        // Problems `shellfirm connect` fixes, then settings that turn the
        // hook off (each message says how to turn it back on).
        let mut problems: Vec<String> = Vec::new();
        if !r.hook_installed {
            problems.push("the hook does not cover the agent's shell commands".into());
        }
        if !r.shell_tools_missing.is_empty() {
            problems.push(format!("not covered: {}", r.shell_tools_missing.join(", ")));
        }
        if r.legacy_hook {
            problems.push("legacy hook command line".into());
        }
        let rerun = if problems.is_empty() {
            String::new()
        } else {
            format!("; re-run `shellfirm connect {}`", r.tool)
        };
        if problems.is_empty() && covered_by_managed_hook(r, rows) {
            report.add(
                "agent_hook",
                Status::Info,
                format!(
                    "{} ({}): hook in {file} is not loaded ({}); the managed hook is used",
                    r.tool,
                    r.scope,
                    super::connect_cmd::MANAGED_HOOKS_ONLY
                ),
            );
            continue;
        }
        problems.extend(r.hook_off.iter().cloned());
        if problems.is_empty() {
            report.add(
                "agent_hook",
                Status::Ok,
                format!(
                    "{} ({}): hook in {file}{}",
                    r.tool,
                    r.scope,
                    if r.fail_closed {
                        ""
                    } else if r.tool == "gemini" {
                        // Gemini CLI blocks on any exit status but 0 and 1.
                        " (Gemini CLI runs the tool call if shellfirm exits with status 1; a \
                         missing binary or a crash blocks it)"
                    } else {
                        " (the agent runs the tool call if shellfirm cannot run)"
                    }
                ),
            );
        } else {
            report.add(
                "agent_hook",
                Status::Warn,
                format!(
                    "{} ({}): hook in {file}: {}{rerun}",
                    r.tool,
                    r.scope,
                    problems.join("; "),
                ),
            );
        }
    }
    if !any {
        report.add(
            "agent_hook",
            Status::Info,
            "no AI-agent hook installed (see `shellfirm connect --help`)",
        );
    }
}

/// Findings about the shell hook: they fail when the hook is missing.
const SHELL_HOOK_FINDINGS: &[&str] = &[
    "session",
    "rc_file",
    "hook_loaded",
    "enter",
    "ctrl_o",
    "widgets",
];

/// A machine set up for AI agents only: no shell hook at all, and every
/// agent hook found is in order. The missing shell hook is then a warning,
/// not a failure (exit 0), so an agent-only rollout can be checked.
fn agent_only_setup(report: &mut Report, shell_hook_absent: bool) {
    let agent = |s: Status| {
        report
            .findings
            .iter()
            .any(|f| f.id == "agent_hook" && f.status == s)
    };
    if !shell_hook_absent || !agent(Status::Ok) || agent(Status::Warn) {
        return;
    }
    let mut changed = false;
    for f in &mut report.findings {
        if f.status == Status::Fail && SHELL_HOOK_FINDINGS.contains(&f.id) {
            f.status = Status::Warn;
            changed = true;
        }
    }
    if changed {
        report.add(
            "agent_only",
            Status::Info,
            "no shell hook is installed, but the AI-agent hooks are in place: doctor does not \
             fail for the shell. Run `shellfirm init` to check commands you type too.",
        );
    }
}

/// settings.yaml parses: `ok`, unless `shellfirm sandbox` refuses some
/// of its entries (`refused`).
fn valid_settings(report: &mut Report, path: &str, refused: &[String]) {
    if refused.is_empty() {
        report.add("settings", Status::Ok, format!("{path} is valid"));
    } else {
        report.add(
            "settings",
            Status::Warn,
            format!(
                "{path} parses, but `shellfirm sandbox` refuses it: {}; fix it with \
                 `shellfirm config edit`",
                refused.join("; ")
            ),
        );
    }
}

fn check_config(report: &mut Report) -> serde_json::Value {
    let config = match Config::new(None) {
        Ok(c) => c,
        Err(e) => {
            report.add(
                "config",
                Status::Fail,
                format!("could not determine the configuration directory: {e}"),
            );
            return json!({ "error": e.to_string() });
        }
    };
    let (settings, settings_error) = config.load_settings_lenient();
    let path = config.setting_file_path.display().to_string();
    match &settings_error {
        Some(e) => report.add(
            "settings",
            Status::Fail,
            format!("{path} is invalid (built-in defaults are used for the bad values): {e}"),
        ),
        None if config.setting_file_path.exists() => valid_settings(
            report,
            &path,
            &super::sandbox_cmd::settings_errors(
                &dirs::home_dir().unwrap_or_default(),
                &settings.sandbox,
            ),
        ),
        None => report.add(
            "settings",
            Status::Info,
            format!("{path} does not exist yet (built-in defaults)"),
        ),
    }
    check_default_groups(report, &settings);
    let custom = shellfirm::config::load_custom_checks_report(&config.custom_checks_dir());
    if custom.warnings.is_empty() {
        report.add(
            "custom_checks",
            Status::Ok,
            format!("{} custom check(s) loaded", custom.checks.len()),
        );
    } else {
        report.add(
            "custom_checks",
            Status::Warn,
            format!(
                "{} custom check(s) loaded, {} problem(s): {}",
                custom.checks.len(),
                custom.warnings.len(),
                custom.warnings.join("; ")
            ),
        );
    }
    // `shellfirm sandbox`: say when an agent's sandbox lost shellfirm's
    // entries (or was turned off) after it was set up.
    let sandboxes = super::sandbox_cmd::sandbox_status(
        &dirs::home_dir().unwrap_or_default(),
        &std::env::current_dir().unwrap_or_default(),
        &config.root_folder,
        &settings.sandbox,
    );
    for row in &sandboxes {
        let status = if row.complete() {
            Status::Ok
        } else {
            Status::Warn
        };
        report.add("agent_sandbox", status, row.line());
    }
    json!({
        "settings_file": path,
        "settings_valid": settings_error.is_none(),
        "settings_error": settings_error,
        "custom_checks": custom.checks.len(),
        "custom_check_warnings": custom.warnings,
    })
}

/// Where the probe output came from.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ProbeSource {
    NewShell,
    Stdin,
}

impl ProbeSource {
    const fn describe(self) -> &'static str {
        match self {
            Self::NewShell => "a new interactive shell",
            Self::Stdin => "this shell (stdin)",
        }
    }
}

/// Marker the bash new-shell probe appends to `enter=` when a
/// `PROMPT_COMMAND` entry rebinds Enter at the first prompt.
const BASH_FIRST_PROMPT_REBIND: &str = "(rebound at the first prompt";

/// The `enter` finding. Returns whether Enter goes through shellfirm.
/// `gate`: zsh checks the line again when the line editor finishes
/// (zle-line-finish), whatever widget Enter runs.
fn check_enter(report: &mut Report, shell: Shell, value: Option<&str>, gate: bool) -> bool {
    match value {
        Some(v)
            if gate
                && shell == Shell::Zsh
                && (v.starts_with("bypass:") || v.starts_with("unknown:")) =>
        {
            let w = v.split_once(':').map_or(v, |(_, w)| w);
            report.add(
                "enter",
                Status::Ok,
                format!(
                    "Enter runs the `{w}` widget, which may call zsh's built-in `.accept-line`; \
                     shellfirm checks the line when zsh finishes reading it (zle-line-finish), \
                     so it is still checked"
                ),
            );
            true
        }
        Some("ok") => {
            report.add("enter", Status::Ok, "Enter runs commands through shellfirm");
            true
        }
        Some("n/a") => {
            report.add(
                "enter",
                Status::Warn,
                "line editing is off: the fallback DEBUG-trap hook is used (commands hidden from history are not checked)",
            );
            true
        }
        // zsh: a widget bound to Enter that calls the (checked) accept-line.
        Some(v) if v.starts_with("chained:") => {
            let w = &v["chained:".len()..];
            report.add(
                "enter",
                Status::Ok,
                if shell == Shell::Fish {
                    format!("Enter runs `{w}`, which calls the checked `commandline -f execute`")
                } else {
                    format!("Enter runs the `{w}` widget, which calls the checked accept-line")
                },
            );
            true
        }
        Some(v) if v.starts_with("bypass:") => {
            report.add(
                "enter",
                Status::Fail,
                format!(
                    "Enter runs `{}`, which calls zsh's built-in `.accept-line`: commands are NOT checked",
                    &v["bypass:".len()..]
                ),
            );
            false
        }
        Some(v)
            if shell == Shell::Zsh && (v.starts_with("unknown:") || v.starts_with("rebound:")) =>
        {
            let w = v.split_once(':').map_or(v, |(_, w)| w);
            report.add(
                "enter",
                Status::Warn,
                format!(
                    "Enter runs the `{w}` widget; shellfirm cannot tell whether it calls the \
                     checked accept-line (`zle accept-line`) or bypasses it (`zle .accept-line`)"
                ),
            );
            true
        }
        // bash, new-shell probe: a PROMPT_COMMAND entry that runs after
        // shellfirm's rebinds Enter with `builtin bind` (a plain `bind` is
        // wrapped again at once), so the first command is not checked.
        Some(v) if shell == Shell::Bash && v.contains(BASH_FIRST_PROMPT_REBIND) => {
            let keys = v.split(" (").next().unwrap_or(v).trim();
            report.add(
                "enter",
                Status::Fail,
                format!(
                    "a PROMPT_COMMAND entry that runs after shellfirm's rebinds Enter ({keys}) with \
                     `builtin bind` at the first prompt: the first command of a new shell is NOT \
                     checked (shellfirm warns after it and checks the commands that follow). \
                     Have the plugin use `bind` instead of `builtin bind`; shellfirm wraps a \
                     `bind` that changes Enter again at once"
                ),
            );
            false
        }
        Some(other) => {
            report.add(
                "enter",
                Status::Fail,
                format!(
                    "Enter is bound to something else ({}): commands are NOT checked",
                    other.trim()
                ),
            );
            false
        }
        None => true,
    }
}

/// Turn the probe output into findings. Returns whether Enter goes through
/// shellfirm.
#[allow(clippy::too_many_lines)]
fn check_probe(
    report: &mut Report,
    shell: Shell,
    probe: &BTreeMap<String, String>,
    source: ProbeSource,
) -> bool {
    let get = |k: &str| probe.get(k).map(String::as_str);
    let Some(version) = get("hook_version").filter(|v| !v.is_empty()) else {
        let msg = match source {
            ProbeSource::NewShell => format!("a new interactive {shell} does not load the shellfirm hook"),
            ProbeSource::Stdin => format!(
                "the probe output on stdin has no hook version: the shellfirm hook is not loaded in this {shell}"
            ),
        };
        report.add("hook_loaded", Status::Fail, msg);
        return false;
    };
    if let Some(probed) = get("shell").and_then(Shell::from_name) {
        if probed != shell {
            report.add(
                "hook_loaded",
                Status::Warn,
                format!("the probe output is from {probed}, not {shell}"),
            );
        }
    }
    if version == HOOK_VERSION {
        report.add(
            "hook_loaded",
            Status::Ok,
            format!("hook loaded (version {version})"),
        );
    } else {
        report.add(
            "hook_loaded",
            Status::Warn,
            format!(
                "the hook in this shell is version {version}, this shellfirm ships {HOOK_VERSION}: \
                 restart the shell (`{}`)",
                shell.activate_hint()
            ),
        );
    }

    let gate = shell == Shell::Zsh && get("line_finish") == Some("ok");
    let mut enter_ok = check_enter(report, shell, get("enter"), gate);
    if let Some(chain) = get("enter_chain").filter(|c| !c.is_empty()) {
        report.add(
            "enter",
            Status::Info,
            format!("the Enter binding that was there before shellfirm (`{chain}`) runs after the check"),
        );
    }

    match shell {
        Shell::Bash => {
            if get("ctrl_o") == Some("unchecked") {
                enter_ok = false;
                report.add(
                    "ctrl_o",
                    Status::Fail,
                    "Ctrl-O (operate-and-get-next) is bound directly: commands run with it are NOT checked",
                );
            }
            match (get("fc"), get("fc_builtin")) {
                (Some("ok"), Some("on")) => report.add(
                    "fc",
                    Status::Warn,
                    "fc typed on the line (also as `command fc` / `builtin fc` or inside `eval`) \
                     and Ctrl-X Ctrl-E / vi `v` are checked, but the fc builtin is turned on again \
                     (`enable fc`): a `command fc -s` / `builtin fc -s` run from a function, a \
                     variable, PROMPT_COMMAND or a trap re-runs history unchecked",
                ),
                (Some("ok"), Some("off-no-handler")) => report.add(
                    "fc",
                    Status::Warn,
                    "fc typed on the line is checked, but command_not_found_handle was replaced \
                     after shellfirm loaded: `command fc` run from a function, a variable, \
                     PROMPT_COMMAND or a trap fails instead of running the checked fc",
                ),
                (Some("ok"), _) => report.add(
                    "fc",
                    Status::Ok,
                    "fc (editor and `fc -s` re-runs, also as `command fc`, `builtin fc`, inside \
                     `eval` or in a function) and Ctrl-X Ctrl-E / vi `v` are checked; a \
                     `command fc` that runs from a function, a variable, PROMPT_COMMAND or a \
                     trap goes to the checked fc (the fc builtin is turned off; `builtin fc` \
                     works only on a line typed at the prompt)",
                ),
                (Some(_), _) => report.add(
                    "fc",
                    Status::Warn,
                    "a user-defined `fc` replaces shellfirm's: Ctrl-X Ctrl-E / vi `v` / fc run edited or re-run commands unchecked",
                ),
                (None, _) => {}
            }
            if let Some(k) = get("rewrapped").filter(|k| !k.is_empty()) {
                report.add(
                    "enter",
                    Status::Info,
                    format!(
                        "Enter was rebound after shellfirm loaded ({k}); shellfirm wrapped it at \
                         the prompt, so the line is checked first and then that binding runs"
                    ),
                );
            }
            if get("precmd") == Some("missing") {
                report.add(
                    "precmd",
                    Status::Warn,
                    "__shellfirm_precmd is not in PROMPT_COMMAND",
                );
            }
        }
        Shell::Zsh => {
            match get("widgets") {
                Some("ok") | None => {}
                Some(bad) => {
                    enter_ok = false;
                    report.add(
                        "widgets",
                        Status::Fail,
                        format!("accept-line widgets are not wrapped by shellfirm: {bad}"),
                    );
                }
            }
            if let Some(v) = get("isearch").filter(|v| *v != "ok") {
                report.add(
                    "isearch",
                    Status::Warn,
                    format!(
                        "Ctrl-R (incremental search) + Enter is not routed through shellfirm ({v})"
                    ),
                );
            }
            if let Some(w) = get("rewrapped").filter(|w| !w.is_empty()) {
                report.add(
                    "widgets",
                    Status::Info,
                    format!(
                        "`{w}` was replaced or bound to Enter after shellfirm loaded (a plugin); \
                         shellfirm wrapped it at the prompt, so the line is still checked first"
                    ),
                );
            }
            if get("line_finish") == Some("missing") {
                report.add(
                    "line_finish",
                    Status::Warn,
                    "the zle-line-finish check is not in place (zsh older than 5.3, or a plugin \
                     replaced the zle-line-finish widget): a plugin that binds Enter after the \
                     first prompt (zinit turbo, zsh-defer, `sched`) can run one command unchecked",
                );
            }
            if get("correct") == Some("checked") {
                report.add(
                    "correct",
                    Status::Info,
                    "CORRECT is on: a mistyped command name is also checked as each command \
                     zsh could correct it to",
                );
            }
            match get("fc") {
                Some("ok") => report.add(
                    "fc",
                    Status::Ok,
                    "fc and r (editor and re-runs, also as `builtin fc`/`builtin r` or inside \
                     `eval`) are checked",
                ),
                Some(_) => report.add(
                    "fc",
                    Status::Warn,
                    "`fc` / `r` are your own alias or function: commands they edit or re-run are only checked when typed as `r ...` / `fc -e - ...`",
                ),
                None => {}
            }
        }
        Shell::Fish if get("execute_wrapper") == Some("missing") => {
            report.add(
                "execute_wrapper",
                Status::Warn,
                "`commandline -f execute` (atuin enter_accept, transient prompts) is not checked",
            );
        }
        _ => {}
    }
    if get("legacy_hook") == Some("active") {
        report.add(
            "legacy_hook",
            Status::Fail,
            "an old (0.3.x) shellfirm hook is active in this shell: it prompts twice; remove it from the rc file",
        );
    }
    if get("bypass_seen") == Some("yes") {
        enter_ok = false;
        report.add(
            "bypass",
            Status::Fail,
            "a command in this session ran without passing through shellfirm (Enter was rebound)",
        );
    }
    let plugins: Vec<&str> = get("plugins")
        .unwrap_or_default()
        .split_whitespace()
        .collect();
    for p in &plugins {
        let (name, state) = p.split_once(':').unwrap_or((p, ""));
        let (status, msg) = match (shell, name, state) {
            (Shell::Bash, "atuin", "checked") => (Status::Ok, "atuin enter_accept is checked".to_string()),
            (Shell::Bash, "atuin", _) => (
                Status::Warn,
                "atuin enter_accept runs commands unchecked (set `enter_accept = false` in atuin's config)".to_string(),
            ),
            (Shell::Bash, "ble.sh", _) => (
                Status::Warn,
                "ble.sh replaces readline: the shellfirm key bindings are not used".to_string(),
            ),
            (Shell::Fish, "transient", "chained") => (
                Status::Ok,
                "transient prompt: its Enter binding runs after the check".to_string(),
            ),
            (Shell::Fish, "transient", _) => (
                Status::Info,
                "transient prompt: its `commandline -f execute` is checked".to_string(),
            ),
            _ => (Status::Info, format!("{name} detected")),
        };
        report.add("plugin", status, msg);
    }
    enter_ok
}

fn print_text(shell: Shell, source: &str, report: &Report) {
    // Wrapped between words to the terminal width (unchanged when piped).
    let wrap = shellfirm::prompt::wrap_for_stdout;
    println!(
        "{}\n",
        wrap(&ascii_fallback(&format!(
            "shellfirm doctor — {shell} (from {source})"
        )))
    );
    for f in &report.findings {
        println!(
            "{}",
            wrap(&ascii_fallback(&format!(
                "  [{}] {:<16} {}",
                f.status.symbol(),
                f.id,
                f.message
            )))
        );
    }
    println!();
}

#[allow(clippy::too_many_lines)]
pub fn run(matches: &ArgMatches) -> shellfirm::CmdExit {
    let format = matches
        .get_one::<String>("format")
        .map_or("text", String::as_str);
    let detected = Shell::detect_current();
    let explicit = matches
        .get_one::<String>("shell")
        .and_then(|s| Shell::from_name(s));
    let (shell, source) = explicit.map_or_else(
        || detected.map_or((None, "unknown"), |(s, src)| (Some(s), src.describe())),
        |s| (Some(s), "--shell"),
    );
    let Some(shell) = shell else {
        return shellfirm::CmdExit {
            code: exitcode::USAGE,
            message: Some(
                "Could not detect your shell (parent process or $SHELL). Use: shellfirm doctor --shell <shell>"
                    .into(),
            ),
        };
    };
    // Only the shell doctor was started from can be asked whether it loaded
    // the hook.
    let from_this_shell =
        detected.is_some_and(|(s, src)| s == shell && src == ShellSource::ParentProcess);
    let session = if from_this_shell {
        detect_session()
    } else {
        Session::Unknown
    };
    let use_stdin = matches.get_flag("stdin");

    let mut report = Report::default();
    report.add(
        "shell",
        Status::Info,
        format!("{shell} (detected from {source})"),
    );
    if session != Session::Inherited {
        check_session(&mut report, shell, session);
    }
    let binary = check_binary(&mut report);
    let rc = init::rc_report(shell);

    let probe_source = if use_stdin {
        ProbeSource::Stdin
    } else {
        ProbeSource::NewShell
    };
    let probe_text = if use_stdin {
        let mut s = String::new();
        let _ = std::io::stdin().take(1024 * 1024).read_to_string(&mut s);
        if s.trim().is_empty() {
            Err(format!(
                "no probe output on stdin: the shellfirm hook is not loaded in this shell (`{}` \
                 does not exist). Load it with `{}` (after `shellfirm init {shell}`)",
                probe_function(shell),
                shell.activate_hint()
            ))
        } else {
            Ok(s)
        }
    } else {
        run_probe(shell)
    };
    let probe = probe_text
        .as_ref()
        .map_or_else(|_| BTreeMap::new(), |t| parse_probe(t));
    let mut probe_report = Report::default();
    let enter = match (&probe_text, shell) {
        (Ok(_), _) => Some(check_probe(&mut probe_report, shell, &probe, probe_source)),
        (Err(e), _) if use_stdin => {
            probe_report.add("hook_loaded", Status::Fail, e.clone());
            Some(false)
        }
        (Err(e), Shell::Bash | Shell::Zsh | Shell::Fish) => {
            probe_report.add(
                "hook_loaded",
                Status::Warn,
                format!("live check skipped: {e}"),
            );
            None
        }
        (Err(_), _) => {
            probe_report.add(
                "key_bindings",
                Status::Info,
                format!(
                    "doctor cannot inspect {shell}'s key bindings from outside; the session and \
                     rc file checks above are all it can verify"
                ),
            );
            None
        }
    };
    // The rc file is judged by what a new shell does: the probe of a new
    // shell, or (no new-shell probe) this session. A probe read from stdin
    // describes this session, which may have loaded the hook by hand.
    let probe_hooked = probe.get("hook_version").is_some_and(|v| !v.is_empty());
    let live_hooked = match probe_source {
        ProbeSource::NewShell if probe_text.is_ok() => probe_hooked,
        _ => probe_hooked || session == Session::Hooked,
    };
    if session == Session::Inherited {
        // After `exec`, only a new shell tells what this one most likely did.
        let mut s = Report::default();
        if matches!(probe_source, ProbeSource::NewShell) && probe_text.is_ok() {
            check_inherited_session(&mut s, shell, probe_hooked);
        } else {
            check_session(&mut s, shell, session);
        }
        report.findings.splice(1..1, s.findings);
    }
    check_rc(
        &mut report,
        shell,
        &rc,
        live_hooked,
        session == Session::Hooked,
    );
    report.findings.extend(probe_report.findings);
    if let Some(l) = shell.limitation() {
        report.add("limitation", Status::Warn, l);
    }
    if let Some(var) = match shell {
        Shell::Bash | Shell::Zsh => Some("$?"),
        Shell::Fish => Some("$status"),
        _ => None,
    } {
        report.add(
            "exit_status",
            Status::Info,
            format!(
                "after a line shellfirm blocked, `{var}` still holds the status of the command \
                 before it: the blocked line never ran, and {shell} gives a key binding no way \
                 to set it"
            ),
        );
    }
    let config = check_config(&mut report);
    check_agent_hooks(
        &mut report,
        &super::connect_cmd::integration_status(
            &dirs::home_dir().unwrap_or_default(),
            &std::env::current_dir().unwrap_or_default(),
        ),
    );
    let shell_hook_absent =
        !rc.installed && rc.loaded_from.is_none() && !live_hooked && session != Session::Hooked;
    agent_only_setup(&mut report, shell_hook_absent);
    let failed = report.failed();

    if format == "json" {
        let out = json!({
            "schema_version": SCHEMA_VERSION,
            "version": crate_version!(),
            "shell": shell.name(),
            "detected_from": source,
            "ok": !failed,
            "session_hooked": match session {
                Session::Hooked => Some(true),
                Session::NotHooked { .. } => Some(false),
                Session::Inherited | Session::Unknown => None,
            },
            "enter_routes_through_shellfirm": enter,
            "hook_version_expected": HOOK_VERSION,
            "hook_version": probe.get("hook_version"),
            "probe_source": probe_source.describe(),
            "probe": probe,
            "binary": binary,
            "rc_file": rc,
            "config": config,
            "findings": report.findings,
        });
        println!("{}", serde_json::to_string_pretty(&out).unwrap_or_default());
    } else {
        print_text(shell, source, &report);
        if !use_stdin && probe_invocation(shell).is_some() {
            if matches!(session, Session::NotHooked { .. }) {
                println!(
                    "{}\n",
                    shellfirm::prompt::wrap_for_stdout(&format!(
                        "This session is not protected; the live check ran in {}. Start a new shell: {}",
                        probe_source.describe(),
                        shell.activate_hint()
                    ))
                );
            } else if live_hooked {
                // Only useful when the probe function exists.
                println!(
                    "{}\n",
                    shellfirm::prompt::wrap_for_stdout(&format!(
                        "Live check ran in {}. To check this session (bindings changed after startup):\n  {} | shellfirm doctor --stdin",
                        probe_source.describe(),
                        probe_function(shell)
                    ))
                );
            }
        }
    }

    shellfirm::CmdExit {
        code: if failed { EXIT_FAILED } else { exitcode::OK },
        message: None,
    }
}

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

    fn probe(text: &str) -> BTreeMap<String, String> {
        parse_probe(&text.replace("{V}", HOOK_VERSION))
    }

    #[test]
    fn parses_probe_lines() {
        let p =
            parse_probe("shell=bash\nhook_version=4\nenter=ok\nnoise line\nplugins=atuin fzf\n");
        assert_eq!(p.get("shell").map(String::as_str), Some("bash"));
        assert_eq!(p.get("plugins").map(String::as_str), Some("atuin fzf"));
        assert!(!p.contains_key("noise line"));
    }

    #[test]
    fn missing_hook_fails() {
        let mut r = Report::default();
        assert!(!check_probe(
            &mut r,
            Shell::Bash,
            &BTreeMap::new(),
            ProbeSource::NewShell
        ));
        assert!(r.failed());
        let mut r = Report::default();
        check_probe(&mut r, Shell::Zsh, &BTreeMap::new(), ProbeSource::Stdin);
        assert!(r.findings[0].message.contains("not loaded in this zsh"));
    }

    #[test]
    fn rebound_enter_fails_in_bash() {
        let mut r = Report::default();
        let p = probe("shell=bash\nhook_version={V}\nenter= emacs:\\C-m\nfc=ok\n");
        assert!(!check_probe(&mut r, Shell::Bash, &p, ProbeSource::Stdin));
        assert!(r.failed());
    }

    #[test]
    fn first_prompt_rebind_has_its_own_message_in_bash() {
        let mut r = Report::default();
        let p = probe(
            "shell=bash\nhook_version={V}\nenter=emacs:\\C-m (rebound at the first prompt by a \
             PROMPT_COMMAND entry that runs after shellfirm looks: the first command of a new \
             shell is not checked)\nfc=ok\n",
        );
        assert!(!check_probe(&mut r, Shell::Bash, &p, ProbeSource::NewShell));
        let msg = &r.findings.iter().find(|f| f.id == "enter").unwrap().message;
        assert!(msg.contains("builtin bind"), "{msg}");
        assert!(
            msg.contains("first command of a new shell is NOT checked"),
            "{msg}"
        );
        assert!(msg.contains("(emacs:\\C-m)"), "{msg}");
        assert!(!msg.contains("something else"), "{msg}");
    }

    #[test]
    fn rebound_ctrl_o_fails_in_bash() {
        let mut r = Report::default();
        let p = probe("shell=bash\nhook_version={V}\nenter=ok\nctrl_o=unchecked\nfc=ok\n");
        assert!(!check_probe(&mut r, Shell::Bash, &p, ProbeSource::Stdin));
        assert!(r.failed());
    }

    #[test]
    fn healthy_probe_passes() {
        let mut r = Report::default();
        let p = probe(
            "shell=zsh\nhook_version={V}\nwidgets=ok\nenter=ok\nisearch=ok\nprecmd=ok\nfc=ok\nplugins=atuin\n",
        );
        assert!(check_probe(&mut r, Shell::Zsh, &p, ProbeSource::NewShell));
        assert!(!r.failed());
    }

    #[test]
    fn zsh_enter_widgets_are_classified() {
        // zsh-abbr / magic-enter style: calls `zle accept-line` (checked).
        let mut r = Report::default();
        let p = probe("shell=zsh\nhook_version={V}\nwidgets=ok\nenter=chained:magic-enter\n");
        assert!(check_probe(&mut r, Shell::Zsh, &p, ProbeSource::Stdin));
        assert!(r
            .findings
            .iter()
            .all(|f| f.status != Status::Warn && f.status != Status::Fail));
        // `zle .accept-line`: a bypass.
        let mut r = Report::default();
        let p = probe("shell=zsh\nhook_version={V}\nwidgets=ok\nenter=bypass:my-enter\n");
        assert!(!check_probe(&mut r, Shell::Zsh, &p, ProbeSource::Stdin));
        assert!(r.failed());
        // Can't tell: a warning, not a failure.
        let mut r = Report::default();
        let p = probe("shell=zsh\nhook_version={V}\nwidgets=ok\nenter=unknown:odd\n");
        assert!(check_probe(&mut r, Shell::Zsh, &p, ProbeSource::Stdin));
        assert!(!r.failed());
        assert!(r
            .findings
            .iter()
            .any(|f| f.id == "enter" && f.status == Status::Warn));
    }

    #[test]
    fn zsh_line_finish_check_covers_an_enter_widget_that_bypasses() {
        // `zle .accept-line` in the Enter widget, but zle-line-finish checks
        // the line anyway: ok.
        let mut r = Report::default();
        let p = probe(
            "shell=zsh\nhook_version={V}\nwidgets=ok\nenter=bypass:my-enter\nline_finish=ok\n",
        );
        assert!(check_probe(&mut r, Shell::Zsh, &p, ProbeSource::Stdin));
        assert!(!r.failed());
        assert!(r.findings.iter().any(|f| f.id == "enter"
            && f.status == Status::Ok
            && f.message.contains("zle-line-finish")));
        // Without it, a plugin that binds Enter later is a gap: a warning.
        let mut r = Report::default();
        let p = probe("shell=zsh\nhook_version={V}\nwidgets=ok\nenter=ok\nline_finish=missing\n");
        assert!(check_probe(&mut r, Shell::Zsh, &p, ProbeSource::Stdin));
        assert!(r
            .findings
            .iter()
            .any(|f| f.id == "line_finish" && f.status == Status::Warn));
        // A bypass seen in the session still fails.
        let mut r = Report::default();
        let p = probe("shell=zsh\nhook_version={V}\nenter=ok\nline_finish=ok\nbypass_seen=yes\n");
        assert!(!check_probe(&mut r, Shell::Zsh, &p, ProbeSource::Stdin));
    }

    #[test]
    fn every_shell_uses_the_same_probe_name() {
        for shell in [Shell::Bash, Shell::Zsh, Shell::Fish] {
            assert_eq!(probe_function(shell), "__shellfirm_doctor_probe");
            let (_, args) = probe_invocation(shell).expect("probe");
            assert!(args.iter().any(|a| a.contains("__shellfirm_doctor_probe")));
        }
    }

    #[test]
    fn fish_rebound_enter_fails() {
        let mut r = Report::default();
        let p =
            probe("shell=fish\nhook_version={V}\nenter=default:\\r=execute\nexecute_wrapper=ok\n");
        assert!(!check_probe(&mut r, Shell::Fish, &p, ProbeSource::Stdin));
        assert!(r.failed());
    }

    #[test]
    fn old_hook_version_warns() {
        let mut r = Report::default();
        let p = parse_probe("shell=fish\nhook_version=1\nenter=ok\n");
        check_probe(&mut r, Shell::Fish, &p, ProbeSource::NewShell);
        assert!(r
            .findings
            .iter()
            .any(|f| f.id == "hook_loaded" && f.status == Status::Warn));
    }

    #[test]
    fn session_is_told_by_the_hook_pid() {
        assert_eq!(session_state(Some("42"), Some(42)), Session::Hooked);
        assert_eq!(
            session_state(None, Some(42)),
            Session::NotHooked { outer: None }
        );
        // `zsh -f` started from a protected bash: the marker is bash's.
        assert_eq!(
            session_state(Some("9"), Some(42)),
            Session::NotHooked { outer: Some(9) }
        );
        assert_eq!(session_state(Some("x"), None), Session::Unknown);
    }

    #[test]
    fn exec_then_reloaded_hook_is_hooked() {
        // `exec bash` that loaded the hook again: a new load marker.
        assert_eq!(
            inherited_or_reloaded(Some("42.1"), Some("42.7")),
            Session::Hooked
        );
        // The marker it started with: not known.
        assert_eq!(
            inherited_or_reloaded(Some("42.7"), Some("42.7")),
            Session::Inherited
        );
        assert_eq!(inherited_or_reloaded(None, None), Session::Inherited);
        assert_eq!(
            environ_value(b"A=1\0SHELLFIRM_HOOK_LOAD=42.7\0", HOOK_LOAD_ENV).as_deref(),
            Some("42.7")
        );
        // Right after `init --uninstall`: still protected until a restart.
        let rc = init::RcReport::default();
        let mut r = Report::default();
        check_rc(&mut r, Shell::Bash, &rc, false, true);
        assert!(r.findings[0]
            .message
            .contains("stays protected until you restart"));
    }

    #[test]
    fn exec_inherited_marker_is_detected() {
        let env = b"PATH=/bin\0SHELLFIRM_HOOK_PID=42\0HOME=/h\0";
        assert!(environ_has_marker(env, 42));
        assert!(!environ_has_marker(env, 4));
        assert!(!environ_has_marker(b"SHELLFIRM_HOOK_PID=420\0", 42));
        let mut r = Report::default();
        check_inherited_session(&mut r, Shell::Bash, false);
        assert!(r.failed());
        let mut r = Report::default();
        check_inherited_session(&mut r, Shell::Bash, true);
        assert!(!r.failed());
        let mut r = Report::default();
        check_session(&mut r, Shell::Bash, Session::Inherited);
        assert!(r.findings[0].message.contains("exec"));
        assert_eq!(r.findings[0].status, Status::Warn);
    }

    #[test]
    fn fish_enter_chain_is_ok() {
        let mut r = Report::default();
        let p = probe(
            "shell=fish\nhook_version={V}\nenter=chained:transient_execute\nexecute_wrapper=ok\n",
        );
        assert!(check_probe(&mut r, Shell::Fish, &p, ProbeSource::Stdin));
        assert!(!r.failed());
        assert!(r
            .findings
            .iter()
            .any(|f| f.message.contains("commandline -f execute")));
    }

    #[test]
    fn zsh_rewrapped_widget_is_reported() {
        let mut r = Report::default();
        let p = probe("shell=zsh\nhook_version={V}\nwidgets=ok\nenter=ok\nrewrapped=accept-line\n");
        assert!(check_probe(&mut r, Shell::Zsh, &p, ProbeSource::Stdin));
        assert!(r
            .findings
            .iter()
            .any(|f| f.id == "widgets" && f.status == Status::Info));
    }

    #[test]
    fn unprotected_session_fails() {
        let mut r = Report::default();
        check_session(&mut r, Shell::Zsh, Session::NotHooked { outer: None });
        assert!(r.failed());
        assert!(r.findings[0].message.contains("exec zsh"));
        let mut r = Report::default();
        check_session(&mut r, Shell::Zsh, Session::Hooked);
        assert!(!r.failed());
    }

    #[test]
    fn default_groups_off_warn_without_failing() {
        let mut r = Report::default();
        check_default_groups(&mut r, &shellfirm::config::Settings::default());
        assert!(r.findings.is_empty());
        let settings = shellfirm::config::Settings {
            disabled_groups: vec!["shell".into()],
            ..Default::default()
        };
        check_default_groups(&mut r, &settings);
        assert!(!r.failed());
        assert_eq!(r.findings[0].status, Status::Warn);
        assert!(
            r.findings[0]
                .message
                .contains("`shellfirm config groups --enable shell`"),
            "{}",
            r.findings[0].message
        );
    }

    #[test]
    fn rc_loaded_elsewhere_is_not_an_error() {
        let rc = init::RcReport {
            path: Some(PathBuf::from("/h/.zshrc")),
            exists: true,
            installed: false,
            load_count: 0,
            legacy_hook_line: None,
            loaded_from: None,
        };
        let mut r = Report::default();
        check_rc(&mut r, Shell::Zsh, &rc, true, false);
        assert!(!r.failed());
        assert!(!r.findings[0].message.contains("run `shellfirm init"));
        let mut r = Report::default();
        check_rc(&mut r, Shell::Zsh, &rc, false, false);
        assert!(r.failed());
        let rc = init::RcReport {
            loaded_from: Some(PathBuf::from("/h/.config/fish/conf.d/shellfirm.fish")),
            ..rc
        };
        let mut r = Report::default();
        check_rc(&mut r, Shell::Fish, &rc, false, false);
        assert!(!r.failed());
    }

    #[test]
    fn agent_only_setup_does_not_fail_for_the_missing_shell_hook() {
        let base = || {
            let mut r = Report::default();
            r.add(
                "rc_file",
                Status::Fail,
                "~/.zshrc does not load the shellfirm hook",
            );
            r.add("hook_loaded", Status::Fail, "not loaded");
            r.add("binary", Status::Ok, "ok");
            r
        };
        // Agent hooks in order: the shell findings become warnings.
        let mut r = base();
        r.add("agent_hook", Status::Ok, "claude-code (user): hook in x");
        agent_only_setup(&mut r, true);
        assert!(!r.failed());
        assert!(r.findings.iter().any(|f| f.id == "agent_only"));
        // A shell hook that is installed but broken still fails.
        let mut r = base();
        r.add("agent_hook", Status::Ok, "claude-code (user): hook in x");
        agent_only_setup(&mut r, false);
        assert!(r.failed());
        // No agent hook, or one with a problem: still a failure.
        let mut r = base();
        r.add("agent_hook", Status::Info, "no AI-agent hook installed");
        agent_only_setup(&mut r, true);
        assert!(r.failed());
        let mut r = base();
        r.add("agent_hook", Status::Ok, "codex (user): hook in x");
        r.add(
            "agent_hook",
            Status::Warn,
            "claude-code (user): disableAllHooks",
        );
        agent_only_setup(&mut r, true);
        assert!(r.failed());
        // Other failures (the binary) are kept.
        let mut r = base();
        r.add("binary", Status::Fail, "missing");
        r.add("agent_hook", Status::Ok, "claude-code (user): hook in x");
        agent_only_setup(&mut r, true);
        assert!(r.failed());
    }

    #[test]
    fn agent_hook_advice_matches_the_problem() {
        let row =
            |hook_off: Vec<String>, installed: bool| super::super::connect_cmd::IntegrationStatus {
                tool: "gemini",
                scope: "user",
                hook_file: Some("s.json".into()),
                hook_installed: installed,
                hook_present: true,
                shell_tools_missing: Vec::new(),
                file_tools_covered: true,
                legacy_hook: false,
                fail_closed: false,
                config_dir: None,
                mcp_file: None,
                mcp_registered: false,
                notes: Vec::new(),
                hook_off,
                error: None,
            };
        let msg = |r| {
            let mut rep = Report::default();
            check_agent_hooks(&mut rep, &[r]);
            rep.findings[0].message.clone()
        };
        let m = msg(row(
            vec!["hooks are turned off (hooksConfig.enabled: false; set it to true)".into()],
            true,
        ));
        assert!(m.contains("set it to true") && !m.contains("re-run"), "{m}");
        let m = msg(row(Vec::new(), false));
        assert!(m.contains("re-run `shellfirm connect gemini`"), "{m}");
        let m = msg(row(Vec::new(), true));
        assert!(
            m.contains("exits with status 1; a missing binary or a crash blocks it"),
            "{m}"
        );
    }

    #[test]
    fn a_managed_hook_covers_a_user_hook_turned_off_by_managed_only() {
        let row = |scope, hook_off: Vec<String>| super::super::connect_cmd::IntegrationStatus {
            tool: "claude-code",
            scope,
            hook_file: Some("s.json".into()),
            hook_installed: true,
            hook_present: true,
            shell_tools_missing: Vec::new(),
            file_tools_covered: true,
            legacy_hook: false,
            fail_closed: true,
            config_dir: None,
            mcp_file: None,
            mcp_registered: false,
            notes: Vec::new(),
            hook_off,
            error: None,
        };
        let only = vec!["allowManagedHooksOnly is true in /etc/m.json: ...".to_string()];
        let statuses = |rows: &[super::super::connect_cmd::IntegrationStatus]| {
            let mut rep = Report::default();
            check_agent_hooks(&mut rep, rows);
            rep.findings.iter().map(|f| f.status).collect::<Vec<_>>()
        };
        // Without a managed hook, the user hook being off is a warning.
        assert_eq!(statuses(&[row("user", only.clone())]), [Status::Warn]);
        assert_eq!(
            statuses(&[row("user", only.clone()), row("managed", Vec::new())]),
            [Status::Info, Status::Ok]
        );
        // A managed hook that is itself off does not cover it.
        let off = vec!["disableAllHooks is true in /etc/m.json".to_string()];
        assert_eq!(
            statuses(&[row("user", only), row("managed", off)]),
            [Status::Warn, Status::Warn]
        );
        // An unreadable configuration is a warning, never "not installed".
        let mut unreadable = row("user", Vec::new());
        unreadable.hook_present = false;
        unreadable.error = Some("can't read /h/.claude/settings.json: denied".into());
        let mut rep = Report::default();
        check_agent_hooks(&mut rep, &[unreadable]);
        assert_eq!(rep.findings.len(), 1);
        assert_eq!(rep.findings[0].status, Status::Warn);
        assert!(rep.findings[0].message.contains("can't read"));
        // The managed hook alone is enough for an agent-only setup.
        let mut rep = Report::default();
        check_agent_hooks(&mut rep, &[row("managed", Vec::new())]);
        assert_eq!(rep.findings[0].status, Status::Ok);
    }

    #[test]
    fn a_foreign_file_at_a_hook_path_is_a_warning() {
        let row = super::super::connect_cmd::IntegrationStatus {
            tool: "cline",
            scope: "user",
            hook_file: Some("PreToolUse".into()),
            hook_installed: false,
            hook_present: false,
            shell_tools_missing: Vec::new(),
            file_tools_covered: false,
            legacy_hook: false,
            fail_closed: false,
            config_dir: None,
            mcp_file: None,
            mcp_registered: false,
            notes: vec![
                "/h/Documents/Cline/Hooks/PreToolUse exists but was not written by shellfirm"
                    .into(),
            ],
            hook_off: Vec::new(),
            error: None,
        };
        let mut rep = Report::default();
        check_agent_hooks(&mut rep, &[row]);
        let f = &rep.findings[0];
        assert_eq!(f.status, Status::Warn);
        assert!(
            f.message.contains(
                "cline (user): /h/Documents/Cline/Hooks/PreToolUse exists but was not written"
            ),
            "{}",
            f.message
        );
    }

    #[test]
    fn settings_with_a_refused_sandbox_entry_are_not_called_valid() {
        let mut rep = Report::default();
        valid_settings(&mut rep, "s.yaml", &[]);
        assert_eq!(rep.findings[0].status, Status::Ok);
        let mut rep = Report::default();
        let refused = shellfirm_sandbox_errors();
        valid_settings(&mut rep, "s.yaml", &refused);
        let f = &rep.findings[0];
        assert_eq!(f.status, Status::Warn);
        assert!(
            f.message.contains("sandbox.deny_read: `/`") && f.message.contains("config edit"),
            "{}",
            f.message
        );
    }

    fn shellfirm_sandbox_errors() -> Vec<String> {
        let cfg = shellfirm::config::SandboxConfig {
            deny_read: vec!["/".into()],
            ..shellfirm::config::SandboxConfig::default()
        };
        super::super::sandbox_cmd::settings_errors(std::path::Path::new("/h"), &cfg)
    }
}