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
//! First run: the `prompt` and `guard` hooks seed a bank that does not exist yet with the starter tripwires
//! (exactly what `instinct starter --apply` banks), tell the user once, and never fail. Every test has its own
//! fresh HOME, XDG_DATA_HOME, LOCALAPPDATA and INSTINCT_* environment.
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::{Command, Output, Stdio};
use std::sync::atomic::{AtomicUsize, Ordering};

const PACK: usize = 45;
const RM_RF: &str = "rm -rf \"$BUILD_DIR\"/*";

fn bin() -> &'static str {
    env!("CARGO_BIN_EXE_instinct")
}

/// A fresh machine: its own HOME, XDG_DATA_HOME and LOCALAPPDATA, and no INSTINCT_* variable.
struct Fresh {
    root: PathBuf,
}

impl Fresh {
    fn new(name: &str) -> Fresh {
        static N: AtomicUsize = AtomicUsize::new(0);
        let root = std::env::temp_dir().join(format!(
            "instinct-first-run-{}-{}-{name}",
            std::process::id(),
            N.fetch_add(1, Ordering::Relaxed)
        ));
        let _ = std::fs::remove_dir_all(&root);
        std::fs::create_dir_all(root.join("home")).unwrap();
        Fresh { root }
    }

    /// Where the default bank lands (the folder does not exist yet): `$XDG_DATA_HOME/instinct/bank.hxdb`,
    /// or `%LOCALAPPDATA%\instinct\bank.hxdb` on Windows, matching `default_store`.
    fn bank(&self) -> PathBuf {
        let base = if cfg!(windows) { "local" } else { "data" };
        self.root.join(base).join("instinct").join("bank.hxdb")
    }

    fn cmd(&self, args: &[&str]) -> Command {
        let mut c = Command::new(bin());
        c.args(args)
            .env("HOME", self.root.join("home"))
            .env("XDG_DATA_HOME", self.root.join("data"))
            .env("LOCALAPPDATA", self.root.join("local"))
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped());
        for (k, _) in std::env::vars() {
            if k.starts_with("INSTINCT_") {
                c.env_remove(k);
            }
        }
        c
    }

    fn run(&self, mut c: Command, stdin: &str) -> Output {
        let mut child = c.spawn().unwrap();
        child.stdin.take().unwrap().write_all(stdin.as_bytes()).ok();
        child.wait_with_output().unwrap()
    }

    fn guard(&self, command: &str) -> Output {
        self.run(self.cmd(&["guard"]), &guard_payload(command))
    }
}

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

fn esc(s: &str) -> String {
    s.replace('\\', "\\\\").replace('"', "\\\"")
}

fn guard_payload(command: &str) -> String {
    format!(
        "{{\"cwd\":\"/home/dev/app\",\"hook_event_name\":\"PreToolUse\",\"tool_name\":\"Bash\",\"tool_input\":{{\"command\":\"{}\"}}}}",
        esc(command)
    )
}

const PROMPT: &str = "{\"hook_event_name\":\"UserPromptSubmit\",\"cwd\":\"/home/dev/app\",\"prompt\":\"hello there\"}";

fn text(o: &Output) -> String {
    String::from_utf8_lossy(&o.stdout).into_owned()
}

fn lessons(bank: &Path) -> usize {
    std::fs::read_to_string(bank).map(|t| t.lines().filter(|l| l.contains("\"title\"")).count()).unwrap_or(0)
}

#[test]
fn the_first_ever_guard_call_fires_rm_rf_and_banks_the_pack() {
    let b = Fresh::new("guard");
    assert!(!b.bank().exists());
    let o = b.guard(RM_RF);
    assert!(o.status.success(), "{}", String::from_utf8_lossy(&o.stderr));
    let out = text(&o);
    assert!(out.contains("Instinct tripwire"), "the first call must warn: {out}");
    assert!(out.to_lowercase().contains("rm -rf"), "{out}");
    assert_eq!(lessons(&b.bank()), PACK);
    let bank = std::fs::read_to_string(b.bank()).unwrap();
    assert!(bank.contains("\"source\":\"community\""), "seeded as the pack is");
    assert!(bank.contains("\"state\":\"community\""), "seeded as the pack is");
    assert!(!b.bank().with_extension("hxdb.seed.lock").exists());
}

#[test]
fn the_seeded_bank_is_what_starter_apply_banks() {
    let seeded = Fresh::new("same-seeded");
    assert!(seeded.guard(RM_RF).status.success());
    let applied = Fresh::new("same-applied");
    let o = applied.run(applied.cmd(&["starter", "--apply"]), "");
    assert!(o.status.success());
    let ids = |b: &Fresh| {
        let mut v: Vec<String> = std::fs::read_to_string(b.bank())
            .unwrap()
            .lines()
            .filter(|l| l.contains("\"title\""))
            .map(|l| l.split("\"id\":\"").nth(1).unwrap().split('"').next().unwrap().to_string())
            .collect();
        v.sort();
        v
    };
    assert_eq!(ids(&seeded), ids(&applied));
    assert_eq!(ids(&seeded).len(), PACK);
}

#[test]
fn opting_out_keeps_the_guard_silent_and_creates_no_bank() {
    for off in ["0", "off", "false"] {
        let b = Fresh::new("optout");
        let mut c = b.cmd(&["guard"]);
        c.env("INSTINCT_STARTER", off);
        let o = b.run(c, &guard_payload(RM_RF));
        assert!(o.status.success());
        assert_eq!(text(&o), "", "INSTINCT_STARTER={off}");
        assert!(!b.bank().exists(), "no bank file with INSTINCT_STARTER={off}");
        let mut c = b.cmd(&["prompt"]);
        c.env("INSTINCT_STARTER", off);
        let o = b.run(c, PROMPT);
        assert!(o.status.success());
        assert!(!b.bank().exists(), "the prompt hook must not create it either (INSTINCT_STARTER={off})");
    }
}

#[test]
fn an_existing_bank_is_never_seeded() {
    let b = Fresh::new("existing");
    let o = b.run(
        b.cmd(&[
            "bank", "--title", "Check the build dir", "--when", "cleaning the project output folder",
            "--found", "The folder held user files", "--how", "List it first",
            "--evidence", "Seen once", "--tags", "cleanup",
        ]),
        "",
    );
    assert!(o.status.success(), "{}", String::from_utf8_lossy(&o.stderr));
    assert_eq!(lessons(&b.bank()), 1);
    let o = b.guard(RM_RF);
    assert!(o.status.success());
    assert_eq!(text(&o), "", "rm -rf stays silent: the bank exists");
    let o = b.run(b.cmd(&["prompt"]), PROMPT);
    assert!(o.status.success());
    assert!(!text(&o).contains("systemMessage"));
    assert_eq!(lessons(&b.bank()), 1);
}

#[test]
fn only_the_first_prompt_carries_the_notice() {
    let b = Fresh::new("notice");
    let first = text(&b.run(b.cmd(&["prompt"]), PROMPT));
    let want = format!(
        "\"systemMessage\":\"Instinct created your bank with {PACK} starter tripwires. They warn before risky commands such as rm -rf on an empty variable and never block anything. Set INSTINCT_STARTER=0 to start empty.\""
    );
    assert!(first.contains(&want), "{first}");
    assert!(first.trim_start().starts_with('{') && first.trim_end().ends_with('}'), "{first}");
    assert_eq!(lessons(&b.bank()), PACK);
    let second = text(&b.run(b.cmd(&["prompt"]), PROMPT));
    assert!(!second.contains("systemMessage") && !second.contains("starter tripwires"), "{second}");
    // The guard path tells once too, and only on its seeding call.
    let g = Fresh::new("notice-guard");
    let first = text(&g.guard(RM_RF));
    // On the guard the one systemMessage carries the tripwire line, then the first-run sentence.
    let sentence = want.trim_start_matches("\"systemMessage\":\"").trim_end_matches('"');
    assert!(first.starts_with("{\"systemMessage\":\"Instinct tripwire: "), "{first}");
    assert!(first.contains(&format!("\\n{sentence}\",\"hookSpecificOutput\"")), "{first}");
    let second = text(&g.guard(RM_RF));
    assert!(!second.contains("starter tripwires") && second.contains("additionalContext"), "{second}");
}

#[test]
fn the_plain_text_format_prints_the_notice_as_one_line() {
    let b = Fresh::new("plain");
    let o = b.run(b.cmd(&["guard", "--format", "text"]), &guard_payload(RM_RF));
    let out = text(&o);
    let first = out.lines().next().unwrap();
    assert_eq!(
        first,
        format!("Instinct created your bank with {PACK} starter tripwires. They warn before risky commands such as rm -rf on an empty variable and never block anything. Set INSTINCT_STARTER=0 to start empty.")
    );
    let again = text(&b.run(b.cmd(&["guard", "--format", "text"]), &guard_payload(RM_RF)));
    assert!(!again.contains("starter tripwires"), "{again}");
    let p = Fresh::new("plain-prompt");
    let out = text(&p.run(p.cmd(&["prompt", "--format", "text"]), PROMPT));
    assert!(out.starts_with("Instinct created your bank with"), "{out}");
    assert!(!out.contains('{'), "{out}");
}

#[test]
fn two_concurrent_first_calls_give_exactly_the_pack() {
    for round in 0..8 {
        let b = Fresh::new(&format!("race{round}"));
        let kids: Vec<_> = (0..4)
            .map(|i| {
                let mut c = if i % 2 == 0 { b.cmd(&["guard"]) } else { b.cmd(&["prompt"]) };
                let mut child = c.spawn().unwrap();
                let payload = if i % 2 == 0 { guard_payload(RM_RF) } else { PROMPT.to_string() };
                child.stdin.take().unwrap().write_all(payload.as_bytes()).ok();
                child
            })
            .collect();
        let mut notices = 0;
        for k in kids {
            let o = k.wait_with_output().unwrap();
            assert!(o.status.success(), "{}", String::from_utf8_lossy(&o.stderr));
            notices += text(&o).matches("starter tripwires").count();
        }
        assert_eq!(lessons(&b.bank()), PACK, "round {round}: two sessions must not double the bank");
        assert_eq!(notices, 1, "round {round}: the user is told once");
    }
}

#[test]
fn a_seeded_bank_gets_no_removal_advice_for_the_starter_tripwires() {
    let b = Fresh::new("eval");
    // A delivery with a session id makes the delivery record non-empty, which is when "never fired" is told.
    let payload = guard_payload(RM_RF).replacen('{', "{\"session_id\":\"sess-1\",", 1);
    let o = b.run(b.cmd(&["guard"]), &payload);
    assert!(text(&o).contains("Instinct tripwire"), "{}", text(&o));
    assert_eq!(lessons(&b.bank()), PACK);
    for args in [&["eval"][..], &["eval", "--since", "all"], &["eval", "--json"]] {
        let o = b.run(b.cmd(args), "");
        assert!(o.status.success(), "{}", String::from_utf8_lossy(&o.stderr));
        let out = text(&o);
        assert!(out.contains(&PACK.to_string()), "the eval saw the bank: {out}");
        assert!(!out.contains("--apply-quarantine"), "{out}");
        assert!(!out.contains("--state quarantined"), "{out}");
        assert!(!out.contains("say nearly the same thing"), "{out}");
    }
    let o = b.run(b.cmd(&["eval", "--apply-quarantine"]), "");
    assert!(o.status.success());
    let bank = std::fs::read_to_string(b.bank()).unwrap();
    assert!(!bank.contains("quarantined"), "eval must not quarantine a fresh starter");
    assert_eq!(lessons(&b.bank()), PACK);
}

#[test]
fn a_missing_store_folder_exits_zero_without_a_panic() {
    let b = Fresh::new("nostore");
    let store = b.root.join("not-there").join("sub").join("bank.hxdb");
    let mut c = b.cmd(&["guard"]);
    c.env("INSTINCT_STORE", &store);
    let o = b.run(c, &guard_payload(RM_RF));
    assert_eq!(o.status.code(), Some(0), "{}", String::from_utf8_lossy(&o.stderr));
    assert_eq!(text(&o), "");
    assert!(!String::from_utf8_lossy(&o.stderr).contains("panicked"));
    assert!(!store.exists());
    let mut c = b.cmd(&["prompt"]);
    c.env("INSTINCT_STORE", &store);
    let o = b.run(c, PROMPT);
    assert_eq!(o.status.code(), Some(0));
    assert!(!String::from_utf8_lossy(&o.stderr).contains("panicked"));
    // An explicit store whose folder exists is seeded like any other new bank.
    let ok = b.root.join("here");
    std::fs::create_dir_all(&ok).unwrap();
    let mut c = b.cmd(&["guard"]);
    c.env("INSTINCT_STORE", ok.join("bank.hxdb"));
    let o = b.run(c, &guard_payload(RM_RF));
    assert_eq!(o.status.code(), Some(0));
    assert_eq!(lessons(&ok.join("bank.hxdb")), PACK);
}

/// Claude Code and Codex PreToolUse payloads both get the user-facing `systemMessage` (Codex documents it on
/// PreToolUse: https://learn.chatgpt.com/docs/hooks), and the model-facing `additionalContext` keeps its shape.
#[test]
fn a_fired_tripwire_says_so_to_the_user_and_keeps_additional_context() {
    let b = Fresh::new("sysmsg");
    assert!(b.guard("ls").status.success()); // seeds; nothing fires
    let claude = guard_payload("git reset --hard HEAD~1");
    let codex = claude.replacen(
        '{',
        "{\"session_id\":\"c1\",\"turn_id\":\"t1\",\"model\":\"gpt-5-codex\",\"permission_mode\":\"default\",",
        1,
    );
    for payload in [&claude, &codex] {
        let out = text(&b.run(b.cmd(&["guard"]), payload));
        let head = "{\"systemMessage\":\"Instinct tripwire: ";
        assert!(out.starts_with(head), "{out}");
        let end = out.find("\",\"hookSpecificOutput\"").unwrap_or_else(|| panic!("{out}"));
        let msg = &out[head.len()..end];
        assert!(msg.ends_with(" (advisory, nothing was blocked)"), "{msg}");
        assert!(msg.len() > 40 && !msg.contains("\\n"), "a title, on one line: {msg}");
        // Without the systemMessage member this is byte for byte what the guard printed before.
        let rest = format!("{{{}", &out[end + 2..]);
        assert!(
            rest.starts_with("{\"hookSpecificOutput\":{\"hookEventName\":\"PreToolUse\",\"additionalContext\":\"Instinct tripwire (advisory, nothing is blocked): a saved lesson fits this action.\\n["),
            "{rest}"
        );
        assert!(rest.trim_end().ends_with("\"}}"), "{rest}");
    }
    // Silent stays silent, and the text format is unchanged.
    assert_eq!(text(&b.guard("ls -la")), "");
    let plain = text(&b.run(b.cmd(&["guard", "--format", "text"]), &claude));
    assert!(plain.starts_with("Instinct tripwire (advisory, nothing is blocked)"), "{plain}");
    assert!(!plain.contains("systemMessage"));
}

#[test]
fn other_commands_never_seed() {
    for args in [&["recall", "--q", "rm -rf build"][..], &["stats"], &["decide", "--q", "clean up"], &["instincts"]] {
        let b = Fresh::new("others");
        let _ = b.run(b.cmd(args), "");
        assert!(!b.bank().exists(), "{args:?} must not create a bank");
    }
}

#[test]
fn cline_recall_uses_the_active_workspace_harness_and_task() {
    let b = Fresh::new("cline-recall");
    let workspace = b.root.join("cobalt");
    let other = b.root.join("other");
    std::fs::create_dir(&workspace).unwrap();
    std::fs::create_dir(&other).unwrap();
    let query = "Why does the cobalt orchard conveyor slip?";
    let bank = b.run(b.cmd(&[
        "bank", "--title", "Cobalt orchard conveyor slips", "--when", query,
        "--found", "Encoder signal reversed.", "--how", "Check the \"ORCHID-473\" marker.",
        "--evidence", "Synthetic calibration.", "--project", workspace.to_str().unwrap(),
        "--applicability-harness", "cline", "--applicability-version", "4.1.28",
    ]), "");
    assert!(bank.status.success(), "{}", String::from_utf8_lossy(&bank.stderr));
    let event = |task: &str, version: &str| format!(
        r#"{{"hookName":"UserPromptSubmit","clineVersion":"{version}","taskId":"{task}","workspaceRoots":["{}","{}"],"userPromptSubmit":{{"prompt":"{query}"}}}}"#,
        esc(other.to_str().unwrap()), esc(workspace.to_str().unwrap())
    );
    let prompt = |cwd: &Path, event: &str| {
        let mut cmd = b.cmd(&["prompt"]);
        cmd.current_dir(cwd);
        let o = b.run(cmd, event);
        assert!(o.status.success());
        text(&o)
    };
    let good = event("task-a", "4.1.28");
    let quiet = "{\"cancel\":false}\n";
    assert_eq!(prompt(&other, &good), quiet);
    assert_eq!(prompt(&b.root, &good), quiet);
    assert_eq!(prompt(&workspace, &event("task-a", "4.0.0")), quiet);
    let first = prompt(&workspace, &good);
    assert!(first.starts_with(r#"{"cancel":false,"contextModification":""#), "{first}");
    assert!(first.contains(r#"Check the \"ORCHID-473\" marker."#), "{first}");
    assert!(!prompt(&workspace, &good).contains("ORCHID-473"));
    assert!(prompt(&workspace, &event("task-b", "4.1.28")).contains("ORCHID-473"));
}

#[test]
fn cline_empty_unrelated_or_invalid_input_leaves_the_prompt_alone() {
    let b = Fresh::new("cline-quiet");
    for event in [
        r#"{"userPromptSubmit":{"prompt":"hello there"}}"#,
        r#"{"userPromptSubmit":{"prompt":42}}"#,
        r#"{"hookName":"TaskStart","userPromptSubmit":{"prompt":"skip"}}"#,
        r#"{"prompt":"a different harness sent this"}"#,
        r#"{"userPromptSubmit":{"prompt":"skip"},"workspaceRoots":["relative"]}"#,
        "bad json",
    ] {
        let mut c = b.cmd(&["prompt", "--format", "cline"]);
        c.env("INSTINCT_STARTER", "0");
        let o = b.run(c, event);
        assert!(o.status.success());
        assert_eq!(text(&o), "{\"cancel\":false}\n", "{event}");
    }
}

#[test]
fn cline_without_a_workspace_cannot_load_the_launchers_team_bank() {
    let b = Fresh::new("cline-no-root");
    let workspace = b.root.join("cobalt");
    std::fs::create_dir_all(workspace.join(".git")).unwrap();
    let mut init = b.cmd(&["team", "init"]);
    init.current_dir(&workspace);
    assert!(b.run(init, "").status.success());
    let mut bank = b.cmd(&[
        "bank", "--team", "--title", "Cobalt orchard conveyor slips",
        "--when", "Why does the cobalt orchard conveyor slip?", "--found", "Encoder reversed.",
        "--how", "Check the ORCHID-473 marker.", "--evidence", "Synthetic calibration.",
    ]);
    bank.current_dir(&workspace);
    let o = b.run(bank, "");
    assert!(o.status.success(), "{}", String::from_utf8_lossy(&o.stderr));
    let event = |roots: &str| format!(
        r#"{{"workspaceRoots":{roots},"userPromptSubmit":{{"prompt":"Why does the cobalt orchard conveyor slip?"}}}}"#
    );
    let run = |roots: &str| {
        let mut cmd = b.cmd(&["prompt", "--format", "cline"]);
        cmd.current_dir(&workspace).env("INSTINCT_STARTER", "0");
        text(&b.run(cmd, &event(roots)))
    };
    assert!(run(&format!(r#"["{}"]"#, esc(workspace.to_str().unwrap()))).contains("ORCHID-473"));
    assert_eq!(run("[]"), "{\"cancel\":false}\n");
}