instinct-cli 0.3.9

Shared local memory for coding agents. Save a fix once and find it again in a new session or another connected tool.
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
//! `instinct doctor [--json] [--online] [--store PATH]`: a read-only report of whether Instinct is wired up on this machine.
//!
//! It never writes a file, never touches the network (except one request with `--online`) 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>,
    /// Starter tripwires the bank holds; None when the bank is missing or unreadable.
    starter_held: Option<usize>,
    /// The bank path came from `--store` or INSTINCT_STORE, so a command that targets it must say so.
    explicit: bool,
}

impl Bank {
    /// The exact command that adds the starter tripwires to this bank.
    fn starter_cmd(&self) -> String {
        match (&self.path, self.explicit) {
            (Some(p), true) => {
                let s = p.display().to_string();
                let s = if s.contains(char::is_whitespace) { format!("\"{s}\"") } else { s };
                format!("instinct starter --apply --store {s}")
            }
            _ => "instinct starter --apply".to_string(),
        }
    }
    /// The arguments of `instinct` that add the starter tripwires to this bank (same as `starter_cmd`).
    fn starter_args(&self) -> Vec<String> {
        let mut a = vec!["starter".to_string(), "--apply".to_string()];
        if let (Some(p), true) = (&self.path, self.explicit) {
            a.push("--store".into());
            a.push(p.display().to_string());
        }
        a
    }
    /// An existing, readable bank that holds none of the starter tripwires: the guard stays silent on it.
    fn has_no_starter(&self) -> bool {
        self.exists && self.starter_held == Some(0) && self.starter_new.is_some_and(|n| n > 0)
    }
}

// ------------------------------------------------------------------ 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))
    })
}

/// `[plugins."<id>"]` in Codex's config.toml, enabled (a missing `enabled` key means enabled), by a line scan.
fn toml_plugin_on(text: &str, id: &str) -> bool {
    let header = format!("[plugins.\"{id}\"]");
    let mut inside = false;
    let mut found = false;
    for l in text.lines().map(str::trim) {
        if l.starts_with('[') {
            inside = l == header;
            found |= inside;
        } else if inside && l.replace(' ', "") == "enabled=false" {
            return false;
        }
    }
    found
}

/// A saved Codex hook trust (`[hooks.state."<key>"]`) whose key holds every part in `parts`.
fn toml_hook_trusted(text: &str, parts: &[&str]) -> bool {
    text.lines().map(str::trim).any(|l| l.starts_with("[hooks.state.") && parts.iter().all(|p| l.contains(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

/// The working folder and its git root (nearest ancestor with `.git`), the paths a local-scope plugin can name.
fn project_roots(cwd: Option<&Path>) -> Vec<PathBuf> {
    let Some(c) = cwd else { return Vec::new() };
    let norm = |p: &Path| p.canonicalize().unwrap_or_else(|_| p.to_path_buf());
    let mut v = vec![norm(c)];
    if let Some(g) = c.ancestors().find(|a| a.join(".git").exists()) {
        v.push(norm(g));
    }
    v
}

/// `~/.claude/plugins/installed_plugins.json`: Some(true) when `key` is installed at user scope, Some(false) when
/// at local/project scope for one of `roots`, None otherwise.
fn installed_plugin_scope(reg: &Json, key: &str, roots: &[PathBuf]) -> Option<bool> {
    let Some(Json::Arr(entries)) = reg.get("plugins").and_then(|p| p.get(key)) else { return None };
    let mut found = None;
    for e in entries {
        match e.get("scope") {
            Some(Json::Str(s)) if s == "user" => return Some(true),
            Some(Json::Str(s)) if s == "local" || s == "project" => {
                if let Some(Json::Str(p)) = e.get("projectPath") {
                    let p = Path::new(p);
                    let p = p.canonicalize().unwrap_or_else(|_| p.to_path_buf());
                    if roots.contains(&p) {
                        found = Some(false);
                    }
                }
            }
            _ => {}
        }
    }
    found
}

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 installed = read_json(&dir.join("plugins").join("installed_plugins.json"));
        let roots = project_roots(cwd);
        // `claude plugin install --scope local|project` records the plugin in the project's settings, not the user's.
        let plugin = |key: &'static str| {
            let mut i = from_json(&settings, "plugin", "plugin", "plugin", &|j| plugin_enabled(j, key));
            if i.state == State::Off && project.iter().any(|j| plugin_enabled(j, key)) {
                i = item("plugin", "plugin", State::On, "project plugin");
            }
            // Claude Code 2.1.335 records `--scope local` (and newer `user`/`project`) installs only here.
            if i.state == State::Off {
                if let Cfg::Ok(reg) = &installed {
                    match installed_plugin_scope(reg, key, &roots) {
                        Some(true) => i = item("plugin", "plugin", State::On, "user plugin"),
                        Some(false) => i = item("plugin", "plugin", State::On, "project plugin"),
                        None => {}
                    }
                }
            }
            i
        };
        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"));
        let cfg = read_text(&dir.join("config.toml"));
        // A plugin's hooks live in the plugin, not in hooks.json; Codex lists them under the plugin id.
        let plugin = |id: &'static str| match &cfg {
            Cfg::Ok(t) if toml_plugin_on(t, id) => item("plugin", "plugin", State::On, "plugin"),
            _ => item("plugin", "plugin", State::Off, ""),
        };
        let tripwires = first_on(
            "tripwires",
            "tripwires (instinct guard)",
            vec![from_json(&hooks, "tripwires", "tripwires", "hook", &|j| has_hook(j, "guard")), plugin("instinct@koscak-labs")],
        );
        let autorecall = first_on(
            "autorecall",
            "automatic lookup (instinct prompt)",
            vec![from_json(&hooks, "autorecall", "autorecall", "hook", &|j| has_hook(j, "prompt")), plugin("instinct-autorecall@koscak-labs")],
        );
        // Codex skips a hook that is not trusted, with no message. Present, but not trusted, is not working.
        let saved = |ev: &str, plugin_id: &str| match &cfg {
            Cfg::Ok(t) => toml_hook_trusted(t, &["hooks.json", ev]) || toml_hook_trusted(t, &[plugin_id, ev]),
            _ => false,
        };
        let wants = [(&tripwires, "pre_tool_use", "instinct@koscak-labs"), (&autorecall, "user_prompt_submit", "instinct-autorecall@koscak-labs")];
        let installed: Vec<_> = wants.iter().filter(|(i, _, _)| i.state == State::On).collect();
        let trust = if installed.is_empty() {
            None
        } else if installed.iter().all(|(_, ev, id)| saved(ev, id)) {
            Some(item("trust", "hooks trusted by Codex", State::On, "config.toml"))
        } else {
            Some(item("trust", "hooks trusted by Codex", State::Off, ""))
        };
        items.push(tripwires);
        items.push(autorecall);
        items.extend(trust);
        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>, explicit: bool) -> Bank {
    let Some(p) = path else {
        return Bank { path: None, exists: false, lessons: None, error: false, writable: false, starter_new: None, starter_held: None, explicit };
    };
    let exists = p.exists();
    let mut starter_new = None;
    let mut starter_held = 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();
                starter_held = starter_new.and_then(|n| super::starter::total().map(|t| t.saturating_sub(n)));
                (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, starter_held, explicit }
}

/// 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,
    /// Other `instinct` binaries on PATH whose `--version` could be read, with that version.
    others: Vec<(PathBuf, String)>,
    /// `--online` only: None = not asked, Some(None) = asked but skipped, Some(Some(v)) = latest release.
    online: Option<Option<String>>,
}

/// "instinct 0.3.6", "v0.3.6" or "0.3.6-rc1" -> (0, 3, 6). Anything else is not a version.
fn parse_version(s: &str) -> Option<(u64, u64, u64)> {
    let tok = s.split_whitespace().find(|t| t.trim_start_matches('v').starts_with(|c: char| c.is_ascii_digit()))?;
    let core = tok.trim_start_matches('v').split(['-', '+']).next()?;
    let mut p = core.split('.');
    let v = (p.next()?.parse().ok()?, p.next()?.parse().ok()?, p.next()?.parse().ok()?);
    if p.next().is_some() {
        return None;
    }
    Some(v)
}

/// Run a command with no stdin and at most `secs` seconds, returning its stdout when it exits 0.
fn capture(mut cmd: std::process::Command, secs: u64) -> Option<String> {
    use std::io::Read;
    use std::process::Stdio;
    let mut child = cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::null()).spawn().ok()?;
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(secs);
    let status = loop {
        match child.try_wait() {
            Ok(Some(s)) => break s,
            Ok(None) if std::time::Instant::now() < deadline => std::thread::sleep(std::time::Duration::from_millis(20)),
            _ => {
                let _ = child.kill();
                let _ = child.wait();
                return None;
            }
        }
    };
    let mut out = String::new();
    child.stdout.take()?.take(1 << 16).read_to_string(&mut out).ok()?;
    status.success().then_some(out)
}

/// The newest release tag, from one HTTPS request through the system curl. None when curl is missing or fails.
fn latest_release() -> Option<String> {
    let mut c = std::process::Command::new("curl");
    c.args(["-fsS", "--max-time", "5", "-H", "Accept: application/vnd.github+json", "https://api.github.com/repos/koscak-labs/instinct/releases/latest"]);
    let body = capture(c, 8)?;
    let rest = &body[body.find("\"tag_name\"")? + 10..];
    let rest = &rest[rest.find('"')? + 1..];
    let tag = &rest[..rest.find('"')?];
    parse_version(tag).map(|(a, b, c)| format!("{a}.{b}.{c}"))
}

/// Every other `instinct` on PATH (not this binary, each real file once) with the version it prints.
fn other_binaries(me: Option<&Path>) -> Vec<(PathBuf, String)> {
    let name = if cfg!(windows) { "instinct.exe" } else { "instinct" };
    let mut seen: Vec<PathBuf> = Vec::new();
    let mut out = Vec::new();
    for dir in std::env::var_os("PATH").map(|p| std::env::split_paths(&p).collect::<Vec<_>>()).unwrap_or_default() {
        let c = dir.join(name);
        if !c.is_file() {
            continue;
        }
        let real = plain(fs::canonicalize(&c).unwrap_or(c));
        if seen.contains(&real) || Some(real.as_path()) == me {
            continue;
        }
        seen.push(real.clone());
        let mut cmd = std::process::Command::new(&real);
        cmd.arg("--version");
        if let Some(v) = capture(cmd, 2).and_then(|o| parse_version(&o)) {
            out.push((real, format!("{}.{}.{}", v.0, v.1, v.2)));
        }
    }
    out
}

/// Plain sentences about version mismatches, for the report. Empty when nothing is out of date.
fn version_notes(pb: &PathBin) -> Vec<String> {
    let mine = parse_version(env!("CARGO_PKG_VERSION"));
    let mut v = Vec::new();
    for (p, ver) in &pb.others {
        match parse_version(ver).cmp(&mine) {
            std::cmp::Ordering::Less => v.push(format!("another instinct on PATH is older ({ver} at {}): remove it or put the new one first", p.display())),
            std::cmp::Ordering::Greater => v.push(format!("another instinct on PATH is newer ({ver} at {}): this {} is out of date; update it or put the new one first", p.display(), env!("CARGO_PKG_VERSION"))),
            std::cmp::Ordering::Equal => {}
        }
    }
    if let Some(Some(latest)) = &pb.online {
        if parse_version(latest) > mine {
            v.push(format!("the latest release is {latest} and this is {}: see https://github.com/koscak-labs/instinct/releases/latest", env!("CARGO_PKG_VERSION")));
        }
    }
    v
}

/// 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, others: other_binaries(me.as_deref()), online: None }
}

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

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

/// The steps about which `instinct` runs. `doctor --fix` only prints these: the other binary is not Instinct's own file.
fn path_steps(pb: &PathBin, exe: Option<&Path>) -> Vec<String> {
    let mut v = version_notes(pb);
    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())),
        _ => {}
    }
    v
}

/// One safe repair `doctor --fix` runs: a subcommand of this same binary that only writes Instinct's own bank or hooks.
struct Fix {
    what: &'static str,
    args: Vec<String>,
}

/// What `doctor --fix` would run for this state. Nothing here removes or replaces a file Instinct did not write.
fn plan_fixes(bank: &Bank, hs: &[Harness]) -> Vec<Fix> {
    let mut v = Vec::new();
    let tripwire_on = hs.iter().any(|h| h.items.iter().any(|i| i.id == "tripwires" && i.state == State::On));
    if bank.has_no_starter() || (bank.path.is_some() && !bank.exists && !bank.error && !tripwire_on) {
        v.push(Fix { what: "add the starter tripwires to the bank", args: bank.starter_args() });
    }
    let state = |h: &Harness, id: &str| h.items.iter().find(|i| i.id == id).map(|i| i.state);
    for h in hs.iter().filter(|h| h.found) {
        if h.items.iter().any(|i| i.state == State::Unreadable) {
            continue; // a config file we cannot read is left for a human
        }
        match h.id {
            "claude_code" if state(h, "tripwires") != Some(State::On) || state(h, "autorecall") != Some(State::On) => {
                v.push(Fix { what: "connect Claude Code (plugins at project scope)", args: vec!["connect".into(), "claude".into()] });
            }
            "codex" if state(h, "tripwires") != Some(State::On) => {
                v.push(Fix { what: "write the Codex hooks and trust them", args: vec!["connect".into(), "codex".into(), "--trust".into()] });
            }
            "codex" if state(h, "trust") == Some(State::Off) => {
                v.push(Fix { what: "trust the Instinct hooks in Codex", args: vec!["codex-trust".into()] });
            }
            _ => {}
        }
    }
    v
}

fn next_steps(
    bank: &Bank,
    pb: &PathBin,
    exe: Option<&Path>,
    hs: &[Harness],
    prompt: &Activity,
    guard: &Activity,
) -> Vec<String> {
    let mut v = path_steps(pb, exe);
    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") => "claude plugin marketplace add koscak-labs/instinct && claude plugin install instinct@koscak-labs".into(),
                ("claude_code", "autorecall") => "claude 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: codex plugin marketplace add koscak-labs/instinct && codex plugin add instinct@koscak-labs, then instinct codex-trust ({CONNECT}#tripwires)"),
                ("codex", "trust") => "Codex skips hooks it has not trusted, silently: run `instinct codex-trust` once (or approve them with /hooks inside Codex)".into(),
                ("codex", "autorecall") => format!("Codex automatic lookup: codex plugin add instinct-autorecall@koscak-labs, then instinct codex-trust ({CONNECT}#codex-cli)"),
                ("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.has_no_starter() {
        v.push(format!(
            "this bank holds none of the starter tripwires, so `instinct guard` stays silent on rm -rf, git push --force and the like: {}",
            bank.starter_cmd()
        ));
    }
    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(format!("or add the starter tripwires now without hooks: {}", bank.starter_cmd()));
    }
    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()))
    });
    // Only present when there is something to say, so the schema without it is exactly what it was.
    let notes = version_notes(pb);
    let version_j = if notes.is_empty() && pb.online.is_none() {
        String::new()
    } else {
        let others: Vec<String> = pb.others.iter().map(|(p, v)| format!("{{\"path\":{},\"version\":{}}}", jstr(&p.display().to_string()), jstr(v))).collect();
        let online = match &pb.online {
            None => String::new(),
            Some(l) => format!(",\"latest_release\":{}", l.as_deref().map_or("null".into(), jstr)),
        };
        format!(",\"version_check\":{{\"other_binaries\":[{}]{}}}", others.join(","), online)
    };
    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() },
        version_j,
        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},\"starter_none\":{},\"starter_command\":{}",
            bank.has_no_starter(),
            jstr(&bank.starter_cmd())
        )),
        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(if pb.online.is_some() {
        "instinct doctor (read-only: nothing is written; --online sent one request to api.github.com)\n\n"
    } else {
        "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")));
    for note in version_notes(pb) {
        o.push_str(&format!("version   {note}\n"));
    }
    match &pb.online {
        Some(None) => o.push_str("version   online check skipped: no curl, or no answer from GitHub\n"),
        Some(Some(v)) if parse_version(v) <= parse_version(env!("CARGO_PKG_VERSION")) => o.push_str(&format!("version   latest release is {v}: up to date\n")),
        _ => {}
    }
    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 bank.has_no_starter() {
                o.push_str(&format!(
                    "starter   none of the starter tripwires are in this bank, so the guard is silent on rm -rf $VAR, git push --force and the like: {}\n",
                    bank.starter_cmd()
                ));
            } else if let Some(n) = bank.starter_new.filter(|&n| n > 0) {
                o.push_str(&format!("starter   {n} new starter tripwires: {}\n", bank.starter_cmd()));
            }
        }
    }
    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));
    o.push_str(&if super::fix::enabled() {
        "fixes     on: guard rewrites rm -rf $VAR, git push --force and poll loops before they run (INSTINCT_FIX=0 turns it off; instinct fix --dry-run CMD)\n".to_string()
    } else {
        "fixes     off (INSTINCT_FIX=0): guard only warns\n".to_string()
    });
    if let Some(p) = &bank.path {
        o.push_str(&speed::doctor_line(p));
    }
    o.push_str(&super::leftovers::doctor_line());
    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
}

const USAGE: &str = "usage: instinct doctor [--json] [--online] [--store PATH] [--fix]";

pub fn run(argv: &[String]) -> Result<(), String> {
    if argv.iter().any(|a| a == "--leftovers") {
        return super::leftovers::run(argv);
    }
    if argv.iter().any(|a| a == "--waits") {
        return super::waits::run(argv);
    }
    let mut json = false;
    let mut online = false;
    let mut fix = false;
    let mut store: Option<PathBuf> = None;
    let mut i = 0;
    while i < argv.len() {
        match argv[i].as_str() {
            "--json" => json = true,
            "--online" => online = true,
            "--fix" => fix = true,
            "--store" => {
                i += 1;
                store = Some(PathBuf::from(argv.get(i).ok_or(USAGE)?));
            }
            _ => return Err(USAGE.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 mut pb = first_on_path(exe.as_deref());
    if online {
        pb.online = Some(latest_release());
    }
    let explicit_flag = store.is_some();
    let store_path = match store {
        Some(p) => Some(p),
        None => default_store().ok(),
    };
    let explicit = explicit_flag || std::env::var_os("INSTINCT_STORE").is_some_and(|v| !v.is_empty());
    let cwd = std::env::current_dir().ok();
    let gather = || {
        let bank = inspect_bank(store_path.as_deref(), explicit);
        let (prompt, guard) = match &store_path {
            Some(p) => activity(p),
            None => (Activity { last: None }, Activity { last: None }),
        };
        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(),
        };
        (bank, prompt, guard, hs)
    };
    let (mut bank, mut prompt, mut guard, mut hs) = gather();
    let mut failed = 0;
    if fix {
        let say = |l: String| if json { eprintln!("{l}") } else { println!("{l}") };
        let plan = plan_fixes(&bank, &hs);
        if plan.is_empty() {
            say("fix: nothing to fix: no repair that only touches Instinct's own files or hooks is needed".into());
        }
        for f in &plan {
            let exe = exe.clone().ok_or("cannot find the instinct binary to run the fixes")?;
            say(format!("fix: {} ($ instinct {})", f.what, f.args.join(" ")));
            match std::process::Command::new(&exe).args(&f.args).stdin(std::process::Stdio::null()).output() {
                Ok(o) => {
                    for l in String::from_utf8_lossy(&o.stdout).lines().chain(String::from_utf8_lossy(&o.stderr).lines()).filter(|l| !l.trim().is_empty()).take(8) {
                        say(format!("    {l}"));
                    }
                    if o.status.success() {
                        say("    done".into());
                    } else {
                        failed += 1;
                        say(format!("    failed (exit {})", o.status.code().unwrap_or(-1)));
                    }
                }
                Err(e) => {
                    failed += 1;
                    say(format!("    could not run: {e}"));
                }
            }
        }
        for l in path_steps(&pb, exe.as_deref()) {
            say(format!("left for you (another binary is not Instinct's to change): {l}"));
        }
        (bank, prompt, guard, hs) = gather();
        say(String::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}");
    }
    if failed > 0 {
        return Err(format!("{failed} fix{} failed (see above)", if failed == 1 { "" } else { "es" }));
    }
    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"));
    }
}