instinct-cli 0.3.6

Local memory for AI coding agents: an MCP server and CLI that gives Claude Code, Codex, Cursor and any MCP client the one lesson that fits. Lessons that keep failing go quiet.
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
//! `instinct doctor [--json] [--store PATH]`: a read-only report of whether Instinct is wired up on this machine.
//!
//! It never writes a file, never touches the network and always exits 0 for a report. It opens the bank, the
//! `<store>.meter` and `<store>.sessions` ledgers, and the config files of the agents whose config folder exists.
//! Privacy: those config files can hold API keys. They are parsed in memory only to answer "is the Instinct
//! entry there?"; nothing read from them is ever printed, logged or stored. Only fixed labels, the config
//! folder paths and the bank path are printed.
//!
//! Where each path and key comes from is listed in docs/connect.md (Claude Code, Codex CLI, "Agents that use
//! `mcpServers`", Tripwires) and in the pull request that added this file.
//! Sibling access goes through `super::` because the playground compiles main.rs as a submodule.
use super::*;

#[derive(Clone, Copy, PartialEq, Debug)]
enum State {
    On,
    Off,
    Unreadable,
}

impl State {
    fn word(self) -> &'static str {
        match self {
            State::On => "present",
            State::Off => "absent",
            State::Unreadable => "unreadable",
        }
    }
}

struct Item {
    id: &'static str,
    label: &'static str,
    state: State,
    /// How it is on: "plugin", "hook", "settings", ... (a fixed label, never file content).
    via: &'static str,
}

struct Harness {
    id: &'static str,
    name: &'static str,
    dir: PathBuf,
    found: bool,
    items: Vec<Item>,
}

struct Activity {
    last: Option<u64>,
}

struct Bank {
    path: Option<PathBuf>,
    exists: bool,
    lessons: Option<usize>,
    error: bool,
    writable: bool,
    /// Starter tripwires the bank does not hold yet; None when the bank is missing or unreadable.
    starter_new: Option<usize>,
}

// ------------------------------------------------------------------ reading config files without printing them

/// A config file as found on disk. Content stays in memory and is only ever searched.
enum Cfg<T> {
    Missing,
    Bad,
    Ok(T),
}

fn read_text(p: &Path) -> Cfg<String> {
    match fs::read(p) {
        Ok(b) => {
            let s = String::from_utf8_lossy(&b).into_owned();
            Cfg::Ok(s.strip_prefix('\u{feff}').map(str::to_owned).unwrap_or(s))
        }
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Cfg::Missing,
        Err(_) => Cfg::Bad,
    }
}

fn read_json(p: &Path) -> Cfg<Json> {
    match read_text(p) {
        Cfg::Ok(t) => match parse_json(&t) {
            Ok(j) => Cfg::Ok(j),
            Err(_) => Cfg::Bad,
        },
        Cfg::Missing => Cfg::Missing,
        Cfg::Bad => Cfg::Bad,
    }
}

/// Does a hook command run `instinct <sub>`? (`instinct.exe` and a full path before the name both count.)
fn runs(cmd: &str, sub: &str) -> bool {
    cmd.replace("instinct.exe", "instinct").contains(&format!("instinct {sub}"))
}

/// Every string anywhere under `j`, to look for hook commands.
fn any_string(j: &Json, f: &dyn Fn(&str) -> bool) -> bool {
    match j {
        Json::Str(s) => f(s),
        Json::Arr(a) => a.iter().any(|x| any_string(x, f)),
        Json::Obj(o) => o.iter().any(|(_, v)| any_string(v, f)),
        _ => false,
    }
}

/// Is there a hook running `instinct <sub>` under the document's `hooks` key?
fn has_hook(doc: &Json, sub: &str) -> bool {
    doc.get("hooks").is_some_and(|h| any_string(h, &|s| runs(s, sub)))
}

/// A `mcpServers` object with an `instinct` key anywhere in the tree (Claude Code keeps per-project servers
/// under `projects.<path>.mcpServers`).
fn mcp_anywhere(j: &Json) -> bool {
    match j {
        Json::Obj(o) => o.iter().any(|(k, v)| {
            (k == "mcpServers" && v.get("instinct").is_some()) || mcp_anywhere(v)
        }),
        Json::Arr(a) => a.iter().any(mcp_anywhere),
        _ => false,
    }
}

fn plugin_enabled(doc: &Json, key: &str) -> bool {
    matches!(doc.get("enabledPlugins").and_then(|p| p.get(key)), Some(Json::Bool(true)))
}

/// `[mcp_servers.instinct]` (or a sub-table of it) in a TOML file, found by a line scan.
fn toml_has_mcp(text: &str) -> bool {
    text.lines().any(|l| {
        let l = l.trim();
        ["[mcp_servers.instinct]", "[mcp_servers.instinct.", "[mcp_servers.\"instinct\"]", "[mcp_servers.\"instinct\"."]
            .iter()
            .any(|p| l.starts_with(p))
    })
}

fn item(id: &'static str, label: &'static str, state: State, via: &'static str) -> Item {
    Item { id, label, state, via }
}

fn from_json(
    cfg: &Cfg<Json>,
    id: &'static str,
    label: &'static str,
    via: &'static str,
    f: &dyn Fn(&Json) -> bool,
) -> Item {
    match cfg {
        Cfg::Ok(j) if f(j) => item(id, label, State::On, via),
        Cfg::Ok(_) | Cfg::Missing => item(id, label, State::Off, ""),
        Cfg::Bad => item(id, label, State::Unreadable, ""),
    }
}

/// First item that is On wins; else Unreadable if any source was unreadable; else Off.
fn first_on(id: &'static str, label: &'static str, tries: Vec<Item>) -> Item {
    if let Some(i) = tries.iter().find(|i| i.state == State::On) {
        return item(id, label, State::On, i.via);
    }
    if tries.iter().any(|i| i.state == State::Unreadable) {
        return item(id, label, State::Unreadable, "");
    }
    item(id, label, State::Off, "")
}

// ------------------------------------------------------------------ harnesses

fn claude_code(home: &Path, cwd: Option<&Path>) -> Harness {
    let dir = home.join(".claude");
    let found = dir.is_dir();
    let mut items = Vec::new();
    if found {
        let settings = read_json(&dir.join("settings.json"));
        let state_file = read_json(&home.join(".claude.json"));
        // Project hook files named in docs/connect.md (`.claude/settings.local.json`); a bad one is just ignored.
        let project: Vec<Json> = cwd
            .map(|c| {
                ["settings.local.json", "settings.json"]
                    .iter()
                    .filter_map(|f| match read_json(&c.join(".claude").join(f)) {
                        Cfg::Ok(j) => Some(j),
                        _ => None,
                    })
                    .collect()
            })
            .unwrap_or_default();
        let proj_hook = |sub: &str| project.iter().any(|j| has_hook(j, sub));
        let hook = |sub: &'static str| {
            let mut i = from_json(&settings, "hook", "hook", "hook", &|j| has_hook(j, sub));
            if i.state == State::Off && proj_hook(sub) {
                i = item("hook", "hook", State::On, "project hook");
            }
            i
        };
        let plugin = |key: &'static str| from_json(&settings, "plugin", "plugin", "plugin", &|j| plugin_enabled(j, key));
        items.push(first_on(
            "tripwires",
            "tripwires (instinct guard)",
            vec![plugin("instinct@koscak-labs"), hook("guard")],
        ));
        items.push(first_on(
            "autorecall",
            "automatic lookup (instinct prompt)",
            vec![plugin("instinct-autorecall@koscak-labs"), hook("prompt")],
        ));
        let direct = from_json(&state_file, "mcp", "mcp", "mcp server", &mcp_anywhere);
        let via_plugin = plugin("instinct@koscak-labs");
        let via_plugin = if via_plugin.state == State::On { item("mcp", "mcp", State::On, "plugin") } else { via_plugin };
        items.push(first_on("mcp", "MCP server", vec![direct, via_plugin]));
    }
    Harness { id: "claude_code", name: "Claude Code", dir, found, items }
}

fn codex(home: &Path) -> Harness {
    let dir = home.join(".codex");
    let found = dir.is_dir();
    let mut items = Vec::new();
    if found {
        let hooks = read_json(&dir.join("hooks.json"));
        items.push(from_json(&hooks, "tripwires", "tripwires (instinct guard)", "hook", &|j| has_hook(j, "guard")));
        items.push(from_json(&hooks, "autorecall", "automatic lookup (instinct prompt)", "hook", &|j| has_hook(j, "prompt")));
        let mcp = match read_text(&dir.join("config.toml")) {
            Cfg::Ok(t) if toml_has_mcp(&t) => item("mcp", "MCP server", State::On, "config.toml"),
            Cfg::Ok(_) | Cfg::Missing => item("mcp", "MCP server", State::Off, ""),
            Cfg::Bad => item("mcp", "MCP server", State::Unreadable, ""),
        };
        items.push(mcp);
        let skill = if home.join(".agents").join("skills").join("instinct").is_dir() {
            item("skill", "skill folder", State::On, "~/.agents/skills")
        } else {
            item("skill", "skill folder", State::Off, "")
        };
        items.push(skill);
    }
    Harness { id: "codex", name: "Codex CLI", dir, found, items }
}

fn gemini(home: &Path) -> Harness {
    let dir = home.join(".gemini");
    let found = dir.is_dir();
    let mut items = Vec::new();
    if found {
        let s = read_json(&dir.join("settings.json"));
        items.push(from_json(&s, "autorecall", "automatic lookup (instinct prompt)", "hook", &|j| has_hook(j, "prompt")));
        items.push(from_json(&s, "mcp", "MCP server", "settings.json", &|j| {
            j.get("mcpServers").is_some_and(|m| m.get("instinct").is_some())
        }));
    }
    Harness { id: "gemini_cli", name: "Gemini CLI", dir, found, items }
}

fn cursor(home: &Path) -> Harness {
    let dir = home.join(".cursor");
    let found = dir.is_dir();
    let mut items = Vec::new();
    if found {
        let s = read_json(&dir.join("mcp.json"));
        items.push(from_json(&s, "mcp", "MCP server", "mcp.json", &|j| {
            j.get("mcpServers").is_some_and(|m| m.get("instinct").is_some())
        }));
    }
    Harness { id: "cursor", name: "Cursor", dir, found, items }
}

/// Windsurf: the editor's discovery file `~/.codeium/windsurf/mcp_config.json` and the file Cascade opens,
/// `~/.config/devin/mcp_config.json` (docs.devin.ai/windsurf/plugins/cascade/mcp). Found by the first folder.
fn windsurf(home: &Path) -> Harness {
    let dir = home.join(".codeium").join("windsurf");
    let found = dir.is_dir();
    let mut items = Vec::new();
    if found {
        let has = |j: &Json| j.get("mcpServers").is_some_and(|m| m.get("instinct").is_some());
        let a = from_json(&read_json(&dir.join("mcp_config.json")), "mcp", "MCP server", "mcp_config.json", &has);
        let b = from_json(&read_json(&home.join(".config").join("devin").join("mcp_config.json")), "mcp", "MCP server", "mcp_config.json", &has);
        items.push(first_on("mcp", "MCP server", vec![a, b]));
    }
    Harness { id: "windsurf", name: "Windsurf", dir, found, items }
}

/// Warp: `~/.warp/.mcp.json` (docs.warp.dev/agent-platform/capabilities/mcp).
fn warp(home: &Path) -> Harness {
    let dir = home.join(".warp");
    let found = dir.is_dir();
    let mut items = Vec::new();
    if found {
        let s = read_json(&dir.join(".mcp.json"));
        items.push(from_json(&s, "mcp", "MCP server", ".mcp.json", &|j| {
            j.get("mcpServers").is_some_and(|m| m.get("instinct").is_some())
        }));
    }
    Harness { id: "warp", name: "Warp", dir, found, items }
}

// ------------------------------------------------------------------ bank and activity

/// Is the bank's folder (or, if it does not exist yet, the nearest existing parent) open for writing by its
/// permissions? Nothing is created to find out.
fn folder_writable(bank: &Path) -> bool {
    let mut d = bank.parent().map(Path::to_path_buf).unwrap_or_default();
    if d.as_os_str().is_empty() {
        d = PathBuf::from(".");
    }
    loop {
        if let Ok(m) = fs::metadata(&d) {
            return m.is_dir() && !m.permissions().readonly();
        }
        match d.parent() {
            Some(p) if !p.as_os_str().is_empty() => d = p.to_path_buf(),
            _ => return false,
        }
    }
}

fn inspect_bank(path: Option<&Path>) -> Bank {
    let Some(p) = path else {
        return Bank { path: None, exists: false, lessons: None, error: false, writable: false, starter_new: None };
    };
    let exists = p.exists();
    let mut starter_new = None;
    let (lessons, error) = if exists {
        match load_plain(&p.to_path_buf()) {
            Ok(v) => {
                let ids: HashSet<String> = v.iter().map(|d| d.id.clone()).collect();
                starter_new = super::starter::new_in(&ids).ok();
                (Some(v.len()), false)
            }
            Err(_) => (None, true),
        }
    } else {
        (Some(0), false)
    };
    Bank { path: Some(p.to_path_buf()), exists, lessons, error, writable: folder_writable(p), starter_new }
}

/// Last run of each hook: the newest of the meter line (`ts kind ...`) and the sessions line carrying
/// that hook's source tag.
fn activity(store: &Path) -> (Activity, Activity) {
    let (mut prompt, mut guard) = (None::<u64>, None::<u64>);
    let bump = |slot: &mut Option<u64>, ts: u64| {
        if ts > 0 && slot.map_or(true, |t| ts > t) {
            *slot = Some(ts);
        }
    };
    if let Ok(b) = fs::read(meter::meter_path(store)) {
        for line in String::from_utf8_lossy(&b).lines() {
            let mut f = line.split_whitespace();
            let (Some(ts), Some(kind)) = (f.next().and_then(|t| t.parse::<u64>().ok()), f.next()) else { continue };
            match kind {
                "prompt" => bump(&mut prompt, ts),
                "guard" => bump(&mut guard, ts),
                _ => {}
            }
        }
    }
    for r in session::records(store) {
        match r.source {
            session::Source::Prompt => bump(&mut prompt, r.ts),
            session::Source::Guard => bump(&mut guard, r.ts),
            session::Source::Unknown => {}
        }
    }
    (Activity { last: prompt }, Activity { last: guard })
}

fn ago(last: Option<u64>, now: u64) -> String {
    let Some(t) = last else { return "never".into() };
    let s = now.saturating_sub(t);
    let (n, unit) = match s {
        0..=59 => return "just now".into(),
        60..=3599 => (s / 60, "min"),
        3600..=86_399 => (s / 3600, "h"),
        _ => (s / 86_400, if s / 86_400 == 1 { "day" } else { "days" }),
    };
    format!("{n} {unit} ago")
}

/// The first `instinct` on PATH (what a hook will run), found without executing it; both paths canonical.
struct PathBin {
    found: Option<PathBuf>,
    same: bool,
}

/// Windows `canonicalize` returns verbatim paths (`\\?\C:\...`, `\\?\UNC\host\share\...`).
/// Show and compare the form people type: `C:\...` and `\\host\share\...`.
fn plain(p: PathBuf) -> PathBuf {
    let s = p.to_string_lossy();
    if let Some(rest) = s.strip_prefix(r"\\?\UNC\") {
        return PathBuf::from(format!(r"\\{rest}"));
    }
    if let Some(rest) = s.strip_prefix(r"\\?\") {
        return PathBuf::from(rest);
    }
    p
}

fn first_on_path(exe: Option<&Path>) -> PathBin {
    let name = if cfg!(windows) { "instinct.exe" } else { "instinct" };
    let found = std::env::var_os("PATH").and_then(|p| {
        std::env::split_paths(&p).map(|d| d.join(name)).find(|c| c.is_file()).map(|c| plain(fs::canonicalize(&c).unwrap_or(c)))
    });
    let me = exe.map(|e| plain(fs::canonicalize(e).unwrap_or_else(|_| e.to_path_buf())));
    let same = found.is_some() && found == me;
    PathBin { found, same }
}

// ------------------------------------------------------------------ next steps

const CONNECT: &str = "https://github.com/koscak-labs/instinct/blob/main/docs/connect.md";

fn next_steps(
    bank: &Bank,
    pb: &PathBin,
    exe: Option<&Path>,
    hs: &[Harness],
    prompt: &Activity,
    guard: &Activity,
) -> Vec<String> {
    let mut v = Vec::new();
    match (&pb.found, pb.same) {
        (None, _) => {
            let dir = exe.and_then(Path::parent).map(|d| d.display().to_string()).unwrap_or_else(|| "the folder holding instinct".into());
            v.push(format!("add {dir} to your PATH, so hooks and MCP servers can start `instinct`"));
        }
        (Some(p), false) => v.push(format!("check the version your hooks run: {} --version, and update it if it is older", p.display())),
        _ => {}
    }
    let any = hs.iter().any(|h| h.found);
    if !any {
        v.push("npx skills add koscak-labs/instinct --skill instinct".into());
    }
    for h in hs.iter().filter(|h| h.found) {
        for i in h.items.iter().filter(|i| i.state != State::On) {
            let unread = i.state == State::Unreadable;
            let step = match (h.id, i.id) {
                (_, _) if unread => format!("{}: fix or remove the unreadable config file in {}, then run `instinct doctor` again", h.name, h.dir.display()),
                ("claude_code", "tripwires") => "/plugin marketplace add koscak-labs/instinct, then /plugin install instinct@koscak-labs".into(),
                ("claude_code", "autorecall") => "/plugin install instinct-autorecall@koscak-labs".into(),
                ("claude_code", "mcp") => "claude mcp add --transport stdio --scope local instinct -- instinct mcp".into(),
                ("codex", "mcp") => "codex mcp add instinct -- instinct mcp".into(),
                ("codex", "tripwires") => format!("Codex tripwires: add the PreToolUse hook from {CONNECT}#tripwires to ~/.codex/hooks.json"),
                ("codex", "autorecall") => format!("Codex automatic lookup: add the UserPromptSubmit hook shown in {CONNECT}#codex-cli to ~/.codex/hooks.json"),
                ("codex", "skill") => "npx skills add koscak-labs/instinct --skill instinct".into(),
                ("gemini_cli", "mcp") => format!("Gemini CLI MCP: add the mcpServers snippet from {CONNECT}#agents-that-use-mcpservers to ~/.gemini/settings.json"),
                ("gemini_cli", "autorecall") => format!("Gemini CLI automatic lookup: add the BeforeAgent hook described in {CONNECT}#agents-that-use-mcpservers to ~/.gemini/settings.json"),
                ("cursor", "mcp") => format!("Cursor MCP: add the mcpServers snippet from {CONNECT}#agents-that-use-mcpservers to ~/.cursor/mcp.json"),
                ("windsurf", "mcp") => format!("Windsurf MCP: add the mcpServers snippet from {CONNECT}#windsurf-warp-and-crush to ~/.codeium/windsurf/mcp_config.json"),
                ("warp", "mcp") => format!("Warp MCP: add the mcpServers snippet from {CONNECT}#windsurf-warp-and-crush to ~/.warp/.mcp.json"),
                _ => continue,
            };
            v.push(step);
        }
    }
    if bank.path.is_none() {
        v.push("set INSTINCT_STORE to a bank file path, or set HOME".into());
    } else if bank.error {
        v.push("the bank could not be read; run `instinct stats` to see the error".into());
    } else if !bank.exists && !hs.iter().any(|h| h.items.iter().any(|i| i.id == "tripwires" && i.state == State::On)) {
        v.push("or add the starter tripwires now without hooks: instinct starter --apply".into());
    }
    let wired = hs.iter().any(|h| h.items.iter().any(|i| i.state == State::On && matches!(i.id, "tripwires" | "autorecall")));
    if wired && prompt.last.is_none() && guard.last.is_none() {
        v.push("use your agent once, then run `instinct doctor` again: a hook that ran shows up under Activity".into());
    }
    v
}

// ------------------------------------------------------------------ output

fn jstr(s: &str) -> String {
    format!("\"{}\"", escape_json(s))
}

fn jopt_num(n: Option<u64>) -> String {
    n.map_or("null".into(), |n| n.to_string())
}

fn render_json(
    exe: Option<&Path>,
    pb: &PathBin,
    bank: &Bank,
    team: &Option<(PathBuf, Option<usize>)>,
    prompt: &Activity,
    guard: &Activity,
    hs: &[Harness],
    steps: &[String],
    now: u64,
) -> String {
    let act = |a: &Activity| {
        format!(
            "{{\"last_unix\":{},\"seconds_ago\":{}}}",
            jopt_num(a.last),
            jopt_num(a.last.map(|t| now.saturating_sub(t)))
        )
    };
    let exe_s = exe.map_or("null".into(), |p| jstr(&p.display().to_string()));
    let bank_path = bank.path.as_ref().map_or("null".into(), |p| jstr(&p.display().to_string()));
    let lessons = bank.lessons.map_or("null".into(), |n| n.to_string());
    let hjson: Vec<String> = hs
        .iter()
        .map(|h| {
            let items: Vec<String> = h
                .items
                .iter()
                .map(|i| {
                    format!(
                        "{{\"id\":{},\"state\":{},\"via\":{}}}",
                        jstr(i.id),
                        jstr(i.state.word()),
                        if i.via.is_empty() { "null".into() } else { jstr(i.via) }
                    )
                })
                .collect();
            format!(
                "{{\"id\":{},\"name\":{},\"config_dir\":{},\"found\":{},\"items\":[{}]}}",
                jstr(h.id),
                jstr(h.name),
                jstr(&h.dir.display().to_string()),
                h.found,
                items.join(",")
            )
        })
        .collect();
    let steps_j: Vec<String> = steps.iter().map(|s| jstr(s)).collect();
    // Only present when a project bank was found, so the schema without one is exactly what it was.
    let team_j = team.as_ref().map_or(String::new(), |(p, n)| {
        format!(",\"team\":{{\"path\":{},\"lessons\":{}}}", jstr(&p.display().to_string()), n.map_or("null".into(), |n| n.to_string()))
    });
    format!(
        "{{\"schema\":1,\"binary\":{{\"version\":{},\"path\":{},\"on_path\":{},\"path_binary\":{},\"path_binary_is_this\":{}}},\"bank\":{{\"path\":{},\"exists\":{},\"lessons\":{},\"readable\":{},\"folder_writable\":{}{}}}{},\"activity\":{{\"prompt\":{},\"guard\":{}}},\"harnesses\":[{}],\"next_steps\":[{}]}}",
        jstr(env!("CARGO_PKG_VERSION")),
        exe_s,
        pb.found.is_some(),
        pb.found.as_ref().map_or("null".into(), |p| jstr(&p.display().to_string())),
        if pb.found.is_some() { pb.same.to_string() } else { "null".into() },
        bank_path,
        bank.exists,
        lessons,
        !bank.error,
        bank.writable,
        bank.starter_new.filter(|&n| n > 0).map_or(String::new(), |n| format!(",\"starter_new\":{n}")),
        team_j,
        act(prompt),
        act(guard),
        hjson.join(","),
        steps_j.join(",")
    )
}

fn render_text(
    exe: Option<&Path>,
    pb: &PathBin,
    bank: &Bank,
    team: &Option<(PathBuf, Option<usize>)>,
    prompt: &Activity,
    guard: &Activity,
    hs: &[Harness],
    steps: &[String],
    now: u64,
) -> String {
    let mut o = String::new();
    o.push_str("instinct doctor (read-only: nothing is written, nothing leaves this machine)\n\n");
    let exe_s = exe.map_or("unknown path".to_string(), |p| p.display().to_string());
    let tail = match (&pb.found, pb.same) {
        (None, _) => "not found on PATH".to_string(),
        (Some(_), true) => "found on PATH".to_string(),
        (Some(p), false) => format!("your hooks run {} instead (first on PATH)", p.display()),
    };
    o.push_str(&format!("binary    instinct {} at {exe_s}; {tail}\n", env!("CARGO_PKG_VERSION")));
    match &bank.path {
        None => o.push_str("bank      no location found (set INSTINCT_STORE or HOME)\n"),
        Some(p) => {
            let state = if bank.error {
                "exists but could not be read".to_string()
            } else if !bank.exists {
                "does not exist yet".to_string()
            } else {
                let n = bank.lessons.unwrap_or(0);
                format!("{n} lesson{}", if n == 1 { "" } else { "s" })
            };
            o.push_str(&format!(
                "bank      {}: {state}; folder {}\n",
                p.display(),
                if bank.writable { "writable" } else { "not writable" }
            ));
            if let Some(n) = bank.starter_new.filter(|&n| n > 0) {
                o.push_str(&format!("starter   {n} new starter tripwires: instinct starter --apply\n"));
            }
        }
    }
    if let Some((p, n)) = team {
        let state = match n {
            Some(n) => format!("{n} lesson{}", if *n == 1 { "" } else { "s" }),
            None => "exists but could not be read".to_string(),
        };
        o.push_str(&format!("team      {}: {state}; read after your bank, shared through git\n", p.display()));
    }
    let line = |name: &str, a: &Activity| match a.last {
        Some(_) => format!("{name:<10}last ran {}\n", ago(a.last, now)),
        None => format!("{name:<10}never ran (no record in the .meter or .sessions file next to the bank)\n"),
    };
    o.push_str(&line("prompt", prompt));
    o.push_str(&line("guard", guard));
    for h in hs.iter().filter(|h| h.found) {
        o.push_str(&format!("\n{} ({})\n", h.name, h.dir.display()));
        for i in &h.items {
            let s = match i.state {
                State::On if i.via.is_empty() => "on".to_string(),
                State::On => format!("on ({})", i.via),
                State::Off => "off".to_string(),
                State::Unreadable => "unreadable (could not parse the config file)".to_string(),
            };
            o.push_str(&format!("  {:<36}{s}\n", i.label));
        }
    }
    let missing: Vec<&str> = hs.iter().filter(|h| !h.found).map(|h| h.name).collect();
    if !missing.is_empty() {
        o.push_str(&format!("\nnot found on this machine: {}\n", missing.join(", ")));
    }
    if !steps.is_empty() {
        o.push_str("\nnext steps\n");
        for (n, s) in steps.iter().enumerate() {
            o.push_str(&format!("  {}. {s}\n", n + 1));
        }
    }
    o
}

pub fn run(argv: &[String]) -> Result<(), String> {
    let mut json = false;
    let mut store: Option<PathBuf> = None;
    let mut i = 0;
    while i < argv.len() {
        match argv[i].as_str() {
            "--json" => json = true,
            "--store" => {
                i += 1;
                store = Some(PathBuf::from(argv.get(i).ok_or("usage: instinct doctor [--json] [--store PATH]")?));
            }
            _ => return Err("usage: instinct doctor [--json] [--store PATH]".into()),
        }
        i += 1;
    }
    let now = now_secs();
    let home = std::env::var_os("HOME")
        .filter(|v| !v.is_empty())
        .or_else(|| std::env::var_os("USERPROFILE").filter(|v| !v.is_empty()))
        .map(PathBuf::from);
    let exe = std::env::current_exe().ok();
    let pb = first_on_path(exe.as_deref());
    let store_path = match store {
        Some(p) => Some(p),
        None => default_store().ok(),
    };
    let bank = inspect_bank(store_path.as_deref());
    let (prompt, guard) = match &store_path {
        Some(p) => activity(p),
        None => (Activity { last: None }, Activity { last: None }),
    };
    let cwd = std::env::current_dir().ok();
    let hs = match &home {
        Some(h) => vec![claude_code(h, cwd.as_deref()), codex(h), gemini(h), cursor(h), windsurf(h), warp(h)],
        None => Vec::new(),
    };
    // The project bank above the working folder, if any: read-only like everything else here.
    let team = store_path.as_deref().and_then(super::team::find).map(|t| {
        let n = super::team::load(&t).ok().map(|v| v.len());
        (t, n)
    });
    let steps = next_steps(&bank, &pb, exe.as_deref(), &hs, &prompt, &guard);
    let out = if json {
        render_json(exe.as_deref(), &pb, &bank, &team, &prompt, &guard, &hs, &steps, now)
    } else {
        render_text(exe.as_deref(), &pb, &bank, &team, &prompt, &guard, &hs, &steps, now)
    };
    if json {
        println!("{out}");
    } else {
        print!("{out}");
    }
    Ok(())
}

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

    #[test]
    fn ago_reads_plainly() {
        assert_eq!(ago(None, 100), "never");
        assert_eq!(ago(Some(100), 130), "just now");
        assert_eq!(ago(Some(100), 100 + 180), "3 min ago");
        assert_eq!(ago(Some(0 + 1), 1 + 7200), "2 h ago");
        assert_eq!(ago(Some(1), 1 + 86_400), "1 day ago");
        assert_eq!(ago(Some(500), 100), "just now");
    }

    #[test]
    fn hook_commands_are_found_by_substring_and_path() {
        assert!(runs("instinct guard", "guard"));
        assert!(runs("/home/u/.cargo/bin/instinct guard --format json", "guard"));
        assert!(runs("C:\\x\\instinct.exe prompt", "prompt"));
        assert!(!runs("instinct recall", "guard"));
    }

    #[test]
    fn toml_scan_matches_the_table_header_only() {
        assert!(toml_has_mcp("[mcp_servers.instinct]\ncommand = \"instinct\"\n"));
        assert!(toml_has_mcp("  [mcp_servers.instinct.env]\n"));
        assert!(!toml_has_mcp("[mcp_servers.other]\n# [mcp_servers.instinct]\n"));
    }
}