instinct-cli 0.3.7

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
//! `instinct doctor`: read-only, always exit 0, never prints config contents. Every test runs on a fixture machine
//! with its own HOME, XDG_DATA_HOME and LOCALAPPDATA.
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};

const SECRET: &str = "sk-test-SECRET123";

struct Machine {
    root: PathBuf,
}

impl Machine {
    fn new(name: &str) -> Machine {
        let root = std::env::temp_dir().join(format!("instinct-doctor-test-{}-{}-{name}", std::process::id(), uniq()));
        let _ = std::fs::remove_dir_all(&root);
        std::fs::create_dir_all(root.join("home")).unwrap();
        std::fs::create_dir_all(root.join("xdg")).unwrap();
        std::fs::create_dir_all(root.join("local")).unwrap();
        Machine { root }
    }
    fn home(&self) -> PathBuf {
        self.root.join("home")
    }
    fn put(&self, rel: &str, text: &str) {
        let p = self.home().join(rel);
        std::fs::create_dir_all(p.parent().unwrap()).unwrap();
        std::fs::write(p, text).unwrap();
    }
    fn dir(&self, rel: &str) {
        std::fs::create_dir_all(self.home().join(rel)).unwrap();
    }
    fn cmd(&self, args: &[&str]) -> Command {
        let mut c = Command::new(env!("CARGO_BIN_EXE_instinct"));
        c.env_remove("INSTINCT_STORE")
            .env_remove("INSTINCT_METER")
            .env("HOME", self.home())
            .env("USERPROFILE", self.home())
            .env("XDG_DATA_HOME", self.root.join("xdg"))
            .env("LOCALAPPDATA", self.root.join("local"))
            .current_dir(&self.root)
            .args(args);
        c
    }
    fn doctor(&self, args: &[&str]) -> (i32, String, String) {
        let mut a = vec!["doctor"];
        a.extend_from_slice(args);
        let o = self.cmd(&a).output().unwrap();
        (
            o.status.code().unwrap_or(-1),
            String::from_utf8_lossy(&o.stdout).into_owned(),
            String::from_utf8_lossy(&o.stderr).into_owned(),
        )
    }
    fn guard(&self) {
        let payload = "{\"cwd\":\"/home/dev/app\",\"hook_event_name\":\"PreToolUse\",\"tool_name\":\"Bash\",\"tool_input\":{\"command\":\"rm -rf $DIR/\"}}";
        let mut c = self.cmd(&["guard"]);
        c.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped());
        let mut child = c.spawn().unwrap();
        child.stdin.take().unwrap().write_all(payload.as_bytes()).unwrap();
        assert!(child.wait_with_output().unwrap().status.success());
    }
    /// Every path under the fixture with its size, to prove a run changed nothing.
    fn snapshot(&self) -> Vec<(String, u64)> {
        fn walk(d: &Path, out: &mut Vec<(String, u64)>) {
            for e in std::fs::read_dir(d).unwrap().flatten() {
                let m = e.metadata().unwrap();
                out.push((e.path().display().to_string(), if m.is_dir() { 0 } else { m.len() }));
                if m.is_dir() {
                    walk(&e.path(), out);
                }
            }
        }
        let mut v = Vec::new();
        walk(&self.root, &mut v);
        v.sort();
        v
    }
}

impl Drop for Machine {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.root);
    }
}

fn line_with<'a>(text: &'a str, needle: &str) -> &'a str {
    text.lines().find(|l| l.contains(needle)).unwrap_or_else(|| panic!("no line with {needle:?} in:\n{text}"))
}

/// Every `"key":` in the JSON text, in order: the schema's shape without its values.
fn keys(json: &str) -> Vec<String> {
    let b = json.as_bytes();
    let mut out = Vec::new();
    let mut i = 0;
    while i < b.len() {
        if b[i] == b'"' {
            let start = i + 1;
            let mut j = start;
            while j < b.len() && b[j] != b'"' {
                if b[j] == b'\\' {
                    j += 1;
                }
                j += 1;
            }
            if b.get(j + 1) == Some(&b':') {
                out.push(json[start..j].to_string());
            }
            i = j;
        }
        i += 1;
    }
    out
}

#[test]
fn an_empty_machine_is_all_absent_with_next_steps_and_exit_0() {
    let m = Machine::new("empty");
    let before = m.snapshot();
    let (code, out, err) = m.doctor(&[]);
    assert_eq!(code, 0, "{err}");
    assert!(out.contains("does not exist yet"), "{out}");
    assert!(line_with(&out, "prompt ").contains("never"), "{out}");
    assert!(line_with(&out, "guard ").contains("never"), "{out}");
    assert!(out.contains("not found on this machine: Claude Code, Codex CLI, Gemini CLI, Cursor, Windsurf, Warp"), "{out}");
    assert!(out.contains("next steps"), "{out}");
    assert!(out.contains("instinct starter --apply"), "{out}");
    assert!(out.contains("npx skills add koscak-labs/instinct --skill instinct"), "{out}");
    assert_eq!(m.snapshot(), before, "doctor must not create or change any file");
    let (code, json, _) = m.doctor(&["--json"]);
    assert_eq!(code, 0);
    assert!(json.contains("\"found\":false"), "{json}");
    assert!(!json.contains("\"found\":true"), "{json}");
    assert!(json.contains("\"exists\":false"), "{json}");
    assert_eq!(m.snapshot(), before);
}

#[test]
fn an_enabled_claude_code_plugin_means_tripwires_on() {
    let m = Machine::new("plugin");
    m.put(".claude/settings.json", "{\"enabledPlugins\":{\"instinct@koscak-labs\":true}}");
    let (code, out, _) = m.doctor(&[]);
    assert_eq!(code, 0);
    assert!(line_with(&out, "tripwires (instinct guard)").contains("on (plugin)"), "{out}");
    assert!(line_with(&out, "automatic lookup").contains("off"), "{out}");
    assert!(out.contains("claude plugin install instinct-autorecall@koscak-labs"), "{out}");
    assert!(!out.contains("claude plugin install instinct@koscak-labs"), "{out}");
    let (_, json, _) = m.doctor(&["--json"]);
    assert!(json.contains("{\"id\":\"tripwires\",\"state\":\"present\",\"via\":\"plugin\"}"), "{json}");
    assert!(json.contains("{\"id\":\"autorecall\",\"state\":\"absent\",\"via\":null}"), "{json}");
}

#[test]
fn claude_code_hooks_and_a_per_project_mcp_server_are_found() {
    let m = Machine::new("claude-hooks");
    m.put(
        ".claude/settings.json",
        "{\"hooks\":{\"PreToolUse\":[{\"matcher\":\"Bash\",\"hooks\":[{\"type\":\"command\",\"command\":\"/opt/bin/instinct guard\"}]}],\"UserPromptSubmit\":[{\"hooks\":[{\"type\":\"command\",\"command\":\"instinct prompt\"}]}]}}",
    );
    m.put(".claude.json", "{\"projects\":{\"/work/app\":{\"mcpServers\":{\"instinct\":{\"command\":\"instinct\"}}}}}");
    let (_, out, _) = m.doctor(&[]);
    assert!(line_with(&out, "tripwires (instinct guard)").contains("on (hook)"), "{out}");
    assert!(line_with(&out, "automatic lookup").contains("on (hook)"), "{out}");
    assert!(line_with(&out, "MCP server").contains("on (mcp server)"), "{out}");
}

#[test]
fn codex_gemini_and_cursor_are_each_detected() {
    let m = Machine::new("others");
    m.put(
        ".codex/hooks.json",
        "{\"hooks\":{\"PreToolUse\":[{\"matcher\":\"Bash\",\"hooks\":[{\"type\":\"command\",\"command\":\"instinct guard\"}]}],\"UserPromptSubmit\":[{\"hooks\":[{\"type\":\"command\",\"command\":\"instinct prompt\"}]}]}}",
    );
    m.put(".codex/config.toml", "model = \"x\"\n[mcp_servers.instinct]\ncommand = \"instinct\"\nargs = [\"mcp\"]\n");
    m.dir(".agents/skills/instinct");
    m.put(
        ".gemini/settings.json",
        "{\"hooks\":{\"BeforeAgent\":[{\"hooks\":[{\"type\":\"command\",\"command\":\"instinct prompt\"}]}]},\"mcpServers\":{\"instinct\":{\"command\":\"instinct\"}}}",
    );
    m.put(".cursor/mcp.json", "{\"mcpServers\":{\"instinct\":{\"command\":\"instinct\",\"args\":[\"mcp\"]}}}");
    let (code, out, _) = m.doctor(&[]);
    assert_eq!(code, 0);
    let section = |name: &str| -> String {
        let at = out.find(name).unwrap_or_else(|| panic!("no {name} in {out}"));
        out[at..].split("\n\n").next().unwrap().to_string()
    };
    let codex = section("Codex CLI (");
    for l in ["tripwires", "automatic lookup", "MCP server", "skill folder"] {
        assert!(line_with(&codex, l).contains("on"), "{codex}");
        assert!(!line_with(&codex, l).contains("off"), "{codex}");
    }
    let gemini = section("Gemini CLI (");
    assert!(line_with(&gemini, "automatic lookup").contains("on (hook)"), "{gemini}");
    assert!(line_with(&gemini, "MCP server").contains("on (settings.json)"), "{gemini}");
    let cursor = section("Cursor (");
    assert!(line_with(&cursor, "MCP server").contains("on (mcp.json)"), "{cursor}");
    assert!(out.contains("not found on this machine: Claude Code"), "{out}");
}

#[test]
fn guard_activity_after_a_real_guard_call_shows_up() {
    let m = Machine::new("activity");
    m.guard();
    let (code, out, _) = m.doctor(&[]);
    assert_eq!(code, 0);
    assert!(line_with(&out, "guard ").contains("last ran just now"), "{out}");
    assert!(line_with(&out, "prompt ").contains("never"), "{out}");
    assert!(out.contains("lessons;") || out.contains("lesson;"), "{out}");
    let (_, json, _) = m.doctor(&["--json"]);
    assert!(json.contains("\"guard\":{\"last_unix\":1"), "{json}");
    assert!(json.contains("\"prompt\":{\"last_unix\":null,\"seconds_ago\":null}"), "{json}");
}

#[test]
fn doctor_on_a_populated_machine_changes_nothing() {
    let m = Machine::new("readonly");
    m.guard();
    m.put(".claude/settings.json", "{\"enabledPlugins\":{\"instinct@koscak-labs\":true}}");
    let before = m.snapshot();
    let _ = m.doctor(&[]);
    let _ = m.doctor(&["--json"]);
    assert_eq!(m.snapshot(), before);
}

#[test]
fn a_secret_in_any_config_never_appears_in_any_output() {
    let m = Machine::new("secret");
    let doc = format!(
        "{{\"apiKey\":\"{SECRET}\",\"env\":{{\"TOKEN\":\"{SECRET}\"}},\"enabledPlugins\":{{\"instinct@koscak-labs\":true}},\"hooks\":{{\"PreToolUse\":[{{\"hooks\":[{{\"type\":\"command\",\"command\":\"instinct guard --key {SECRET}\"}}]}}]}},\"mcpServers\":{{\"instinct\":{{\"env\":{{\"K\":\"{SECRET}\"}}}},\"other\":{{\"env\":{{\"K\":\"{SECRET}\"}}}}}}}}"
    );
    m.put(".claude/settings.json", &doc);
    m.put(".claude.json", &doc);
    m.put(".codex/hooks.json", &doc);
    m.put(".codex/config.toml", &format!("key = \"{SECRET}\"\n[mcp_servers.instinct.env]\nK = \"{SECRET}\"\n"));
    m.put(".gemini/settings.json", &doc);
    m.put(".cursor/mcp.json", &doc);
    m.put(".codeium/windsurf/mcp_config.json", &doc);
    m.put(".warp/.mcp.json", &doc);
    for args in [&[][..], &["--json"][..]] {
        let (code, out, err) = m.doctor(args);
        assert_eq!(code, 0);
        assert!(!out.contains("SECRET123") && !err.contains("SECRET123"), "secret leaked:\n{out}\n{err}");
        assert!(out.contains("on"), "the entries should still be found: {out}");
    }
    // and the same when the files are broken
    for f in [".claude/settings.json", ".claude.json", ".codex/hooks.json", ".gemini/settings.json", ".cursor/mcp.json", ".codeium/windsurf/mcp_config.json", ".warp/.mcp.json"] {
        m.put(f, &format!("{{\"apiKey\":\"{SECRET}\",,"));
    }
    for args in [&[][..], &["--json"][..]] {
        let (code, out, err) = m.doctor(args);
        assert_eq!(code, 0);
        assert!(!out.contains("SECRET123") && !err.contains("SECRET123"), "secret leaked:\n{out}\n{err}");
    }
}

#[test]
fn malformed_configs_report_unreadable_and_nothing_panics() {
    let m = Machine::new("malformed");
    m.put(".claude/settings.json", "{not json");
    m.put(".claude.json", "[1,2,");
    m.put(".codex/hooks.json", "");
    m.put(".gemini/settings.json", "\u{1}garbage");
    m.put(".cursor/mcp.json", "{\"mcpServers\":");
    m.put(".codeium/windsurf/mcp_config.json", "{\"mcpServers\":");
    m.put(".warp/.mcp.json", "{\"mcpServers\":");
    let (code, out, err) = m.doctor(&[]);
    assert_eq!(code, 0, "{err}");
    assert!(!err.contains("panicked") && !out.contains("panicked"), "{err}");
    for l in ["tripwires (instinct guard)", "MCP server"] {
        assert!(out.lines().any(|x| x.contains(l) && x.contains("unreadable")), "{l}: {out}");
    }
    assert!(out.matches("unreadable (could not parse the config file)").count() >= 8, "{out}");
    let (code, json, _) = m.doctor(&["--json"]);
    assert_eq!(code, 0);
    assert!(json.contains("\"state\":\"unreadable\""), "{json}");
    assert!(!json.contains("\"state\":\"present\""), "{json}");
}

#[test]
fn the_json_schema_is_stable() {
    let m = Machine::new("schema");
    m.put(".claude/settings.json", "{}");
    m.put(".codex/config.toml", "");
    m.put(".gemini/settings.json", "{}");
    m.put(".cursor/mcp.json", "{}");
    let (code, json, _) = m.doctor(&["--json"]);
    assert_eq!(code, 0);
    assert_eq!(json.trim_end().lines().count(), 1, "one JSON document on one line");
    let items = |n: usize| (0..n).flat_map(|_| ["id", "state", "via"]).map(String::from).collect::<Vec<_>>();
    let harness = |n: usize| {
        let mut v: Vec<String> = ["id", "name", "config_dir", "found", "items"].iter().map(|s| s.to_string()).collect();
        v.extend(items(n));
        v
    };
    let mut want: Vec<String> = [
        "schema", "binary", "version", "path", "on_path", "path_binary", "path_binary_is_this", "bank", "path", "exists", "lessons", "readable",
        "folder_writable", "activity", "prompt", "last_unix", "seconds_ago", "guard", "last_unix", "seconds_ago",
        "harnesses",
    ]
    .iter()
    .map(|s| s.to_string())
    .collect();
    want.extend(harness(3)); // Claude Code: tripwires, autorecall, mcp
    want.extend(harness(4)); // Codex: tripwires, autorecall, mcp, skill
    want.extend(harness(2)); // Gemini: autorecall, mcp
    want.extend(harness(1)); // Cursor: mcp
    want.extend(harness(0)); // Windsurf: not found here
    want.extend(harness(0)); // Warp: not found here
    want.push("next_steps".into());
    assert_eq!(keys(&json), want, "{json}");
    assert!(json.starts_with("{\"schema\":1,"), "{json}");
    assert!(json.contains(&format!("\"version\":\"{}\"", env!("CARGO_PKG_VERSION"))));
    let mut at = 0;
    for id in ["claude_code", "codex", "gemini_cli", "cursor", "windsurf", "warp"] {
        let p = json[at..].find(&format!("{{\"id\":\"{id}\"")).unwrap_or_else(|| panic!("{id} out of order in {json}"));
        at += p + 1;
    }
}

/// Run doctor with PATH set to exactly `path_dirs`.
fn doctor_with_path(m: &Machine, path_dirs: &[&Path], args: &[&str]) -> (i32, String) {
    let joined = std::env::join_paths(path_dirs).unwrap();
    let mut a = vec!["doctor"];
    a.extend_from_slice(args);
    let o = m.cmd(&a).env("PATH", joined).output().unwrap();
    (o.status.code().unwrap_or(-1), String::from_utf8_lossy(&o.stdout).into_owned())
}

fn stub_dir(m: &Machine) -> PathBuf {
    let d = m.root.join("stubbin");
    std::fs::create_dir_all(&d).unwrap();
    let name = if cfg!(windows) { "instinct.exe" } else { "instinct" };
    let f = d.join(name);
    std::fs::write(&f, "#!/bin/sh\necho instinct 0.0.1\n").unwrap();
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&f, std::fs::Permissions::from_mode(0o755)).unwrap();
    }
    d
}

#[test]
fn a_different_instinct_first_on_path_is_called_out() {
    let m = Machine::new("pathmismatch");
    let d = stub_dir(&m);
    let name = if cfg!(windows) { "instinct.exe" } else { "instinct" };
    // Doctor shows the path people type: on Windows, canonicalize's verbatim `\\?\` prefix is dropped.
    let canon = std::fs::canonicalize(d.join(name)).unwrap().display().to_string();
    let stub = canon.strip_prefix(r"\\?\").map(str::to_string).unwrap_or(canon.clone());
    let (code, out) = doctor_with_path(&m, &[&d], &[]);
    assert_eq!(code, 0);
    let l = line_with(&out, "binary ");
    assert!(l.contains(&format!("your hooks run {stub} instead (first on PATH)")), "{out}");
    assert!(!l.contains("found on PATH"), "{out}");
    assert!(!out.contains(r"\\?\"), "no verbatim Windows prefix in the report: {out}");
    assert!(out.contains(&format!("check the version your hooks run: {stub} --version, and update it if it is older")), "{out}");
    let (_, json) = doctor_with_path(&m, &[&d], &["--json"]);
    assert!(json.contains("\"on_path\":true"), "{json}");
    // JSON escapes each backslash, so compare against the escaped form.
    assert!(json.contains(&format!("\"path_binary\":\"{}\"", stub.replace('\\', "\\\\"))), "{json}");
    assert!(json.contains("\"path_binary_is_this\":false"), "{json}");
}

#[test]
fn path_set_to_the_binarys_own_dir_gives_no_mismatch() {
    let m = Machine::new("pathsame");
    let me = std::path::Path::new(env!("CARGO_BIN_EXE_instinct")).parent().unwrap().to_path_buf();
    let (code, out) = doctor_with_path(&m, &[&me], &[]);
    assert_eq!(code, 0);
    assert!(line_with(&out, "binary ").contains("found on PATH"), "{out}");
    assert!(!out.contains("your hooks run"), "{out}");
    assert!(!out.contains("check the version your hooks run"), "{out}");
    let (_, json) = doctor_with_path(&m, &[&me], &["--json"]);
    assert!(json.contains("\"path_binary_is_this\":true"), "{json}");
}

#[test]
fn no_instinct_on_path_keeps_the_not_found_wording() {
    let m = Machine::new("pathnone");
    let empty = m.root.join("emptybin");
    std::fs::create_dir_all(&empty).unwrap();
    let (_, out) = doctor_with_path(&m, &[&empty], &[]);
    assert!(line_with(&out, "binary ").contains("not found on PATH"), "{out}");
    let (_, json) = doctor_with_path(&m, &[&empty], &["--json"]);
    assert!(json.contains("\"on_path\":false,\"path_binary\":null,\"path_binary_is_this\":null"), "{json}");
}

#[test]
fn wiring_steps_come_first_and_starter_only_when_no_tripwire_hook_is_on() {
    let m = Machine::new("order");
    m.dir(".claude");
    m.dir(".codex");
    let (_, out, _) = m.doctor(&[]);
    let at = |s: &str| out.find(s).unwrap_or_else(|| panic!("no {s} in {out}"));
    assert!(at("claude plugin marketplace add") < at("codex mcp add"), "{out}");
    assert!(at("codex mcp add") < at("or add the starter tripwires now without hooks: instinct starter --apply"), "{out}");
    // a tripwire hook on anywhere, or an existing bank: no starter step
    m.put(".claude/settings.json", "{\"enabledPlugins\":{\"instinct@koscak-labs\":true}}");
    let (_, out, _) = m.doctor(&[]);
    assert!(!out.contains("starter --apply"), "{out}");
    let m2 = Machine::new("order2");
    m2.guard();
    let (_, out, _) = m2.doctor(&[]);
    assert!(!out.contains("starter --apply"), "{out}");
}

#[test]
fn a_store_flag_points_doctor_at_another_bank() {
    let m = Machine::new("store");
    let bank = m.root.join("elsewhere").join("my.hxdb");
    let (code, out, _) = m.doctor(&["--store", bank.to_str().unwrap()]);
    assert_eq!(code, 0);
    assert!(out.contains(bank.to_str().unwrap()), "{out}");
    assert!(!m.root.join("elsewhere").exists(), "doctor must not create the folder");
}

#[test]
fn an_unknown_flag_is_a_usage_error_not_a_report() {
    let m = Machine::new("badflag");
    let (code, out, err) = m.doctor(&["--frobnicate"]);
    assert_ne!(code, 0);
    assert!(out.is_empty());
    assert!(err.contains("usage: instinct doctor"), "{err}");
}

#[test]
fn windsurf_and_warp_mcp_entries_are_detected_read_only() {
    let m = Machine::new("windsurf-warp");
    let entry = "{\"mcpServers\":{\"instinct\":{\"command\":\"instinct\",\"args\":[\"mcp\"]}}}";
    m.put(".codeium/windsurf/mcp_config.json", "{\"mcpServers\":{\"other\":{\"command\":\"x\"}}}");
    m.put(".warp/.mcp.json", entry);
    let (code, out, _) = m.doctor(&[]);
    assert_eq!(code, 0);
    let section = |out: &str, name: &str| -> String {
        let at = out.find(name).unwrap_or_else(|| panic!("no {name} in {out}"));
        out[at..].split("\n\n").next().unwrap().to_string()
    };
    assert!(line_with(&section(&out, "Warp ("), "MCP server").contains("on (.mcp.json)"), "{out}");
    assert!(line_with(&section(&out, "Windsurf ("), "MCP server").contains("off"), "{out}");
    assert!(out.contains("Windsurf MCP: add the mcpServers snippet"), "{out}");
    // the file Cascade opens counts too
    m.put(".config/devin/mcp_config.json", entry);
    let before = m.snapshot();
    let (_, out, _) = m.doctor(&[]);
    assert!(line_with(&section(&out, "Windsurf ("), "MCP server").contains("on (mcp_config.json)"), "{out}");
    assert_eq!(m.snapshot(), before);
}

/// A number no other call in this test process has seen, so parallel tests never share a folder.
fn uniq() -> usize {
    static N: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
    N.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
}

#[test]
fn a_bank_with_no_starter_tripwires_is_flagged_with_the_exact_command_for_that_bank() {
    // A bank made by hand (an agent that set its own INSTINCT_STORE) is never seeded, so the guard is silent on it.
    let m = Machine::new("nostarter");
    let bank = m.root.join("mine").join("bank.hxdb");
    std::fs::create_dir_all(bank.parent().unwrap()).unwrap();
    let b = m
        .cmd(&["bank", "--store", bank.to_str().unwrap(), "--title", "One lesson", "--when", "running the tests", "--found", "f", "--how", "h", "--evidence", "e"])
        .output()
        .unwrap();
    assert!(b.status.success(), "{}", String::from_utf8_lossy(&b.stderr));
    let (code, out, _) = m.doctor(&["--store", bank.to_str().unwrap()]);
    assert_eq!(code, 0);
    let want = format!("instinct starter --apply --store {}", bank.display());
    assert!(line_with(&out, "starter ").contains("none of the starter tripwires"), "{out}");
    assert!(out.contains(&want), "{out}");
    assert!(out.matches(&want).count() >= 2, "also a next step: {out}");
    let (_, json, _) = m.doctor(&["--store", bank.to_str().unwrap(), "--json"]);
    assert!(json.contains("\"starter_none\":true"), "{json}");
    // INSTINCT_STORE counts as explicit too
    let mut c = m.cmd(&["doctor"]);
    c.env("INSTINCT_STORE", &bank);
    let o = c.output().unwrap();
    assert!(String::from_utf8_lossy(&o.stdout).contains(&want));
    // after applying them the flag is gone
    let a = m.cmd(&["starter", "--apply", "--store", bank.to_str().unwrap()]).output().unwrap();
    assert!(a.status.success());
    let (_, out, _) = m.doctor(&["--store", bank.to_str().unwrap()]);
    assert!(!out.contains("starter --apply"), "{out}");
    // the default bank gets the plain command
    let m2 = Machine::new("nostarter-default");
    let d = m2.cmd(&["bank", "--title", "One", "--when", "w", "--found", "f", "--how", "h", "--evidence", "e"]).output().unwrap();
    assert!(d.status.success());
    let (_, out, _) = m2.doctor(&[]);
    assert!(out.contains("none of the starter tripwires"), "{out}");
    assert!(out.contains("instinct starter --apply\n") && !out.contains("--store"), "{out}");
}

const CODEX_PLUGIN_TOML: &str = "[plugins.\"instinct@koscak-labs\"]\nenabled = true\n";

#[test]
fn codex_plugin_hooks_count_but_an_untrusted_hook_is_reported_as_not_working() {
    let m = Machine::new("codex-trust");
    m.put(".codex/config.toml", CODEX_PLUGIN_TOML);
    let (code, out, _) = m.doctor(&[]);
    assert_eq!(code, 0);
    let codex = &out[out.find("Codex CLI (").expect("codex section")..];
    assert!(line_with(codex, "tripwires").contains("on"), "{codex}");
    assert!(line_with(codex, "trusted by Codex").contains("off"), "{codex}");
    assert!(out.contains("Codex skips hooks it has not trusted"), "{out}");
    // Once Codex has saved a trust entry for the plugin's PreToolUse hook, the item turns on.
    m.put(
        ".codex/config.toml",
        &format!("{CODEX_PLUGIN_TOML}\n[hooks.state.\"instinct@koscak-labs:hooks/hooks.json:pre_tool_use:0:0\"]\ntrusted_hash = \"sha256:aa\"\n"),
    );
    let (_, out, _) = m.doctor(&[]);
    let codex = &out[out.find("Codex CLI (").unwrap()..];
    assert!(line_with(codex, "trusted by Codex").contains("on"), "{codex}");
    assert!(!out.contains("Codex skips hooks it has not trusted"), "{out}");
}

/// `instinct codex-trust` against a stand-in `codex app-server` that speaks the same JSON lines: it must
/// trust only `instinct guard|prompt` hooks, write the first part of a plugin hash, and verify by listing again.
#[cfg(unix)]
#[test]
fn codex_trust_trusts_only_instinct_hooks_and_verifies() {
    use std::os::unix::fs::PermissionsExt;
    let m = Machine::new("codex-trust-cmd");
    let bin = m.root.join("bin");
    std::fs::create_dir_all(&bin).unwrap();
    let marker = m.root.join("written");
    let log = m.root.join("writes.log");
    let script = format!(
        r#"#!/bin/sh
while read -r line; do
  case "$line" in
    *'"initialize"'*) echo '{{"id":1,"result":{{}}}}' ;;
    *'"hooks/list"'*)
      id=$(echo "$line" | sed 's/.*"id":\([0-9]*\).*/\1/')
      if [ -f "{marker}" ]; then st=trusted; else st=untrusted; fi
      echo '{{"id":'$id',"result":{{"data":[{{"cwd":"/","hooks":[{{"key":"instinct@koscak-labs:hooks/hooks.json:pre_tool_use:0:0","eventName":"preToolUse","command":"instinct guard","currentHash":"sha256:aaa/sha256:bbb","trustStatus":"'$st'"}},{{"key":"other:hooks.json:pre_tool_use:0:0","eventName":"preToolUse","command":"rm -rf /","currentHash":"sha256:ccc","trustStatus":"untrusted"}}]}}]}}}}' ;;
    *'"config/batchWrite"'*) echo "$line" >> "{log}"; touch "{marker}"; echo '{{"id":3,"result":{{"status":"ok"}}}}' ;;
  esac
done
"#,
        marker = marker.display(),
        log = log.display()
    );
    let path = bin.join("codex");
    std::fs::write(&path, script).unwrap();
    std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
    let sys = std::env::var("PATH").unwrap_or_default();
    let run = |args: &[&str]| {
        let o = m.cmd(&["codex-trust"]).args(args).env("PATH", format!("{}:{sys}", bin.display())).output().unwrap();
        (o.status.code().unwrap(), String::from_utf8_lossy(&o.stdout).into_owned())
    };
    let (code, out) = run(&["--check"]);
    assert_eq!(code, 0);
    assert!(out.contains("untrusted") && !out.contains("rm -rf"), "{out}");
    assert!(!marker.exists(), "--check must write nothing");
    let (code, out) = run(&[]);
    assert_eq!(code, 0, "{out}");
    assert!(out.contains("trusted") && !out.contains("untrusted"), "{out}");
    let written = std::fs::read_to_string(&log).unwrap();
    assert!(written.contains("\"trusted_hash\":\"sha256:aaa\""), "{written}");
    assert!(!written.contains("bbb") && !written.contains("ccc") && !written.contains("other:"), "{written}");
}