instinct-cli 0.3.6

Local memory for AI coding agents: an MCP server and CLI that gives Claude Code, Codex, Cursor and any MCP client the one lesson that fits. Lessons that keep failing go quiet.
//! 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 = 40;
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()).unwrap();
        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()).unwrap();
                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(RM_RF);
    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");
    }
}