eclipse-core 0.15.1

Core library for eclipse: providers, tools, sessions, config, runtime
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
//! `eclipse doctor`: reach for each thing that can be wrong, and say what to do about it.
//!
//! The point is not a health score. It is that every finding carries **the command that fixes
//! it**, and that the repairs which are safe to make unattended are made unattended: create a
//! directory an install is supposed to have, restore a permission, clear a lock whose holder is
//! gone, and drop a plugin that will not load from `[plugins] enabled` — that last one because an
//! operator who has to remove a broken plugin by hand before the agent will start has been given
//! a service that limps.
//!
//! Nothing here is a policy of its own. The probes read the same config, the same store, the same
//! plugin and skill loaders the agent uses; a doctor with a second opinion about what "loads" is a
//! doctor that reports green while the run fails.
//!
//! **What is deliberately not repaired.** A broken *skill* is named and left alone: there is no
//! `[skills] disabled` list, and inventing one here would be a config key with one reader. A
//! config that does not parse is not repaired at all — a guessed fix to somebody's file is worse
//! than a sentence saying which line is wrong.

use crate::config::{Config, EnvFn};
use std::path::PathBuf;

/// How bad a finding is. `Note` is information worth printing on a healthy install; `Problem` is
/// something that will stop a run working.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Level {
    Ok,
    Note,
    Warn,
    Problem,
}

impl Level {
    pub fn label(&self) -> &'static str {
        match self {
            Level::Ok => "ok",
            Level::Note => "note",
            Level::Warn => "warn",
            Level::Problem => "problem",
        }
    }
}

/// A repair that is safe to apply without asking.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Repair {
    /// `mkdir -p`
    MakeDir(PathBuf),
    /// `chmod <mode>`, for a file that holds something private.
    Chmod(PathBuf, u32),
    /// Remove the session lock files that no process holds a lock on.
    ClearLocks(Vec<PathBuf>),
    /// Take a plugin out of `[plugins] enabled`, which is what makes the next run start clean.
    DisablePlugin(String),
    /// Forget a background task whose process is gone. Its session and its log stay: what is
    /// dropped is the registry entry that claims to be alive.
    ForgetTask(PathBuf),
}

impl Repair {
    /// One line saying what was done, for `--fix`'s output.
    pub fn describe(&self) -> String {
        match self {
            Repair::MakeDir(p) => format!("created {}", p.display()),
            Repair::Chmod(p, mode) => format!("set {} to {mode:o}", p.display()),
            Repair::ClearLocks(paths) => match paths.len() {
                1 => format!("removed the stale lock {}", paths[0].display()),
                n => format!("removed {n} stale lock files"),
            },
            Repair::DisablePlugin(name) => {
                format!("removed `{name}` from [plugins] enabled (the directory stays)")
            }
            Repair::ForgetTask(path) => format!("forgot the background task {}", path.display()),
        }
    }
}

/// One thing the doctor looked at.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Finding {
    pub level: Level,
    /// The area, printed first: `config`, `provider`, `layout`, `permissions`, `sessions`,
    /// `plugins`, `skills`, `shell`.
    pub area: &'static str,
    pub detail: String,
    /// What a person should run, or change, when this is not `Ok`.
    pub fix: Option<String>,
    /// A repair `--fix` may apply. `None` means a human decision.
    pub repair: Option<Repair>,
}

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

    pub fn new(level: Level, area: &'static str, detail: impl Into<String>) -> Self {
        Self {
            level,
            area,
            detail: detail.into(),
            fix: None,
            repair: None,
        }
    }

    pub fn fix(mut self, what: impl Into<String>) -> Self {
        self.fix = Some(what.into());
        self
    }

    pub fn repair(mut self, repair: Repair) -> Self {
        self.repair = Some(repair);
        self
    }
}

/// Whether anything is wrong, and how wrong.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Tally {
    pub problems: usize,
    pub warnings: usize,
    pub repairable: usize,
}

impl Tally {
    pub fn of(findings: &[Finding]) -> Tally {
        let mut t = Tally::default();
        for f in findings {
            match f.level {
                Level::Problem => t.problems += 1,
                Level::Warn => t.warnings += 1,
                _ => {}
            }
            if f.repair.is_some() {
                t.repairable += 1;
            }
        }
        t
    }

    /// `1 problem, 2 warnings` — or `nothing to fix` when there is nothing to say.
    pub fn summary(&self) -> String {
        if self.problems == 0 && self.warnings == 0 {
            return "nothing to fix".to_string();
        }
        let mut parts = Vec::new();
        if self.problems > 0 {
            parts.push(format!("{} problem(s)", self.problems));
        }
        if self.warnings > 0 {
            parts.push(format!("{} warning(s)", self.warnings));
        }
        parts.join(", ")
    }
}

/// Everything that can be checked without a network.
///
/// `cfg` is the config that actually loaded — if it did not load, the caller says so and stops,
/// because every probe below would then be guessing.
pub fn check(cfg: &Config, env: EnvFn<'_>) -> Vec<Finding> {
    let mut found = Vec::new();
    check_layout(cfg, env, &mut found);
    check_permissions(cfg, env, &mut found);
    check_sessions(cfg, env, &mut found);
    check_plugins(cfg, env, &mut found);
    check_skills(cfg, env, &mut found);
    check_tool_schemas(cfg, env, &mut found);
    check_vision(cfg, env, &mut found);
    check_shell(cfg, env, &mut found);
    check_tasks(cfg, env, &mut found);
    check_dashboard_auth(cfg, env, &mut found);
    check_config_version(cfg, env, &mut found);
    found
}

/// The file's `config_version`, against the one this build writes.
///
/// A `Warn`, not a `Note`, for the reason `check_dashboard_auth` gives: `doctor` only prints a
/// `fix:` line from `Warn` up, and the finding *is* the command. Only when a config file exists —
/// a run against built-in defaults has nothing to migrate, and saying so would be noise on every
/// box that never ran `config init`.
fn check_config_version(cfg: &Config, env: EnvFn<'_>, found: &mut Vec<Finding>) {
    let built = crate::config::CONFIG_VERSION;
    if cfg.config_version >= built {
        return;
    }
    // A run against built-in defaults has no file to migrate, and says nothing about it.
    let Some(path) = crate::config::config_path(env) else {
        return;
    };
    if !path.exists() {
        return;
    }
    found.push(
        Finding::new(
            Level::Warn,
            "config",
            format!(
                "the config file was written for shape v{} and this build writes v{}: a setting \
                 added since then is filled by its default and never appears in the file",
                cfg.config_version, built
            ),
        )
        .fix("eclipse config migrate --dry-run  # shows what it would add; then run it without --dry-run"),
    );
}

/// The dashboard's sign-in (`#266`), and whether the install has moved off the shared token.
///
/// It only speaks when a dashboard exists — a token in `web.auth_token` is the proof somebody runs
/// one — because `ok` lines about a feature nobody uses are noise (`check_tasks` draws the line in
/// the same place). Two things it can find:
///
/// - **A password is set and does not parse.** That is a `Problem`, not a `Note`: the dashboard
///   refuses to start on it, and the person's next click is a browser error page, not a shell. The
///   fix names the file and the verb.
/// - **Only the token is set.** A `Warn`, not a `Note`: it still works — the migration case — but
///   nothing else in this install will ever mention that the door is one shared 64-character string
///   with no user attached to it, and `doctor` also only prints a `fix:` line from `Warn` up. A
///   `Note` here would be advice nobody is shown.
fn check_dashboard_auth(cfg: &Config, env: EnvFn<'_>, found: &mut Vec<Finding>) {
    // `map_or` rather than `is_none_or`: that one is 1.82 and this workspace still promises 1.75.
    if cfg
        .web
        .auth_token
        .as_deref()
        .is_none_or(|t| t.trim().is_empty())
    {
        return; // no dashboard: nothing to say
    }
    let lookup = |name: &str| env(name).or_else(|| cfg.dotenv.values.get(name).cloned());
    match crate::auth::Credentials::resolve(lookup) {
        Ok(crate::auth::Credentials::Password { user, .. }) => found.push(Finding::ok(
            "web",
            format!("the dashboard signs in as {user} with a password (the token is the API's)"),
        )),
        Ok(crate::auth::Credentials::Token) => found.push(
            Finding::new(
                Level::Warn,
                "web",
                "the dashboard still signs in with `web.auth_token`: one shared string, pasted into \
                 a box, with no user to say who signed in",
            )
            .fix("eclipse web passwd — sets a username and a password hash in .env; the token \
                  keeps working for `/v1`"),
        ),
        // A hash this build cannot read stops the dashboard from starting at all, so it outranks
        // "you could migrate": `Problem`, with what exactly the parser said.
        Err(why) => found.push(
            Finding::new(
                Level::Problem,
                "web",
                format!("the dashboard's password is set but unusable — {why}"),
            )
            .fix("eclipse web passwd — rewrites the line it cannot read"),
        ),
    }
}

/// The background tasks: an entry whose process is gone is a finding, because it is the one state
/// nothing else can correct — the process that would have written `done` never got there.
///
/// The pid is read through, not believed: [`crate::tasks::Task::state_now`] turns a stored
/// `running` beside a dead pid into `died`, which is the same answer `/tasks` prints. Nothing is
/// said when no task was ever started: an `ok` line about a feature nobody used is noise.
fn check_tasks(cfg: &Config, env: EnvFn<'_>, found: &mut Vec<Finding>) {
    let Ok(state) = cfg.state_dir(env) else {
        return;
    };
    let registry = crate::tasks::Registry::new(state);
    let tasks = registry.list();
    if tasks.is_empty() {
        return;
    }
    let mut reported = 0;
    for task in tasks.iter().filter(|t| t.died()) {
        reported += 1;
        found.push(
            Finding::new(
                Level::Warn,
                "tasks",
                format!(
                    "background task {} died and its entry was never closed: it was last seen {}                      ({})",
                    task.session,
                    crate::session::ago_words(task.updated_ms),
                    task.last
                ),
            )
            .fix(format!(
                "rm {} — the transcript stays in `eclipse sessions`",
                registry.path(&task.session).display()
            ))
            .repair(Repair::ForgetTask(registry.path(&task.session))),
        );
    }
    // A run parked on an approval is a person's decision, not a defect: named, never repaired.
    for task in tasks
        .iter()
        .filter(|t| t.state == crate::tasks::State::Waiting)
    {
        reported += 1;
        found.push(Finding::new(
            Level::Note,
            "tasks",
            format!(
                "background task {} is waiting for an approval: {}",
                task.session, task.detail
            ),
        ));
    }
    if reported == 0 {
        let running = tasks.iter().filter(|t| !t.settled()).count();
        let done = tasks.len() - running;
        found.push(Finding::ok(
            "tasks",
            format!(
                "{running} background task(s) running, {done} finished, none with a missing process"
            ),
        ));
    }
}

/// The directories an install is supposed to have. A missing `skills/` is harmless; a missing
/// state directory is a run that will fail on its first write, which is why it is a problem.
fn check_layout(cfg: &Config, env: EnvFn<'_>, found: &mut Vec<Finding>) {
    let mut made_note = Vec::new();
    if let Some(dir) = cfg.global_context_dir(env) {
        for name in ["memory", "skills", "plugins", "scripts"] {
            let path = dir.join(name);
            if path.is_dir() {
                continue;
            }
            // `skills/`, `plugins/` and `scripts/` are created on demand by the thing that
            // writes them; only `memory/` is expected from an install, and even that is created
            // on first write. So these are notes, not problems.
            made_note.push(name);
            found.push(
                Finding::new(
                    Level::Note,
                    "layout",
                    format!(
                        "{} does not exist yet (it is created on first use)",
                        path.display()
                    ),
                )
                .fix("nothing to do: `eclipse config init` creates the layout")
                .repair(Repair::MakeDir(path.clone())),
            );
        }
    }
    if let Ok(dir) = cfg.sessions_dir(env) {
        if !dir.is_dir() {
            found.push(
                Finding::new(
                    Level::Warn,
                    "layout",
                    format!(
                        "{} does not exist: the first run will create it",
                        dir.display()
                    ),
                )
                .fix("`eclipse sessions list` creates it, or `eclipse doctor --fix`")
                .repair(Repair::MakeDir(dir.clone())),
            );
        }
    }
    if made_note.is_empty() {
        found.push(Finding::ok(
            "layout",
            "the config, state and session directories exist",
        ));
    }
}

/// A file that holds a secret, or a session database, belongs to one user and to nobody else.
#[cfg(unix)]
fn check_permissions(cfg: &Config, env: EnvFn<'_>, found: &mut Vec<Finding>) {
    use std::os::unix::fs::PermissionsExt;
    let mut checked = 0;
    let mut bad = 0;
    let mut wanted: Vec<PathBuf> = Vec::new();
    if let Some(dir) = cfg.global_context_dir(env) {
        wanted.push(dir.join(".env"));
        if let Some(profile) = cfg.global_context_dir(env) {
            if cfg.profile_name() != "default" {
                wanted.push(
                    profile
                        .join("profiles")
                        .join(cfg.profile_name())
                        .join(".env"),
                );
            }
        }
    }
    if let Ok(dir) = cfg.sessions_dir(env) {
        wanted.push(dir.join("sessions.db"));
    }
    for path in wanted {
        let Ok(meta) = std::fs::metadata(&path) else {
            continue;
        };
        checked += 1;
        let mode = meta.permissions().mode() & 0o777;
        if mode & 0o077 == 0 {
            continue;
        }
        bad += 1;
        found.push(
            Finding::new(
                Level::Warn,
                "permissions",
                format!(
                    "{} is {mode:o}; only its owner should be able to read it",
                    path.display()
                ),
            )
            .fix(format!("chmod 600 {}", path.display()))
            .repair(Repair::Chmod(path.clone(), 0o600)),
        );
    }
    // One line per area: an `ok` under a warning about the same files reads as a contradiction.
    if checked > 0 && bad == 0 {
        found.push(Finding::ok("permissions", "private files are owner-only"));
    }
}

#[cfg(not(unix))]
fn check_permissions(_: &Config, _: EnvFn<'_>, _: &mut Vec<Finding>) {}

/// The archive: it opens, it has full-text search, and no lock outlived the process that took it.
fn check_sessions(cfg: &Config, env: EnvFn<'_>, found: &mut Vec<Finding>) {
    let Ok(dir) = cfg.sessions_dir(env) else {
        found.push(
            Finding::new(
                Level::Problem,
                "sessions",
                "no session directory can be resolved (HOME is not set)",
            )
            .fix("set HOME"),
        );
        return;
    };
    let store = crate::session::SessionStore::new(dir.clone());
    // The ids this store actually holds, so a leftover lock from a session that is gone can be
    // told apart from one whose session is still here and merely not running.
    let mut known: std::collections::HashSet<String> = std::collections::HashSet::new();
    match store.list_with_archived() {
        Ok(list) => {
            // Every row, archived ones included: "0 session(s)" on a store of filed-away work
            // would read as a lost database (`#240`).
            for session in &list {
                known.insert(session.id.clone());
            }
            let archived = list.iter().filter(|s| s.archived).count();
            let mut detail = match archived {
                0 => format!("{} session(s) in {}", list.len(), dir.display()),
                n => format!(
                    "{} session(s) in {} ({} archived, out of the list — `sessions list --archived`)",
                    list.len(),
                    dir.display(),
                    n
                ),
            };
            if !store.has_fts() {
                detail.push_str("; full-text search is unavailable in this build (LIKE is used instead)");
            }
            found.push(Finding::ok("sessions", detail));
        }
        Err(e) => found.push(
            Finding::new(Level::Problem, "sessions", format!("the session database will not open: {e}"))
                .fix("check the disk, then the permissions on sessions.db; the transcripts are still on disk"),
        ),
    }

    // A lock file left behind by a process that no longer exists blocks the session until the
    // kernel releases it — which it did, when the process died. The file is then just a file, and
    // that is the *normal* state of a session that is not running right now: one finding per
    // finished session turns the report into a list of the box's history (`#497` — 348 of them on
    // one install, against a report that shows 30 and hides the count).
    let stale = crate::session::stale_locks(&dir);
    if !stale.is_empty() {
        let orphans: Vec<&crate::session::StaleLock> = stale
            .iter()
            .filter(|lock| !known.contains(&lock.id))
            .collect();
        let mut detail = format!(
            "{} lock file(s) with no holder in {} (checked with flock)",
            stale.len(),
            dir.display()
        );
        // Not "held by pid X, which is not running": nothing checked whether X lives. The
        // decision is the `flock` probe in `session::stale_locks`, which the kernel answers for
        // the whole machine -- so this finding is right even when `doctor` runs inside the `shell`
        // sandbox, whose PID namespace hides every host process. A model read the old sentence as
        // a pid check it could watch failing, concluded the warnings were false positives, and
        // wrote that into MEMORY.md (#327).
        let level = if orphans.is_empty() {
            detail.push_str(" — normal for sessions that are not running");
            Level::Note
        } else {
            let names: Vec<&str> = orphans.iter().take(3).map(|l| l.id.as_str()).collect();
            let more = orphans.len().saturating_sub(names.len());
            detail.push_str(&format!(
                ", {} of them naming a session this store does not have: {}{}",
                orphans.len(),
                names.join(", "),
                if more > 0 {
                    format!(" and {more} more")
                } else {
                    String::new()
                }
            ));
            Level::Warn
        };
        found.push(
            Finding::new(level, "sessions", detail)
                .fix("`eclipse doctor --fix` removes them; the sessions themselves are unaffected")
                .repair(Repair::ClearLocks(
                    stale.iter().map(|lock| lock.path.clone()).collect(),
                )),
        );
    }

    // A lock something is holding is a session in use right now — the case a lock file exists
    // for. Worth one line, because it is what an "a run is in progress" refusal is talking about.
    let held = crate::session::held_locks(&dir);
    if !held.is_empty() {
        let names: Vec<String> = held
            .iter()
            .take(3)
            .map(|lock| format!("{} ({})", lock.id, lock.holder))
            .collect();
        let more = held.len().saturating_sub(names.len());
        found.push(Finding::new(
            Level::Warn,
            "sessions",
            format!(
                "{} session(s) in use right now: {}{} — the lock is released when that run ends",
                held.len(),
                names.join(", "),
                if more > 0 {
                    format!(" and {more} more")
                } else {
                    String::new()
                }
            ),
        ));
    }
}

/// Plugins: what loaded, what did not, and what the config names but the disk does not have.
fn check_plugins(cfg: &Config, env: EnvFn<'_>, found: &mut Vec<Finding>) {
    let dirs = cfg.plugins_dirs(env);
    let loaded = crate::plugins::load(&dirs, &cfg.plugins.enabled);
    for problem in &loaded.problems {
        found.push(
            Finding::new(Level::Warn, "plugins", problem.clone())
                .fix("fix the manifest, or remove the plugin from [plugins] enabled"),
        );
    }
    for name in &cfg.plugins.enabled {
        if !dirs.iter().any(|d| d.join(name).is_dir()) {
            found.push(
                Finding::new(
                    Level::Problem,
                    "plugins",
                    format!("`{name}` is enabled but its directory is not there"),
                )
                .fix("remove it from [plugins] enabled, or restore the directory")
                .repair(Repair::DisablePlugin(name.clone())),
            );
        }
    }
    // The tool count is what a listing would show, so the doctor and `eclipse tools list` agree
    // about whether a plugin contributes anything.
    let workspace = cfg.workspace_root(env);
    let (tools, _skipped) = loaded.tools(&workspace, 1024, &[]);
    let tools = tools.len();
    if loaded.problems.is_empty() && !cfg.plugins.enabled.is_empty() {
        found.push(Finding::ok(
            "plugins",
            format!("{} enabled, {tools} tool(s)", cfg.plugins.enabled.len()),
        ));
    }
}

/// Skills: a broken one is named with its reason and left alone — there is no `disabled` list for
/// skills, and inventing one here would be a config key with a single reader.
fn check_skills(cfg: &Config, env: EnvFn<'_>, found: &mut Vec<Finding>) {
    let plugins = crate::plugins::load(&cfg.plugins_dirs(env), &cfg.plugins.enabled);
    let workspace = cfg.workspace_root(env);
    let roots = crate::skills::roots_for(cfg, env, &plugins, &workspace);
    let report = crate::skills::discover(&roots);
    for problem in &report.problems {
        found.push(
            Finding::new(Level::Warn, "skills", problem.clone())
                .fix("check the directory's permissions"),
        );
    }
    for broken in report.broken() {
        let why = broken
            .state
            .as_ref()
            .err()
            .cloned()
            .unwrap_or_else(|| "it did not load".into());
        found.push(
            Finding::new(
                Level::Warn,
                "skills",
                format!("`{}` cannot be used: {why}", broken.name),
            )
            .fix(format!(
                "fix {}; the agent is running without it",
                broken.path.display()
            )),
        );
    }
    let active = report.active().count();
    if report.problems.is_empty() && report.broken().next().is_none() {
        found.push(Finding::ok("skills", format!("{active} load(s)")));
    }
    // `#350`: an index that does not fit used to be a stderr line on the CLI and nothing at all on
    // the dashboard. The model now reads the omission in its own prompt; this is the operator's
    // copy of the same fact, and the only one that names the knob.
    let (index, _) = crate::skills::index(&report, cfg.skills.index_budget_chars);
    let kept = index.as_ref().map(|i| i.names.len()).unwrap_or(0);
    if kept < active {
        found.push(
            Finding::new(
                Level::Warn,
                "skills",
                format!(
                    "the index fits {kept} of {active} skill(s); the rest are reachable only by \
                     name (`skill_search`, then `skill_view`)"
                ),
            )
            .fix(format!(
                "raise `[skills] index_budget_chars` ({} now) if the dropped ones matter, or leave \
                 it: the model is told they exist",
                cfg.skills.index_budget_chars
            )),
        );
    }
}

/// `[tools]`: what the tool schemas cost, and where they come from (`#351`).
///
/// Every tool described in a request is paid for on every turn, whether or not the model calls it.
/// Fourteen built-ins are a fair price; forty from an MCP server are not, and nothing used to say
/// so — the deferral existed, defaulted to nothing, and was invisible. This is the number, split by
/// the loader that contributed it, plus the knob that moves a source behind `tool_search`.
fn check_tool_schemas(cfg: &Config, env: EnvFn<'_>, found: &mut Vec<Finding>) {
    let loaded = crate::plugins::load(&cfg.plugins_dirs(env), &cfg.plugins.enabled)
        .with_mcp(crate::plugins::McpSettings::from_config(cfg))
        .with_config_mcp(cfg);
    let workspace = cfg.workspace_root(env);
    let mut problems = Vec::new();
    let registry = crate::runtime::registry_for(cfg, &loaded, &workspace, &env, &mut problems);
    let described = registry.descriptors();
    let offered: Vec<&crate::tools::ToolDescriptor> =
        described.iter().filter(|d| d.advertised).collect();
    if offered.is_empty() {
        found.push(Finding::ok("tools", "no tool is offered"));
        return;
    }
    // What one schema costs: the name, the description and the arguments document, which is what
    // goes into the `tools` array. Close enough to the token cost to compare one source to another.
    let cost = |d: &crate::tools::ToolDescriptor| {
        d.name.chars().count()
            + d.description.chars().count()
            + d.parameters.to_string().chars().count()
    };
    let total: usize = offered.iter().map(|d| cost(d)).sum();
    // Split by loader, biggest first: the reader wants to know which one to defer, not a table.
    let mut by_source: std::collections::BTreeMap<String, (usize, usize)> =
        std::collections::BTreeMap::new();
    for d in &offered {
        let entry = by_source.entry(d.source.label()).or_insert((0, 0));
        entry.0 += 1;
        entry.1 += cost(d);
    }
    let mut rows: Vec<(String, usize, usize)> = by_source
        .into_iter()
        .map(|(label, (count, chars))| (label, count, chars))
        .collect();
    rows.sort_by(|a, b| b.2.cmp(&a.2).then(a.0.cmp(&b.0)));
    let split = rows
        .iter()
        .map(|(label, count, chars)| format!("{label} {count} tool(s) {chars} chars"))
        .collect::<Vec<_>>()
        .join(", ");
    let deferred = described.iter().filter(|d| d.deferred).count();
    let line = format!(
        "{total} chars of schema in every request from {} tool(s) ({split}){}",
        offered.len(),
        if deferred == 0 {
            String::new()
        } else {
            format!("; {deferred} more deferred behind `tool_search`")
        }
    );
    // The built-ins are the baseline this build was designed around, so what is measured is what
    // everything *else* adds: past twenty tools, or past four thousand characters contributed by a
    // plugin or an MCP server, the cost is somebody's choice and worth a warning. A stock install
    // is all built-ins and no warning — that is the price of the tools Eclipse is.
    let builtin_chars = rows
        .iter()
        .find(|(label, _, _)| label == "builtin")
        .map(|(_, _, chars)| *chars)
        .unwrap_or(0);
    let heavy = offered.len() > 20 || total.saturating_sub(builtin_chars) > 4_000;
    // Name the source that costs the most, so the example is about *this* box rather than about
    // MCP in general — the reader came here because something specific got expensive.
    let heaviest = rows
        .iter()
        .find(|(label, _, _)| label != "builtin")
        .map(|(label, _, _)| label.clone())
        .unwrap_or_else(|| "plugin:mcp:*".to_string());
    let fix = format!(
        "defer it with `[tools] deferred = [\"{heaviest}\"]` (now: {:?}); a deferred tool stays \
         callable through `tool_search` then `tool_call`",
        cfg.tools.deferred
    );
    // Under the ceilings the number is still worth printing — it is the answer to "what do my
    // tools cost?" — but it is a confirmation, not a finding to fix. A `Note` counts as a problem
    // in the tally, and a healthy install has none.
    found.push(if heavy {
        Finding::new(Level::Warn, "tools", line).fix(fix)
    } else {
        Finding::ok("tools", line)
    });
}

/// `[vision]`: whether the configured mode and routes can handle a picture (`#346`, `#491`).
///
/// The shipped default (`mode = "auto"`, no `[vision] route`, no route declaring `vision = true`)
/// refuses every attach, so `doctor` checks `auto` too instead of leaving the default silent.
fn check_vision(cfg: &Config, env: EnvFn<'_>, found: &mut Vec<Finding>) {
    use crate::config::VisionMode;
    let mode = cfg.vision.mode;
    // Per-route `vision` in config overrides the manifest, and manifests are read from disk to
    // answer the fallback case. It is a file read per plugin, no process is started.
    let plugins = crate::plugins::load(&cfg.plugins_dirs(env), &cfg.plugins.enabled);
    let profiles = plugins.provider_profiles();
    let routes = cfg.declared_routes();
    let seeing: Vec<String> = routes
        .iter()
        .filter(|r| crate::vision::route_sees(&r.config, &profiles))
        .map(|r| r.name.clone())
        .collect();

    if mode == VisionMode::Auto {
        let route = cfg.vision.route.trim();
        if !route.is_empty() {
            if let Some(named) = routes.iter().find(|r| r.name == route) {
                if !crate::vision::route_sees(&named.config, &profiles) {
                    let profile = named.config.profile.as_deref().unwrap_or("openai");
                    found.push(
                        Finding::new(
                            Level::Warn,
                            "vision",
                            format!(
                                "`vision route = \"{route}\"` (profile `{profile}`) does not \
                                 declare vision, so a picture sent there would be refused"
                            ),
                        )
                        .fix(format!(
                            "add `vision = true` under route `{route}` (or in profile \
                             `{profile}`) if it can see"
                        )),
                    );
                }
            }
            return;
        }
        if seeing.is_empty() {
            let route_list = routes
                .iter()
                .map(|r| r.name.as_str())
                .collect::<Vec<_>>()
                .join(", ");
            found.push(
                Finding::new(
                    Level::Note,
                    "vision",
                    format!(
                        "`[vision] mode = \"auto\"` with no route that declares vision: every \
                         attach is refused — add `vision = true` under a route that can see (and \
                         set `[vision] route` if it is not the default). Routes: {route_list}"
                    ),
                )
                .fix(
                    "add `vision = true` under a route that can see, and set `[vision] route` \
                     if it is not the default",
                ),
            );
        } else if !routes
            .first()
            .is_some_and(|r| crate::vision::route_sees(&r.config, &profiles))
        {
            found.push(
                Finding::new(
                    Level::Note,
                    "vision",
                    format!(
                        "`[vision] mode = \"auto\"` with no `[vision] route`: the default route \
                         does not declare vision, so attaches will be refused unless `[vision] \
                         route` names a seeing route ({})",
                        seeing.join(", ")
                    ),
                )
                .fix("set `[vision] route` to one of the routes that declares `vision = true`"),
            );
        }
        return;
    }

    if mode == VisionMode::Native && seeing.is_empty() {
        found.push(
            Finding::new(
                Level::Warn,
                "vision",
                format!(
                    "`[vision] mode = \"native\"` with no route that declares vision: every \
                     attach is refused. Routes: {}",
                    routes
                        .iter()
                        .map(|r| r.name.as_str())
                        .collect::<Vec<_>>()
                        .join(", ")
                ),
            )
            .fix(
                "add `vision = true` under a route that can see, or set `vision.mode = \"auto\"` \
                 and name a seeing route in `vision.route`",
            ),
        );
        return;
    }
    if mode == VisionMode::Text {
        let route = cfg.vision.route.trim();
        if route.is_empty() {
            found.push(
                Finding::new(
                    Level::Warn,
                    "vision",
                    "`[vision] mode = \"text\"` with no `vision route`: there is nothing to \
                     describe a picture, so every attach is refused",
                )
                .fix("set `vision route` to a route that declares `vision = true`"),
            );
        } else if let Some(named) = routes.iter().find(|r| r.name == route) {
            if !crate::vision::route_sees(&named.config, &profiles) {
                let profile = named.config.profile.as_deref().unwrap_or("openai");
                found.push(
                    Finding::new(
                        Level::Warn,
                        "vision",
                        format!(
                            "`vision route = \"{route}\"` (profile `{profile}`) does not declare \
                             vision, so a picture sent there would be unreadable"
                        ),
                    )
                    .fix(format!(
                        "add `vision = true` under route `{route}` (or in profile `{profile}`) \
                         if it can see"
                    )),
                );
            }
        }
    }
}

fn check_shell(cfg: &Config, env: EnvFn<'_>, found: &mut Vec<Finding>) {
    use crate::config::ShellIsolate;
    let sandbox = crate::sandbox::Sandbox::new(&cfg.tools, &cfg.workspace_root(env), None);
    match cfg.tools.shell_isolate {
        ShellIsolate::Off => found.push(Finding::ok(
            "shell",
            "shell_isolate = \"off\": commands run uncontained by request",
        )),
        ShellIsolate::Process => {
            if !sandbox.degraded() && !sandbox.refuses() {
                found.push(Finding::ok(
                    "shell",
                    format!("shell_isolate = \"process\" through {}", sandbox.status()),
                ));
            } else {
                found.push(
                    Finding::new(
                        Level::Warn,
                        "shell",
                        "shell_isolate = \"process\" but bubblewrap is not on PATH: commands run uncontained",
                    )
                    .fix("install bubblewrap (apt install bubblewrap), or set [tools] shell_isolate = \"off\" to stop the warning"),
                );
            }
        }
        ShellIsolate::Fs => {
            if !sandbox.degraded() && !sandbox.refuses() {
                found.push(Finding::ok(
                    "shell",
                    format!("shell_isolate = \"fs\" through {}", sandbox.status()),
                ));
            } else {
                found.push(
                    Finding::new(
                        Level::Problem,
                        "shell",
                        "shell_isolate = \"fs\" refuses every command: bubblewrap is not on PATH",
                    )
                    .fix("install bubblewrap (apt install bubblewrap), or set [tools] shell_isolate = \"process\""),
                );
            }
        }
    }

    // `#552`: a hide the run cannot apply is the difference between a file withheld and a file
    // readable inside the sandbox, and nothing used to say which. Only `fs` hides anything, so
    // only `fs` is asked — in the other modes the list is inert by design, not by mistake.
    //
    // A path the build *suggests* and this machine happens not to have is not a finding: `~/.aws`
    // is absent on a great many hosts, and a warning nobody can act on is how a check stops being
    // read.
    if cfg.tools.shell_isolate == ShellIsolate::Fs {
        let unapplied: Vec<String> = sandbox
            .skipped_hides()
            .into_iter()
            .filter(|(path, why)| {
                !(*why == crate::sandbox::HideSkip::Missing && sandbox.is_suggested_hide(path))
            })
            .map(|(path, why)| format!("{} ({})", path.display(), why.why()))
            .collect();
        if !unapplied.is_empty() {
            found.push(
                Finding::new(
                    Level::Warn,
                    "shell",
                    format!("shell_isolate_hide is not hiding {}", unapplied.join(", ")),
                )
                .fix(
                    "correct the path, or drop the entry: a hide that is not applied leaves that \
                     file readable inside the sandbox",
                ),
            );
        }
    }
}

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

    fn env_of(home: &std::path::Path) -> impl Fn(&str) -> Option<String> {
        let home = home.display().to_string();
        move |k: &str| (k == "HOME").then(|| home.clone())
    }

    fn temp() -> (tempfile::TempDir, impl Fn(&str) -> Option<String>) {
        let dir = tempfile::tempdir().unwrap();
        let env = env_of(dir.path());
        (dir, env)
    }

    fn areas<'a>(findings: &'a [Finding], area: &str) -> Vec<&'a Finding> {
        findings.iter().filter(|f| f.area == area).collect()
    }

    /// #346: `native` is a promise that the turn's model can see. A config that makes it and has
    /// no route declaring vision refuses every attach, and `doctor` is where that is found before
    /// somebody attaches a screenshot at 1am.
    #[test]
    fn native_with_no_route_that_declares_vision_is_reported_and_says_what_to_change() {
        let (dir, env) = temp();
        std::fs::create_dir_all(dir.path().join(".eclipse/memory")).unwrap();
        let cfg = Config::from_toml_str(
            "[provider]\nbase_url = \"http://127.0.0.1:1/v1\"\nmodel = \"m\"\n\
             [vision]\nmode = \"native\"\n",
        )
        .unwrap();
        let findings = check(&cfg, &env);
        let found = areas(&findings, "vision")
            .into_iter()
            .find(|f| f.level == Level::Warn)
            .expect("a warn");
        assert!(found.detail.contains("native"), "{}", found.detail);
        let fix = found.fix.as_deref().expect("a fix");
        assert!(fix.contains("auto"), "{fix}");
    }

    #[test]
    fn text_without_a_route_is_reported() {
        let (dir, env) = temp();
        std::fs::create_dir_all(dir.path().join(".eclipse/memory")).unwrap();
        let cfg = Config::from_toml_str(
            "[provider]\nbase_url = \"http://127.0.0.1:1/v1\"\nmodel = \"m\"\n\
             [vision]\nmode = \"text\"\n",
        )
        .unwrap();
        let findings = check(&cfg, &env);
        let found = areas(&findings, "vision")
            .into_iter()
            .find(|f| f.level == Level::Warn)
            .expect("a warn");
        assert!(found.detail.contains("vision route"), "{}", found.detail);
    }

    /// `#491`: the shipped default (`mode = "auto"`, no route, nothing declares vision) refuses
    /// every attach, so `doctor` must report a vision finding instead of staying silent.
    #[test]
    fn auto_reports_when_no_route_declares_vision() {
        let (dir, env) = temp();
        std::fs::create_dir_all(dir.path().join(".eclipse/memory")).unwrap();
        let cfg = Config::from_toml_str(
            "[provider]\nbase_url = \"http://127.0.0.1:1/v1\"\nmodel = \"m\"\n",
        )
        .unwrap();
        let findings = check(&cfg, &env);
        let vision = areas(&findings, "vision");
        assert_eq!(vision.len(), 1, "{findings:?}");
        assert!(
            vision[0].detail.contains("no route that declares vision"),
            "{}",
            vision[0].detail
        );
        assert!(
            vision[0].detail.contains("vision = true"),
            "{}",
            vision[0].detail
        );

        // Once a route declares `vision = true` (or `[vision] route` points to one), `auto` is quiet.
        let seeing_default = Config::from_toml_str(
            "[provider]\nbase_url = \"http://127.0.0.1:1/v1\"\nmodel = \"m\"\nvision = true\n",
        )
        .unwrap();
        assert!(areas(&check(&seeing_default, &env), "vision").is_empty());

        let blind_route = Config::from_toml_str(
            "[provider]\nbase_url = \"http://127.0.0.1:1/v1\"\nmodel = \"m\"\n\
             [[provider.route]]\nname = \"aux\"\nbase_url = \"http://127.0.0.1:2/v1\"\nmodel = \"v\"\nprofile = \"llamacpp\"\n\
             [vision]\nmode = \"auto\"\nroute = \"aux\"\n",
        )
        .unwrap();
        let findings = check(&blind_route, &env);
        let found = areas(&findings, "vision")
            .into_iter()
            .find(|f| f.level == Level::Warn)
            .expect("blind describe route warns in auto mode");
        assert!(found.detail.contains("aux"), "{}", found.detail);
        assert!(found.detail.contains("llamacpp"), "{}", found.detail);
        assert!(
            found.fix.as_deref().unwrap_or("").contains("vision = true"),
            "{:?}",
            found.fix
        );
    }

    /// #327: the sentence used to read "is held by pid X, which is not running", which sounds like a
    /// liveness check. Nothing checks liveness — the decision is `flock`, which the kernel answers
    /// for the whole machine — and a model reading the old wording inside the `shell` sandbox (whose
    /// PID namespace hides every host process) concluded the warnings were false positives and wrote
    /// that into `MEMORY.md`. The wording has to name the check that was actually made.
    #[test]
    fn a_stale_lock_names_the_check_that_was_made_and_not_a_liveness_test() {
        let (dir, env) = temp();
        let sessions = dir.path().join(".eclipse/state/sessions");
        std::fs::create_dir_all(&sessions).unwrap();
        std::fs::create_dir_all(dir.path().join(".eclipse/memory")).unwrap();
        let lock = sessions.join("1796000000000-4242-0.lock");
        std::fs::write(&lock, "4242\n").unwrap();
        // The session is in the store, so this lock is a finished session's leftover and not an
        // orphan: the report says so, at the level that says "nothing is wrong".
        crate::session::SessionStore::new(sessions.clone())
            .append(
                "1796000000000-4242-0",
                &crate::message::Message::user("hello"),
            )
            .unwrap();

        let findings = check(&Config::default(), &env);
        let stale = areas(&findings, "sessions")
            .into_iter()
            .find(|f| f.detail.contains("no holder"))
            .expect("the unheld lock is counted");
        assert_eq!(stale.level, Level::Note, "{}", stale.detail);
        assert!(
            stale.detail.contains("flock"),
            "the sentence names the check it made: {}",
            stale.detail
        );
        assert!(
            !stale.detail.contains("which is not running"),
            "and never implies a liveness test: {}",
            stale.detail
        );
        assert!(
            stale
                .detail
                .contains("normal for sessions that are not running"),
            "it says the state is the ordinary one: {}",
            stale.detail
        );
    }

    /// `#497`: every session ever run leaves a lock file, so a per-file finding made the report a
    /// list of the box's history — 348 warnings on one install, of which 30 were shown. One box
    /// gets one line, whatever the pile is.
    #[test]
    fn a_pile_of_finished_sessions_is_one_finding_about_locks() {
        let (dir, env) = temp();
        let sessions = dir.path().join(".eclipse/state/sessions");
        std::fs::create_dir_all(&sessions).unwrap();
        std::fs::create_dir_all(dir.path().join(".eclipse/memory")).unwrap();
        let store = crate::session::SessionStore::new(sessions.clone());
        for i in 0..40u32 {
            let id = format!("17960000000{i:02}-4400-0");
            store
                .append(&id, &crate::message::Message::user("hi"))
                .unwrap();
            std::fs::write(
                sessions.join(format!("{id}.lock")),
                format!("{}\n", 4400 + i),
            )
            .unwrap();
        }

        let findings = check(&Config::default(), &env);
        let about_locks: Vec<&Finding> = areas(&findings, "sessions")
            .into_iter()
            .filter(|f| f.detail.contains("lock"))
            .collect();
        assert_eq!(
            about_locks.len(),
            1,
            "one line for the whole pile: {about_locks:#?}"
        );
        assert!(
            about_locks[0].detail.contains("40"),
            "{}",
            about_locks[0].detail
        );
        assert_eq!(about_locks[0].level, Level::Note);
        // And the repair is the pile, not one file: `--fix` has to be able to clear what was
        // counted, or the next run reports the same 40.
        match about_locks[0].repair {
            Some(Repair::ClearLocks(ref paths)) => assert_eq!(paths.len(), 40),
            ref other => panic!("expected a ClearLocks repair, got {other:?}"),
        }
    }

    /// A lock that names no session this store has is the case worth a warning: nothing will ever
    /// resume it and nothing removes it.
    #[test]
    fn a_lock_with_no_session_behind_it_warns() {
        let (dir, env) = temp();
        let sessions = dir.path().join(".eclipse/state/sessions");
        std::fs::create_dir_all(&sessions).unwrap();
        std::fs::create_dir_all(dir.path().join(".eclipse/memory")).unwrap();
        std::fs::write(sessions.join("1796000000009-9090-0.lock"), "9090\n").unwrap();

        let findings = check(&Config::default(), &env);
        let orphan = areas(&findings, "sessions")
            .into_iter()
            .find(|f| f.detail.contains("no holder"))
            .expect("the lock is counted");
        assert_eq!(orphan.level, Level::Warn, "{}", orphan.detail);
        assert!(
            orphan.detail.contains("1796000000009-9090-0"),
            "it names the session nothing has: {}",
            orphan.detail
        );
    }

    /// The other half, and the one that proves the check is not pid-based: a lock this very process
    /// holds is a session in use, never a leftover, however invisible the holder is to `ps`.
    #[test]
    fn a_lock_a_run_holds_is_reported_as_in_use_and_never_as_stale() {
        let (dir, env) = temp();
        let sessions = dir.path().join(".eclipse/state/sessions");
        std::fs::create_dir_all(&sessions).unwrap();
        std::fs::create_dir_all(dir.path().join(".eclipse/memory")).unwrap();
        let held = sessions.join("1796000000001-4243-0.lock");
        let file = std::fs::OpenOptions::new()
            .create(true)
            .read(true)
            .write(true)
            .truncate(false)
            .open(&held)
            .unwrap();
        {
            use std::os::unix::io::AsRawFd;
            // SAFETY: `file` owns a valid descriptor for the duration of the call.
            let rc = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX) };
            assert_eq!(
                rc,
                0,
                "taking the lock: {}",
                std::io::Error::last_os_error()
            );
        }
        std::fs::write(&held, "4243\n").unwrap();

        let findings = check(&Config::default(), &env);
        assert!(
            !areas(&findings, "sessions")
                .iter()
                .any(|f| f.detail.contains("no holder")
                    || f.detail.contains("1796000000001-4243-0.lock")),
            "a lock this process holds is not stale: {findings:#?}"
        );
        let in_use = areas(&findings, "sessions")
            .into_iter()
            .find(|f| f.detail.contains("in use right now"))
            .expect("a held lock is a session in use");
        assert_eq!(in_use.level, Level::Warn);
        assert!(
            in_use.detail.contains("1796000000001-4243-0"),
            "{}",
            in_use.detail
        );
        drop(file);
    }

    #[test]
    fn a_healthy_install_has_nothing_to_report() {
        let (dir, env) = temp();
        std::fs::create_dir_all(dir.path().join(".eclipse/memory")).unwrap();
        std::fs::create_dir_all(dir.path().join(".eclipse/state/sessions")).unwrap();
        let cfg = Config::default();
        let findings = check(&cfg, &env);
        let tally = Tally::of(&findings);
        assert_eq!(tally.problems, 0, "{findings:#?}");
        // The one finding that depends on the machine rather than the install: a host without
        // bubblewrap really does run commands uncontained, and the doctor is right to say so. The
        // test holds the install to what a healthy *install* controls.
        let elsewhere: Vec<&Finding> = findings
            .iter()
            .filter(|f| f.area != "shell" && f.level >= Level::Warn)
            .collect();
        assert!(elsewhere.is_empty(), "{elsewhere:#?}");
        if tally.warnings == 0 {
            assert!(tally.summary().contains("nothing to fix"));
        }
    }

    /// `#552`: a hide the mode cannot apply is the difference between a file withheld and a file
    /// readable inside the sandbox. The shell line mentions it in passing; the check names it,
    /// because that is the question `config check` was opened to answer.
    #[test]
    fn a_hide_that_cannot_be_applied_is_named_with_its_reason() {
        let (dir, env) = temp();
        std::fs::create_dir_all(dir.path().join(".eclipse/memory")).unwrap();
        std::fs::create_dir_all(dir.path().join(".eclipse/state/sessions")).unwrap();
        let mut cfg = Config::default();
        cfg.tools.shell_isolate = crate::config::ShellIsolate::Fs;
        cfg.tools.shell_isolate_hide = vec![dir.path().join(".netrcc")];
        let findings = check(&cfg, &env);
        let warned = areas(&findings, "shell")
            .into_iter()
            .find(|f| f.detail.contains("shell_isolate_hide"))
            .unwrap_or_else(|| panic!("{findings:#?}"));
        assert_eq!(warned.level, Level::Warn);
        assert!(warned.detail.contains(".netrcc"), "{:?}", warned.detail);
        assert!(
            warned.detail.contains("no such path"),
            "{:?}",
            warned.detail
        );
    }

    /// The suggestion the build makes and a machine without `~/.aws` is not a finding: a warning
    /// nobody can act on is how a check stops being read.
    #[test]
    fn a_suggested_hide_that_this_machine_does_not_have_is_not_a_finding() {
        let (dir, env) = temp();
        std::fs::create_dir_all(dir.path().join(".eclipse/memory")).unwrap();
        std::fs::create_dir_all(dir.path().join(".eclipse/state/sessions")).unwrap();
        let mut cfg = Config::default();
        cfg.tools.shell_isolate = crate::config::ShellIsolate::Fs;
        // Every default, none of them created in the fake home.
        cfg.tools.shell_isolate_hide = crate::config::default_hidden_paths();
        let findings = check(&cfg, &env);
        assert!(
            !areas(&findings, "shell")
                .iter()
                .any(|f| f.detail.contains("shell_isolate_hide")),
            "{findings:#?}"
        );
    }

    /// `#266`: the three states of the dashboard's sign-in, and the one that must not be silent.
    /// A doctor that said nothing about a token install would leave every existing dashboard on
    /// the shared string forever, with nothing to notice.
    #[test]
    fn the_dashboard_sign_in_is_reported_and_a_broken_hash_is_a_problem() {
        let (dir, env) = temp();
        std::fs::create_dir_all(dir.path().join(".eclipse/memory")).unwrap();
        std::fs::create_dir_all(dir.path().join(".eclipse/state/sessions")).unwrap();

        // No dashboard at all: no `web` line, not even an `ok` one.
        let quiet = check(&Config::default(), &env);
        assert!(areas(&quiet, "web").is_empty(), "{quiet:#?}");

        // A dashboard on the token: a note that names the verb which ends it.
        let mut cfg = Config::default();
        cfg.web.auth_token = Some("t".repeat(64));
        let token_only = check(&cfg, &env);
        let web = areas(&token_only, "web");
        assert_eq!(web.len(), 1, "{token_only:#?}");
        // `Warn`, because that is the first level at which `doctor` prints a `fix:` line: advice
        // nobody is shown is not advice.
        assert_eq!(web[0].level, Level::Warn);
        assert!(web[0].detail.contains("web.auth_token"), "{:?}", web[0]);
        assert!(
            web[0]
                .fix
                .as_deref()
                .unwrap_or_default()
                .contains("eclipse web passwd"),
            "{:?}",
            web[0]
        );

        // A password set: an `ok` line, and it names the user.
        let hash = crate::auth::hash_password("open sesame").unwrap();
        std::fs::write(
            dir.path().join(".env"),
            format!("ECLIPSE_WEB_USER=max\nECLIPSE_WEB_PASSWORD_HASH={hash}\n"),
        )
        .unwrap();
        let mut cfg = cfg.clone();
        cfg.dotenv
            .values
            .insert("ECLIPSE_WEB_USER".into(), "max".into());
        cfg.dotenv
            .values
            .insert("ECLIPSE_WEB_PASSWORD_HASH".into(), hash);
        let signed_in = check(&cfg, &env);
        let web = areas(&signed_in, "web");
        assert_eq!(web.len(), 1, "{signed_in:#?}");
        assert_eq!(web[0].level, Level::Ok);
        assert!(web[0].detail.contains("max"), "{:?}", web[0]);

        // A hash this build cannot read stops the dashboard starting, so it is a problem, and the
        // parser's own words are the detail.
        cfg.dotenv.values.insert(
            "ECLIPSE_WEB_PASSWORD_HASH".into(),
            "argon2id$600000$aabb$ccdd".into(),
        );
        let broken = check(&cfg, &env);
        let web = areas(&broken, "web");
        assert_eq!(web.len(), 1, "{broken:#?}");
        assert_eq!(web[0].level, Level::Problem);
        assert!(web[0].detail.contains("unknown scheme"), "{:?}", web[0]);
    }

    #[test]
    fn a_missing_session_directory_is_offered_as_a_repair() {
        let (dir, env) = temp();
        std::fs::create_dir_all(dir.path().join(".eclipse")).unwrap();
        let findings = check(&Config::default(), &env);
        let layout: Vec<&Finding> = areas(&findings, "layout");
        let sessions = layout.iter().find_map(|f| match &f.repair {
            Some(Repair::MakeDir(p)) if p.ends_with("sessions") => Some(p.clone()),
            _ => None,
        });
        let path =
            sessions.unwrap_or_else(|| panic!("no MakeDir for sessions offered: {layout:#?}"));
        std::fs::create_dir_all(&path).unwrap();
        assert!(path.is_dir());
        // And the second run is quiet about it.
        let again = check(&Config::default(), &env);
        assert!(!areas(&again, "layout")
            .iter()
            .any(|f| f.level >= Level::Warn && f.detail.contains("does not exist")));
    }

    #[cfg(unix)]
    #[test]
    fn a_world_readable_dotenv_is_a_warning_with_a_chmod_repair() {
        use std::os::unix::fs::PermissionsExt;
        let (dir, env) = temp();
        let cfg_dir = dir.path().join(".eclipse");
        std::fs::create_dir_all(&cfg_dir).unwrap();
        let dotenv = cfg_dir.join(".env");
        std::fs::write(&dotenv, "ECLIPSE_WEB_AUTH_TOKEN=secret\n").unwrap();
        std::fs::set_permissions(&dotenv, std::fs::Permissions::from_mode(0o644)).unwrap();

        let findings = check(&Config::default(), &env);
        let perms: Vec<&Finding> = areas(&findings, "permissions");
        let bad = perms
            .iter()
            .find(|f| f.level == Level::Warn)
            .unwrap_or_else(|| panic!("no warning: {perms:#?}"));
        assert!(bad.detail.contains(".env"), "{:?}", bad.detail);
        assert!(matches!(bad.repair, Some(Repair::Chmod(_, 0o600))));
        assert!(bad
            .fix
            .as_deref()
            .unwrap_or_default()
            .starts_with("chmod 600"));
    }

    #[test]
    fn a_plugin_named_but_missing_is_a_problem_with_a_repair() {
        let (dir, env) = temp();
        std::fs::create_dir_all(dir.path().join(".eclipse/plugins")).unwrap();
        let mut cfg = Config::default();
        cfg.plugins.enabled = vec!["gone".into()];
        let findings = check(&cfg, &env);
        let plugins: Vec<&Finding> = areas(&findings, "plugins");
        let problem = plugins
            .iter()
            .find(|f| f.level == Level::Problem)
            .unwrap_or_else(|| panic!("no problem: {plugins:#?}"));
        assert!(problem.detail.contains("gone"), "{:?}", problem.detail);
        assert_eq!(problem.repair, Some(Repair::DisablePlugin("gone".into())));
    }

    #[test]
    fn a_broken_skill_is_named_and_not_touched() {
        let (dir, env) = temp();
        let skills = dir.path().join(".eclipse/skills/broken");
        std::fs::create_dir_all(&skills).unwrap();
        std::fs::write(
            skills.join("SKILL.md"),
            "---\ndescription: no name\n---\nbody\n",
        )
        .unwrap();
        let findings = check(&Config::default(), &env);
        let named: Vec<&Finding> = areas(&findings, "skills")
            .into_iter()
            .filter(|f| f.level == Level::Warn)
            .collect();
        assert!(!named.is_empty(), "{findings:#?}");
        assert!(
            named.iter().all(|f| f.repair.is_none()),
            "a skill has no disabled list to repair into: {named:#?}"
        );
    }

    /// `#350`: an index that cannot fit every skill is a finding, not a stderr line only a
    /// terminal user ever sees. It names the count and the knob, and it is repairable by
    /// definition — the fix is the setting.
    #[test]
    fn an_index_that_cannot_fit_every_skill_names_the_count_and_the_knob() {
        let (dir, env) = temp();
        for name in ["alpha", "beta", "gamma"] {
            let dir = dir.path().join(format!(".eclipse/skills/{name}"));
            std::fs::create_dir_all(&dir).unwrap();
            std::fs::write(
                dir.join("SKILL.md"),
                format!(
                    "---\nname: {name}\ndescription: {}\n---\nbody\n",
                    "x".repeat(120)
                ),
            )
            .unwrap();
        }
        let mut cfg = Config::default();
        cfg.skills.index_budget_chars = 120;
        let findings = check(&cfg, &env);
        let warn = areas(&findings, "skills")
            .into_iter()
            .find(|f| f.level == Level::Warn && f.detail.contains("index fits"))
            .unwrap_or_else(|| panic!("{findings:#?}"));
        assert!(warn.detail.contains("of 3 skill(s)"), "{}", warn.detail);
        assert!(
            warn.fix
                .as_deref()
                .unwrap_or("")
                .contains("index_budget_chars"),
            "{warn:#?}"
        );

        // With room for all three, no finding: the check is about a truncation, not about skills.
        let mut roomy = Config::default();
        roomy.skills.index_budget_chars = 0;
        let findings = check(&roomy, &env);
        assert!(
            !areas(&findings, "skills")
                .into_iter()
                .any(|f| f.detail.contains("index fits")),
            "{findings:#?}"
        );
    }

    /// #225: the registry says `running` and the process is gone. That is the one state `/tasks`
    /// cannot correct by itself, so `doctor` names it — and offers to forget the entry, not the
    /// transcript.
    #[test]
    fn a_background_task_whose_process_died_is_a_warning_a_person_can_clear() {
        let (dir, env) = temp();
        std::fs::create_dir_all(dir.path().join(".eclipse")).unwrap();
        let registry = crate::tasks::Registry::new(dir.path().join(".eclipse/state"));
        let mut child = std::process::Command::new("true").spawn().expect("spawn");
        let pid = child.id();
        child.wait().expect("reap");
        let mut gone = crate::tasks::Task::spawned("1700000000000-4242-0", pid, "summarise");
        gone.state = crate::tasks::State::Running;
        registry.write(&gone).unwrap();

        let findings = check(&Config::default(), &env);
        let tasks: Vec<&Finding> = areas(&findings, "tasks");
        let warned = tasks
            .iter()
            .find(|f| f.level == Level::Warn)
            .unwrap_or_else(|| panic!("no warning about the dead task: {tasks:#?}"));
        assert!(
            warned.detail.contains("1700000000000-4242-0") && warned.detail.contains("died"),
            "{:?}",
            warned.detail
        );
        assert_eq!(
            warned.repair,
            Some(Repair::ForgetTask(registry.path("1700000000000-4242-0")))
        );
        assert!(
            warned
                .fix
                .as_deref()
                .unwrap_or_default()
                .contains("eclipse sessions"),
            "the transcript stays: {:?}",
            warned.fix
        );
    }

    #[test]
    fn a_task_still_running_is_reported_as_healthy_and_no_task_at_all_is_silent() {
        let (dir, env) = temp();
        std::fs::create_dir_all(dir.path().join(".eclipse")).unwrap();
        let quiet = check(&Config::default(), &env);
        assert!(
            areas(&quiet, "tasks").is_empty(),
            "nothing was ever started, so there is nothing to say"
        );

        let registry = crate::tasks::Registry::new(dir.path().join(".eclipse/state"));
        let mut live = crate::tasks::Task::begun("1700000000001-4243-0", "count the files");
        live.pid = std::process::id();
        live.pid_since = None;
        registry.write(&live).unwrap();
        let findings = check(&Config::default(), &env);
        let tasks = areas(&findings, "tasks");
        assert_eq!(tasks.len(), 1, "{tasks:#?}");
        assert_eq!(tasks[0].level, Level::Ok, "{tasks:#?}");
        assert!(tasks[0].detail.contains("1 background task(s) running"));
    }

    #[test]
    fn the_summary_counts_what_a_person_has_to_decide() {
        let findings = vec![
            Finding::ok("a", "fine"),
            Finding::new(Level::Warn, "b", "meh"),
            Finding::new(Level::Problem, "c", "broken").repair(Repair::MakeDir("/tmp/x".into())),
        ];
        let tally = Tally::of(&findings);
        assert_eq!(
            (tally.problems, tally.warnings, tally.repairable),
            (1, 1, 1)
        );
        assert_eq!(tally.summary(), "1 problem(s), 1 warning(s)");
    }
}