mushroomdb-cli 0.6.6

CLI binary for mushroomdb: start, shell, and server commands
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
//! `mushroomdb doctor` — verify an install end to end: the config entry, the
//! store, the hooks, and a real stdio handshake with the configured MCP
//! command.
//!
//! # Design
//!
//! Every check reads what is actually on disk — the same files `install`
//! wrote — rather than recomputing what an install *should* look like, so
//! doctor catches drift (a hand-edited config, a stale command) that a
//! `run_install_with` re-derivation would paper over. Checks run in a fixed
//! order and each prints exactly one line: `ok|warn|fail  <name>  <message>`,
//! with a trailing `fix: …` when there is something to run. The same store
//! state always produces the same output.
//!
//! `fail` on any check is the only thing that sets the process exit code;
//! `warn` is informational.

use crate::install::{
    claude_mcp_file, cursor_mcp_file, default_db, entry_db, expand_platform, git_hooks_dir,
    has_our_server, installed_shape, is_disabled, is_our_hook_command, line_runs_for_store,
    opt_ins, resolve_platform, resolve_scope, Externals, Platform, Scope, StoreRef, AUTO_ARG,
    BRIEF_EVENT, ENRICH_EVENT, GIT_HOOKS, HOOK_BEGIN, HOOK_EVENT, IMPACT_EVENT, INTERCEPT_EVENT,
    SERVER_NAME, TOUCH_EVENT,
};
use crate::CliError;
use core_api::{GraphDb, GraphError, OpenOptions};
use serde_json::Value as Js;
use std::io::{BufRead, BufReader, Read as _, Write as _};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};

/// Options parsed from `mushroomdb doctor [flags]`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DoctorOpts {
    /// Which platform's config to check. `None` = auto-detect, same as `install`.
    pub platform: Option<Platform>,
    /// Project or user scope. `None` = auto: project inside a git checkout.
    pub scope: Option<Scope>,
}

/// Outcome of `mushroomdb doctor`: the rendered report and whether to exit 1.
pub struct DoctorReport {
    /// One line per check, already newline-terminated.
    pub output: String,
    /// True when any check is `fail`. The caller exits 1 on this and only this.
    pub had_fail: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Status {
    Ok,
    /// The check does not apply to this install — not a finding either way.
    Skip,
    Warn,
    Fail,
}

impl Status {
    fn word(self) -> &'static str {
        match self {
            Status::Ok => "ok",
            Status::Skip => "skip",
            Status::Warn => "warn",
            Status::Fail => "fail",
        }
    }
}

/// One printed line: a status, the check's name, a message, and an optional
/// one-line fix.
struct Check {
    status: Status,
    name: &'static str,
    message: String,
    fix: Option<String>,
}

impl Check {
    fn ok(name: &'static str, message: impl Into<String>) -> Self {
        Check {
            status: Status::Ok,
            name,
            message: message.into(),
            fix: None,
        }
    }
    fn skip(name: &'static str, message: impl Into<String>) -> Self {
        Check {
            status: Status::Skip,
            name,
            message: message.into(),
            fix: None,
        }
    }
    fn warn(name: &'static str, message: impl Into<String>, fix: Option<String>) -> Self {
        Check {
            status: Status::Warn,
            name,
            message: message.into(),
            fix,
        }
    }
    fn fail(name: &'static str, message: impl Into<String>, fix: Option<String>) -> Self {
        Check {
            status: Status::Fail,
            name,
            message: message.into(),
            fix,
        }
    }
    fn render(&self) -> String {
        // 11 is the longest check name (`impact-hook`, `always-load`), so the
        // message column lines up for every row rather than for most of them.
        let mut line = format!(
            "{:<4} {:<11} {}",
            self.status.word(),
            self.name,
            self.message
        );
        if let Some(fix) = &self.fix {
            line.push_str(&format!("  fix: {fix}"));
        }
        line.push('\n');
        line
    }
}

/// Run `doctor` against the real environment: `HOME` and the process PATH.
pub fn run_doctor(
    project_root: &Path,
    home: &Path,
    opts: &DoctorOpts,
) -> Result<DoctorReport, CliError> {
    run_doctor_with(project_root, home, opts, &Externals::from_env())
}

/// Like [`run_doctor`], with the external environment (PATH) supplied by the
/// caller. Tests use this to stay deterministic and to point `npx` lookups at
/// a directory of stand-ins.
pub fn run_doctor_with(
    project_root: &Path,
    home: &Path,
    opts: &DoctorOpts,
    ext: &Externals,
) -> Result<DoctorReport, CliError> {
    let (scope, _auto_scope) = resolve_scope(project_root, opts.scope);
    let resolved = resolve_platform(project_root, home, opts.platform.as_ref())?;
    let platforms = expand_platform(&resolved);

    // A disabled install has no config to check — every check below it would
    // report exactly what `disable` intentionally removed, which is not a
    // failure. Report the state and stop; `warn` never sets the exit code.
    if is_disabled(project_root, home, scope, &platforms) {
        return Ok(DoctorReport {
            output: Check::warn("state", "disabled — enable with: mushroomdb enable", None)
                .render(),
            had_fail: false,
        });
    }

    // A `cli` install registers no MCP server on purpose, so the two checks
    // that read one have nothing to read and no fault to report; the store it
    // is wired to comes from the hooks it did write. Everything else — the
    // store, the hooks, the git hooks — is as breakable here as anywhere and
    // still runs.
    let (delivery, recorded_store) = installed_shape(project_root, home, scope, &platforms);
    let mcp_delivery = delivery.wires_mcp();

    let mut checks: Vec<Check> = Vec::new();
    let mut primary: Option<(Platform, ConfigEntry)> = None;

    // 1. config — one line per requested platform; the first entry that reads
    //    cleanly becomes the target of every check below it.
    for plat in &platforms {
        // A `cli` delivery closes Claude Code's door and no other's: Cursor
        // and Codex are registered as servers whatever it asked for, so their
        // entries are still there to check (see [`install::Delivery`]).
        if !mcp_delivery && matches!(plat, Platform::ClaudeCode) {
            checks.push(Check::skip(
                "config",
                format!(
                    "delivery: {} — the skill teaches the binary, no MCP entry to check",
                    delivery.label()
                ),
            ));
            continue;
        }
        match mcp_file_for(plat, project_root, home, scope) {
            None => checks.push(Check::warn(
                "config",
                format!(
                    "{}'s configuration is owned by its own CLI — not checked here",
                    plat.label()
                ),
                None,
            )),
            Some(mcp_file) => match read_config_entry(&mcp_file, project_root, home) {
                Ok(entry) => {
                    checks.push(Check::ok(
                        "config",
                        format!(
                            "{} — {} -> {}",
                            plat.label(),
                            mcp_file.display(),
                            entry.describe_store()
                        ),
                    ));
                    if primary.is_none() {
                        primary = Some((plat.clone(), entry));
                    }
                }
                Err(msg) => checks.push(Check::fail("config", msg, Some(install_fix(scope, plat)))),
            },
        }
    }

    // The store every check below reads: the one the config entry names, or —
    // with no entry to name it — the one this install's hooks were written for.
    let store: Option<StoreRef> = match &primary {
        Some((_, entry)) => Some(entry.store.clone()),
        None if !mcp_delivery => recorded_store,
        None => None,
    };

    // 2. how the server is spawned — `npx` fetches the package, a resolved
    //    binary or launcher is a file that has to still be there.
    if let Some((_, entry)) = &primary {
        if entry.command == "npx" {
            checks.push(check_npx(entry, ext));
        } else if let Some(check) = check_resolved_path(entry) {
            checks.push(check);
        }
    }

    // 3. store, then the write-lock probe (same check family, adjacent lines).
    //
    // How long that open took is carried down to the handshake, which spawns a
    // server that must repeat it before it can answer anything.
    let mut store_opened_in: Option<Duration> = None;
    match &store {
        Some(store) => {
            let StoreChecks {
                checks: cs,
                opened_in,
            } = check_store_and_lock(store.path());
            checks.extend(cs);
            store_opened_in = opened_in;
        }
        None => checks.push(Check::fail(
            "store",
            no_store_message(mcp_delivery),
            Some(install_fix_for_scope(scope)),
        )),
    }

    // 4. hooks — Claude Code only; Cursor has no prompt/tool-use hooks to check.
    if platforms.contains(&Platform::ClaudeCode) {
        if let Some(store) = &store {
            checks.push(check_hooks(project_root, home, scope, store));
            // The opt-in hooks each earn a line only where the manifest says
            // this install asked for one. Reporting them otherwise would say
            // something about every install that is true of none.
            let opted = opt_ins(project_root, home, scope, &platforms);
            let settings_file = settings_file(project_root, home, scope);
            let settings = read_json(&settings_file).unwrap_or(Js::Null);
            for (asked, sub, event, matcher, flag) in [
                (
                    opted.intercept_grep,
                    "intercept",
                    INTERCEPT_EVENT,
                    "Grep",
                    "--intercept-grep",
                ),
                (
                    opted.impact_before_edit,
                    "impact-hook",
                    IMPACT_EVENT,
                    "Edit|Write|MultiEdit",
                    "--impact-before-edit",
                ),
                (
                    opted.enrich_grep,
                    "enrich",
                    ENRICH_EVENT,
                    "Grep",
                    "--enrich-grep",
                ),
            ] {
                if asked {
                    checks.push(check_opt_in_hook(
                        sub,
                        event,
                        matcher,
                        flag,
                        &settings_file,
                        &settings,
                        store,
                    ));
                }
            }
            if opted.always_load {
                checks.push(check_always_load(project_root, home, scope));
            }
        }
    }

    // 5. git hooks — project scope, and only for the platforms whose install
    //    wires the repository (matches `install::write_everything`).
    if scope == Scope::Project
        && platforms
            .iter()
            .any(|p| matches!(p, Platform::ClaudeCode | Platform::Cursor))
    {
        if let Some(store) = &store {
            if let Some(check) = check_git_hooks(project_root, store) {
                checks.push(check);
            }
        }
    }

    // 6. self-handshake — spawn the configured command for real.
    match &primary {
        Some((_, entry)) => checks.push(check_handshake(entry, store_opened_in)),
        // No entry and none expected: nothing to spawn, and nothing wrong.
        None if !mcp_delivery => checks.push(Check::skip(
            "handshake",
            format!("delivery: {} — no server to spawn", delivery.label()),
        )),
        None => checks.push(Check::fail(
            "handshake",
            "no usable config entry — nothing to spawn",
            Some(install_fix_for_scope(scope)),
        )),
    }

    // 7. duplicate scope — a second Claude Code server in the other scope.
    if platforms.contains(&Platform::ClaudeCode) {
        checks.push(check_scope_conflict(project_root, home, scope));
    }

    let had_fail = checks.iter().any(|c| c.status == Status::Fail);
    let mut output = String::new();
    for c in &checks {
        output.push_str(&c.render());
    }
    Ok(DoctorReport { output, had_fail })
}

/// Why doctor could not find a store to check, in the terms of whichever
/// artifact was supposed to name one.
fn no_store_message(mcp_delivery: bool) -> &'static str {
    if mcp_delivery {
        "no usable config entry — cannot locate a database to check"
    } else {
        "no recorded SessionStart hook — cannot locate a database to check"
    }
}

fn install_fix_for_scope(scope: Scope) -> String {
    format!(
        "mushroomdb install {}",
        match scope {
            Scope::Project => "--project",
            Scope::User => "--user",
        }
    )
}

fn install_fix(scope: Scope, plat: &Platform) -> String {
    format!(
        "mushroomdb install --platform {} {}",
        plat.label(),
        match scope {
            Scope::Project => "--project",
            Scope::User => "--user",
        }
    )
}

fn mcp_file_for(
    plat: &Platform,
    project_root: &Path,
    home: &Path,
    scope: Scope,
) -> Option<PathBuf> {
    match plat {
        Platform::ClaudeCode => Some(claude_mcp_file(project_root, home, scope)),
        Platform::Cursor => Some(cursor_mcp_file(project_root, home, scope)),
        Platform::Codex | Platform::All => None,
    }
}

// ---------------------------------------------------------------------------
// config
// ---------------------------------------------------------------------------

/// The MCP server entry doctor found: what it points at and how it is spawned.
struct ConfigEntry {
    /// The store the entry names, as written: a path, or `--auto`.
    store: StoreRef,
    command: String,
    args: Vec<String>,
}

impl ConfigEntry {
    /// How the config line reports the store. An `--auto` entry says what it
    /// resolves to as well, since that is the directory every check below it
    /// reads and the one the reader wants to see.
    fn describe_store(&self) -> String {
        if self.store.is_auto() {
            format!("{AUTO_ARG} -> {}", self.store.path().display())
        } else {
            self.store.path().display().to_string()
        }
    }
}

/// The store an entry's argument names, resolved the way the command it was
/// written for would resolve it.
///
/// `--auto` is resolved from `project_root` rather than doctor's own working
/// directory: doctor was already told which project it is checking, and a
/// report that changes depending on which subdirectory it was typed in would
/// be a worse report. That is the same directory a hook resolves to, since a
/// hook walks up to the working tree root from wherever it fired.
fn entry_store(arg: &str, project_root: &Path, home: &Path) -> StoreRef {
    if arg == AUTO_ARG {
        return StoreRef::auto(crate::resolve_auto_db(None, project_root, home));
    }
    let path = PathBuf::from(arg);
    if path == default_db(Scope::Project, project_root, home) {
        return StoreRef::pinned(path).also_auto();
    }
    StoreRef::pinned(path)
}

fn read_json(path: &Path) -> Result<Js, String> {
    let raw = std::fs::read_to_string(path)
        .map_err(|e| format!("cannot read {}: {e}", path.display()))?;
    serde_json::from_str(&raw).map_err(|e| format!("invalid JSON in {}: {e}", path.display()))
}

fn read_config_entry(
    mcp_file: &Path,
    project_root: &Path,
    home: &Path,
) -> Result<ConfigEntry, String> {
    if !mcp_file.exists() {
        return Err(format!("{} does not exist", mcp_file.display()));
    }
    let root = read_json(mcp_file)?;
    let entry = &root["mcpServers"]["mushroomdb"];
    if entry.is_null() {
        return Err(format!(
            "no mcpServers.mushroomdb entry in {}",
            mcp_file.display()
        ));
    }
    let store = entry_store(
        entry_db(entry).ok_or_else(|| {
            format!(
                "{}: mushroomdb entry has no `mcp <db>|--auto` argument",
                mcp_file.display()
            )
        })?,
        project_root,
        home,
    );
    let command = entry["command"]
        .as_str()
        .ok_or_else(|| format!("{}: mushroomdb entry has no `command`", mcp_file.display()))?
        .to_string();
    let args = entry["args"]
        .as_array()
        .map(|a| {
            a.iter()
                .filter_map(|v| v.as_str().map(str::to_string))
                .collect()
        })
        .unwrap_or_default();
    Ok(ConfigEntry {
        store,
        command,
        args,
    })
}

// ---------------------------------------------------------------------------
// npx
// ---------------------------------------------------------------------------

const NPX_TIMEOUT: Duration = Duration::from_secs(60);

fn check_npx(entry: &ConfigEntry, ext: &Externals) -> Check {
    let pinned = entry
        .args
        .iter()
        .find_map(|a| a.strip_prefix("mushroomdb@"))
        .unwrap_or(crate::VERSION);
    let Some(npx) = ext.which("npx") else {
        return Check::fail(
            "npx",
            "npx is not on PATH",
            Some(
                "install Node.js (which provides npx), or re-install with --command <path>"
                    .to_string(),
            ),
        );
    };
    let args = vec![
        "-y".to_string(),
        format!("mushroomdb@{pinned}"),
        "--version".to_string(),
    ];
    match run_capturing(&npx, &args, NPX_TIMEOUT) {
        RunOutcome::Done(out) if out.contains(pinned) => Check::ok(
            "npx",
            format!("npx -y mushroomdb@{pinned} --version -> {}", out.trim()),
        ),
        RunOutcome::Done(out) => Check::fail(
            "npx",
            format!(
                "npx -y mushroomdb@{pinned} --version printed {:?}, expected to contain {pinned}",
                out.trim()
            ),
            Some("re-run `mushroomdb install` to repin the version".to_string()),
        ),
        RunOutcome::TimedOut => Check::warn(
            "npx",
            format!("npx -y mushroomdb@{pinned} --version timed out after {NPX_TIMEOUT:?}"),
            Some("check network access to the npm registry".to_string()),
        ),
        RunOutcome::Failed(e) => Check::fail("npx", e, None),
    }
}

/// The resolved-path counterpart to [`check_npx`].
///
/// `install` writes a path rather than `npx` so the hooks do not spawn `npx`
/// on every prompt: the package's native binary, or `node <launcher.js>` when
/// the binary was not fetched. Both live in npm's cache, and pruning it — or
/// npx evicting an old version — leaves a command that cannot run. The file
/// existing is the whole check; what it does once it runs is the handshake's
/// business.
///
/// A bare `command` is a PATH lookup, not a file, and is left to the handshake.
fn check_resolved_path(entry: &ConfigEntry) -> Option<Check> {
    let (name, path) = if entry.command == "node" {
        ("launcher", Path::new(entry.args.first()?))
    } else if Path::new(&entry.command).is_absolute() {
        ("binary", Path::new(&entry.command))
    } else {
        return None;
    };
    Some(if path.is_file() {
        Check::ok(name, path.display().to_string())
    } else {
        Check::fail(
            name,
            format!("{} no longer exists", path.display()),
            Some("mushroomdb install (re-resolves it)".to_string()),
        )
    })
}

enum RunOutcome {
    Done(String),
    TimedOut,
    Failed(String),
}

/// Run `bin`, capturing stdout, giving up after `timeout`.
fn run_capturing(bin: &Path, args: &[String], timeout: Duration) -> RunOutcome {
    let mut child = match Command::new(bin)
        .args(args)
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        .spawn()
    {
        Ok(c) => c,
        Err(e) => return RunOutcome::Failed(format!("cannot run {}: {e}", bin.display())),
    };
    let mut stdout = child.stdout.take().expect("piped stdout");
    let (tx, rx) = std::sync::mpsc::channel::<String>();
    std::thread::spawn(move || {
        let mut out = String::new();
        let _ = stdout.read_to_string(&mut out);
        let _ = tx.send(out);
    });
    let deadline = Instant::now() + timeout;
    loop {
        match child.try_wait() {
            Ok(Some(status)) => {
                let out = rx.recv_timeout(Duration::from_secs(1)).unwrap_or_default();
                return if status.success() {
                    RunOutcome::Done(out)
                } else {
                    RunOutcome::Failed(format!("{} exited with {status}", bin.display()))
                };
            }
            Ok(None) if Instant::now() >= deadline => {
                let _ = child.kill();
                let _ = child.wait();
                return RunOutcome::TimedOut;
            }
            Ok(None) => std::thread::sleep(Duration::from_millis(25)),
            Err(e) => return RunOutcome::Failed(format!("cannot wait for {}: {e}", bin.display())),
        }
    }
}

// ---------------------------------------------------------------------------
// store + lock
// ---------------------------------------------------------------------------

/// The store and lock checks, plus how long the store took to open.
///
/// The open time is not reported to the user — it is handed to the handshake
/// check, which spawns a server that has to do the same open again. See
/// [`handshake_deadline`].
struct StoreChecks {
    checks: Vec<Check>,
    opened_in: Option<Duration>,
}

fn check_store_and_lock(db_dir: &Path) -> StoreChecks {
    let mut out = Vec::new();
    let started = Instant::now();
    let store = GraphDb::open_with_options(
        db_dir,
        OpenOptions {
            read_only: true,
            auto_migrate: true,
            repair_wal: true,
        },
    );
    // Measured whether or not the open succeeded: a slow *failing* open is
    // still evidence about what the spawned server is in for.
    let mut opened_in = started.elapsed();
    match store {
        Ok(db) => {
            let stats = db.stats();
            let stale = db.is_stale().unwrap_or(false);
            let floor = db.wal_horizon_floor();
            let total = db.wal_total_commits().unwrap_or(floor);
            // A store that names no namespace is one implicit `default`
            // namespace; saying "1 namespaces" on every single-tenant store
            // would be noise, so the clause appears only once there is more
            // than one — the same rule `format_stats` follows.
            let namespaces = if stats.namespaces.len() > 1 {
                format!(", {} namespaces", stats.namespaces.len())
            } else {
                String::new()
            };
            out.push(Check::ok(
                "store",
                format!(
                    "{} — {} nodes live ({} tombstoned), {} edges{}, history from commit {} of {}{}",
                    db_dir.display(),
                    stats.nodes_live,
                    stats.nodes_tombstoned,
                    stats.edges,
                    namespaces,
                    floor,
                    total,
                    if stale {
                        ", stale (newer commits pending refresh)"
                    } else {
                        ""
                    }
                ),
            ));
            drop(db);

            // Briefly try to take the write lock. Success means nobody else
            // holds it; the handle is dropped immediately, before this
            // function returns, so the lock is never held past the check.
            //
            // Timed as well as the read-only open above, and the larger of the
            // two is what the handshake budgets from: this one is the
            // read-write shape the MCP server itself uses, and the read-only
            // open before it may do less work.
            let write_started = Instant::now();
            match GraphDb::open_with_options(db_dir, OpenOptions::default()) {
                Ok(handle) => {
                    opened_in = opened_in.max(write_started.elapsed());
                    drop(handle);
                    out.push(Check::ok(
                        "lock",
                        "free — no other process is writing".to_string(),
                    ));
                }
                Err(GraphError::Busy { .. }) => out.push(Check::warn(
                    "lock",
                    "another process is writing".to_string(),
                    Some("re-run once the other process finishes".to_string()),
                )),
                Err(e) => out.push(Check::warn("lock", format!("could not verify: {e}"), None)),
            }
        }
        Err(e) => out.push(Check::fail(
            "store",
            format!("cannot open {}: {e}", db_dir.display()),
            Some(format!("mushroomdb verify {}", db_dir.display())),
        )),
    }
    StoreChecks {
        checks: out,
        opened_in: Some(opened_in),
    }
}

// ---------------------------------------------------------------------------
// hooks
// ---------------------------------------------------------------------------

fn check_hooks(project_root: &Path, home: &Path, scope: Scope, store: &StoreRef) -> Check {
    let settings_file = match scope {
        Scope::Project => project_root.join(".claude").join("settings.json"),
        Scope::User => home.join(".claude").join("settings.json"),
    };
    let root = read_json(&settings_file).unwrap_or(Js::Null);
    let has_recall = has_hook_matching(&root, HOOK_EVENT, "recall", store);
    let has_touch = has_hook_matching(&root, TOUCH_EVENT, "touch", store);
    let has_brief = has_hook_matching(&root, BRIEF_EVENT, "brief", store);
    if has_recall && has_touch && has_brief {
        Check::ok(
            "hooks",
            format!(
                "{HOOK_EVENT} + {TOUCH_EVENT} + {BRIEF_EVENT} present in {}",
                settings_file.display()
            ),
        )
    } else {
        let mut missing = Vec::new();
        if !has_recall {
            missing.push(HOOK_EVENT);
        }
        if !has_touch {
            missing.push(TOUCH_EVENT);
        }
        if !has_brief {
            missing.push(BRIEF_EVENT);
        }
        Check::warn(
            "hooks",
            format!(
                "missing {} in {}",
                missing.join(", "),
                settings_file.display()
            ),
            Some("mushroomdb install --platform claude-code".to_string()),
        )
    }
}

/// `alwaysLoad` on the registered server, for an install whose manifest asked
/// for it.
///
/// Reads the file rather than trusting the flag. The two can disagree for
/// ordinary reasons — the entry hand-edited, a `--delivery cli` install that
/// records the flag but registers no server for it to sit on, another tool
/// rewriting `.mcp.json` — and in every one of them the manifest says the
/// experiment is on while the host is deferring the server exactly as before.
/// That is the failure a benchmark arm would silently record as "no effect",
/// so it is a `warn` naming the file, not an `ok`.
fn check_always_load(project_root: &Path, home: &Path, scope: Scope) -> Check {
    let mcp_file = claude_mcp_file(project_root, home, scope);
    let entry = read_json(&mcp_file).unwrap_or(Js::Null);
    if entry["mcpServers"][SERVER_NAME]["alwaysLoad"] == Js::Bool(true) {
        Check::ok(
            "always-load",
            format!(
                "mcpServers.{SERVER_NAME} is marked alwaysLoad in {}",
                mcp_file.display()
            ),
        )
    } else {
        Check::warn(
            "always-load",
            format!("manifest records it but {} does not", mcp_file.display()),
            Some("mushroomdb install --platform claude-code --always-load".to_string()),
        )
    }
}

/// The `settings.json` a Claude Code install at this scope writes its hooks to.
fn settings_file(project_root: &Path, home: &Path, scope: Scope) -> PathBuf {
    match scope {
        Scope::Project => project_root.join(".claude").join("settings.json"),
        Scope::User => home.join(".claude").join("settings.json"),
    }
}

/// One experimental hook, for an install whose manifest asked for it.
///
/// `sub` is the subcommand word, which is what tells two hooks sharing an
/// event apart; `matcher` and `flag` only ever reach the reported text. The
/// parsed settings arrive from the caller so three checks cost one read.
fn check_opt_in_hook(
    sub: &'static str,
    event: &str,
    matcher: &str,
    flag: &str,
    settings_file: &Path,
    root: &Js,
    store: &StoreRef,
) -> Check {
    if has_hook_matching(root, event, sub, store) {
        Check::ok(
            sub,
            format!("{event} ({matcher}) present in {}", settings_file.display()),
        )
    } else {
        Check::warn(
            sub,
            format!("missing {event} in {}", settings_file.display()),
            Some(format!("mushroomdb install --platform claude-code {flag}")),
        )
    }
}

fn has_hook_matching(root: &Js, event: &str, sub: &str, store: &StoreRef) -> bool {
    root["hooks"][event]
        .as_array()
        .map(|groups| {
            groups.iter().any(|g| {
                g["hooks"]
                    .as_array()
                    .map(|hs| {
                        hs.iter().any(|h| {
                            h["command"]
                                .as_str()
                                .is_some_and(|c| is_our_hook_command(c, sub, store))
                        })
                    })
                    .unwrap_or(false)
            })
        })
        .unwrap_or(false)
}

// ---------------------------------------------------------------------------
// git hooks
// ---------------------------------------------------------------------------

fn check_git_hooks(project_root: &Path, store: &StoreRef) -> Option<Check> {
    let dir = git_hooks_dir(project_root)?;
    // The block belongs to this store if it names it either way. An `--auto`
    // block in a checkout whose store is the default is the same store, and
    // that is the shape every project install now writes.
    let missing: Vec<&str> = GIT_HOOKS
        .iter()
        .filter(|name| {
            let content = std::fs::read_to_string(dir.join(name)).unwrap_or_default();
            let names_store = content
                .lines()
                .any(|l| line_runs_for_store(l, "sync", store));
            !(content.contains(HOOK_BEGIN) && names_store)
        })
        .copied()
        .collect();
    Some(if missing.is_empty() {
        Check::ok(
            "git-hooks",
            format!("{} present in {}", GIT_HOOKS.join("/"), dir.display()),
        )
    } else {
        Check::warn(
            "git-hooks",
            format!("missing in {}: {}", dir.display(), missing.join(", ")),
            Some("mushroomdb install --project (omit --no-git-hooks)".to_string()),
        )
    })
}

// ---------------------------------------------------------------------------
// duplicate scope
// ---------------------------------------------------------------------------

fn check_scope_conflict(project_root: &Path, home: &Path, scope: Scope) -> Check {
    let (other_file, other_label, other_flag) = match scope {
        Scope::Project => (
            claude_mcp_file(project_root, home, Scope::User),
            "user",
            "--user",
        ),
        Scope::User => (
            claude_mcp_file(project_root, home, Scope::Project),
            "project",
            "--project",
        ),
    };
    if has_our_server(&other_file) {
        Check::warn(
            "scope",
            format!(
                "a {other_label}-scope mushroomdb server also exists ({}) — both will load",
                other_file.display()
            ),
            Some(format!("mushroomdb uninstall {other_flag}")),
        )
    } else {
        Check::ok(
            "scope",
            "no duplicate server in the other scope".to_string(),
        )
    }
}

// ---------------------------------------------------------------------------
// self-handshake
// ---------------------------------------------------------------------------

/// Floor for the handshake deadline. Enough for any store that opens quickly,
/// and short enough that a genuinely broken server is reported rather than
/// waited on.
const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(10);

/// Slack added on top of twice the observed open, to cover process spawn,
/// dynamic linking and the two round trips the handshake itself costs.
const HANDSHAKE_SPAWN_SLACK: Duration = Duration::from_secs(5);

/// The clause appended to a failed handshake's fix hint when the store's own
/// open is why the deadline was generous.
///
/// A server that must open a slow store before it can answer anything is not a
/// broken server, and saying so saves the reader from debugging a command that
/// is fine. The trigger is that [`handshake_deadline`] was *raised above its
/// floor* — exactly the case where the store's cost is the thing worth naming —
/// rather than the open alone crossing ten seconds, which would stay silent on
/// the five-second opens that already scale the deadline past the floor.
fn slow_store_hint(store_opened_in: Option<Duration>, deadline: Duration) -> String {
    match store_opened_in {
        Some(open) if deadline > HANDSHAKE_TIMEOUT => format!(
            "; the store took {:.1}s to open here, so the server was already given \
             {:.1}s and still did not answer — if the command is right, run \
             `mushroomdb build-index` and `mushroomdb snapshot` to make the open cheap",
            open.as_secs_f64(),
            deadline.as_secs_f64()
        ),
        _ => String::new(),
    }
}

/// How long to wait for the spawned server's `initialize` and `tools/list`.
///
/// The server has to open the same store `doctor` just opened, and that open is
/// not always cheap: a WAL-only store replays its vector rules' index builds
/// every time, which on a debug build of a 200-vector 1,536-dimension corpus is
/// over ten seconds. A fixed 10 s deadline therefore failed the handshake on a
/// store whose *own* open, moments earlier, had taken longer than that without
/// anyone calling it a fault.
///
/// So the deadline follows the evidence: at least [`HANDSHAKE_TIMEOUT`], and
/// otherwise twice the open `doctor` measured plus [`HANDSHAKE_SPAWN_SLACK`].
/// Twice, because the spawned server opens the store on a cold page cache while
/// `doctor`'s own open has just warmed it, and because a debug build's timing
/// varies more than a release one's.
fn handshake_deadline(store_opened_in: Option<Duration>) -> Duration {
    match store_opened_in {
        Some(open) => HANDSHAKE_TIMEOUT.max(open * 2 + HANDSHAKE_SPAWN_SLACK),
        None => HANDSHAKE_TIMEOUT,
    }
}

struct HandshakeOk {
    version: String,
    tool_count: usize,
    /// The repository task tool the listing carried — see [`TASK_PATH_TOOLS`].
    task_tool: String,
}

fn check_handshake(entry: &ConfigEntry, store_opened_in: Option<Duration>) -> Check {
    let deadline = handshake_deadline(store_opened_in);
    match self_handshake(&entry.command, &entry.args, deadline) {
        Ok(HandshakeOk {
            version,
            tool_count,
            task_tool,
        }) => Check::ok(
            "handshake",
            format!(
                "initialize + tools/list ok — version {version}, {tool_count} tools \
                 ({task_tool} present)"
            ),
        ),
        Err(msg) => Check::fail(
            "handshake",
            msg,
            Some(format!(
                "verify `{} {}` runs mushroomdb's MCP server, or re-run `mushroomdb install` \
                 to rewrite the command{}",
                entry.command,
                entry.args.join(" "),
                slow_store_hint(store_opened_in, deadline)
            )),
        ),
    }
}

/// Spawn `command args…`, speak one `initialize` and one `tools/list` request
/// over its stdio, and check the response.
///
/// Reads with `deadline` (see [`handshake_deadline`]); closes stdin once both
/// responses are in (or the deadline passes) so a well-behaved server exits on
/// EOF, then reaps it with a short bounded wait — a broken server never hangs
/// `doctor`.
fn self_handshake(
    command: &str,
    args: &[String],
    timeout: Duration,
) -> Result<HandshakeOk, String> {
    let mut child = Command::new(command)
        .args(args)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        .spawn()
        .map_err(|e| format!("cannot spawn `{command}`: {e}"))?;

    let mut stdin = child.stdin.take().expect("piped stdin");
    let stdout = child.stdout.take().expect("piped stdout");

    let (tx, rx) = std::sync::mpsc::channel::<String>();
    std::thread::spawn(move || {
        let mut reader = BufReader::new(stdout);
        let mut line = String::new();
        loop {
            line.clear();
            match reader.read_line(&mut line) {
                Ok(0) | Err(_) => break,
                Ok(_) => {
                    if tx.send(line.trim().to_string()).is_err() {
                        break;
                    }
                }
            }
        }
    });

    let sent = writeln!(
        stdin,
        r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"protocolVersion":"2024-11-05","capabilities":{{}},"clientInfo":{{"name":"mushroomdb-doctor","version":"1"}}}}}}"#
    )
    .and_then(|()| writeln!(stdin, r#"{{"jsonrpc":"2.0","id":2,"method":"tools/list"}}"#))
    .and_then(|()| stdin.flush());

    let mut init_resp: Option<Js> = None;
    let mut list_resp: Option<Js> = None;
    if sent.is_ok() {
        let deadline = Instant::now() + timeout;
        while (init_resp.is_none() || list_resp.is_none()) && Instant::now() < deadline {
            let remaining = deadline.saturating_duration_since(Instant::now());
            match rx.recv_timeout(remaining.min(Duration::from_millis(50))) {
                Ok(line) if !line.is_empty() => {
                    if let Ok(v) = serde_json::from_str::<Js>(&line) {
                        match v.get("id").and_then(Js::as_i64) {
                            Some(1) => init_resp = Some(v),
                            Some(2) => list_resp = Some(v),
                            _ => {}
                        }
                    }
                }
                Ok(_) => {}
                Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break,
                Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {}
            }
        }
    }

    // EOF on stdin is how a well-behaved server knows to exit; then reap it
    // with a short bounded wait so a broken one cannot hang doctor.
    drop(stdin);
    let reap_deadline = Instant::now() + Duration::from_secs(2);
    loop {
        match child.try_wait() {
            Ok(Some(_)) | Err(_) => break,
            Ok(None) if Instant::now() >= reap_deadline => {
                let _ = child.kill();
                let _ = child.wait();
                break;
            }
            Ok(None) => std::thread::sleep(Duration::from_millis(20)),
        }
    }

    if sent.is_err() {
        return Err(format!("cannot write to `{command}`'s stdin"));
    }
    let init = init_resp
        .ok_or_else(|| format!("`{command}` did not answer `initialize` within {timeout:?}"))?;
    let list = list_resp
        .ok_or_else(|| format!("`{command}` did not answer `tools/list` within {timeout:?}"))?;

    let version = init["result"]["serverInfo"]["version"]
        .as_str()
        .ok_or_else(|| format!("`{command}`: initialize response has no serverInfo.version"))?
        .to_string();
    if version != crate::VERSION {
        return Err(format!(
            "`{command}` reports version {version}, expected {}",
            crate::VERSION
        ));
    }
    let tools = list["result"]["tools"]
        .as_array()
        .ok_or_else(|| format!("`{command}`: tools/list response has no tools array"))?;
    let task_tool = tools
        .iter()
        .filter_map(|t| t["name"].as_str())
        .find(|name| TASK_PATH_TOOLS.contains(name))
        .ok_or_else(|| {
            format!(
                "`{command}`: tools/list includes none of {}",
                TASK_PATH_TOOLS.join(", ")
            )
        })?
        .to_string();

    Ok(HandshakeOk {
        version,
        tool_count: tools.len(),
        task_tool,
    })
}

/// The tool names that prove the repository task path is served rather than the
/// graph API alone.
///
/// Either is enough, because which one is listed follows the store: a store
/// `ingest-git` built advertises `explore` and hides the rest, and any other
/// store advertises `explain_association` among its fifteen. Requiring one
/// particular name would fail `doctor` on exactly the stores the other surface
/// exists for.
const TASK_PATH_TOOLS: [&str; 2] = ["explore", "explain_association"];

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

    /// The deadline never drops below its floor, and it scales with a slow open.
    ///
    /// The floor is what keeps a broken server from being waited on: a store
    /// that opens in milliseconds gives `2 × open + 5 s` well under 10 s, and
    /// the handshake must still get the full 10 s. Above the floor the evidence
    /// wins, because a server that has to repeat a 13 s open cannot answer in
    /// 10 s however healthy it is.
    #[test]
    fn the_handshake_deadline_holds_its_floor_and_scales() {
        // No measurement at all — the store check did not run, or there is no
        // store. Nothing to scale from, so the floor stands.
        assert_eq!(handshake_deadline(None), HANDSHAKE_TIMEOUT);

        // Fast opens: 2 × open + 5 s is below the floor, so the floor holds.
        for ms in [0, 1, 50, 500, 2_400] {
            assert_eq!(
                handshake_deadline(Some(Duration::from_millis(ms))),
                HANDSHAKE_TIMEOUT,
                "a {ms}ms open must not shorten the deadline below its floor"
            );
        }

        // 2.5 s is the crossover: 2 × 2.5 + 5 == 10 s exactly.
        assert_eq!(
            handshake_deadline(Some(Duration::from_millis(2_500))),
            HANDSHAKE_TIMEOUT
        );

        // Above it the measurement decides.
        assert_eq!(
            handshake_deadline(Some(Duration::from_secs(3))),
            Duration::from_secs(11)
        );
        // The CI failure this exists for: a 13.3 s open got a 10 s deadline.
        let ci = Duration::from_millis(13_300);
        let got = handshake_deadline(Some(ci));
        assert_eq!(got, Duration::from_millis(31_600));
        assert!(
            got > ci,
            "the deadline must exceed the open it was measured from"
        );

        // Monotonic: a slower open never buys a shorter deadline.
        let mut prev = handshake_deadline(Some(Duration::ZERO));
        for s in 1..60 {
            let next = handshake_deadline(Some(Duration::from_secs(s)));
            assert!(next >= prev, "deadline shrank at a {s}s open");
            prev = next;
        }
    }

    /// The fix hint names the store's cost exactly when that cost is why the
    /// deadline was raised — and says nothing at the floor, where the store is
    /// not the explanation and mentioning it would send the reader the wrong
    /// way.
    #[test]
    fn the_fix_hint_names_a_slow_store_only_when_it_is_the_reason() {
        // At the floor: silent, whether or not an open was measured.
        assert_eq!(slow_store_hint(None, HANDSHAKE_TIMEOUT), "");
        assert_eq!(
            slow_store_hint(Some(Duration::from_millis(80)), HANDSHAKE_TIMEOUT),
            ""
        );
        // Never speaks without a measurement, even on a raised deadline.
        assert_eq!(slow_store_hint(None, Duration::from_secs(40)), "");

        // Raised: the hint carries both numbers and the two commands that fix
        // a slow open.
        let open = Duration::from_millis(13_300);
        let hint = slow_store_hint(Some(open), handshake_deadline(Some(open)));
        assert!(hint.contains("13.3s"), "the open time: {hint}");
        assert!(hint.contains("31.6s"), "the deadline it bought: {hint}");
        assert!(hint.contains("build-index"), "{hint}");
        assert!(hint.contains("snapshot"), "{hint}");

        // A 4.8s open already raises the deadline past the floor, and that is
        // the case the first spelling of this hint missed.
        let modest = Duration::from_millis(4_800);
        assert!(handshake_deadline(Some(modest)) > HANDSHAKE_TIMEOUT);
        assert!(
            slow_store_hint(Some(modest), handshake_deadline(Some(modest))).contains("4.8s"),
            "an open below ten seconds can still be the reason"
        );
    }
}