instinct-cli 0.3.10

Shared local memory for coding agents. Save a fix once and find it again in a new session or another connected tool.
//! `instinct guard`: match, no match, malformed stdin, missing store, other harness shapes, project scope.
use std::io::Write;
use std::path::PathBuf;
use std::process::{Command, Stdio};

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

fn store(name: &str) -> PathBuf {
    let dir = std::env::temp_dir().join(format!("instinct-guard-{}-{}-{name}", std::process::id(), uniq()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    dir.join("bank.hxdb")
}

fn empty_home() -> PathBuf {
    store("no-home").parent().unwrap().to_path_buf()
}

fn bank(store: &PathBuf, when: &str, project: Option<&str>) {
    let mut c = Command::new(bin());
    c.env("INSTINCT_STORE", store)
        .args(["bank", "--title", "t", "--when", when, "--found", "f", "--how", "kill the exact PID"])
        .args(["--evidence", "seen twice"]);
    if let Some(p) = project {
        c.args(["--project", p]);
    }
    assert!(c.output().unwrap().status.success());
}

/// Returns (exit code, stdout).
fn guard(store: Option<&PathBuf>, args: &[&str], stdin: &str) -> (i32, String) {
    guard_env(store, args, stdin, &[])
}

fn guard_env(store: Option<&PathBuf>, args: &[&str], stdin: &str, env: &[(&str, &str)]) -> (i32, String) {
    let mut c = Command::new(bin());
    c.arg("guard").args(args).env_remove("INSTINCT_STORE").env_remove("XDG_DATA_HOME").env("HOME", empty_home());
    c.envs(env.iter().copied());
    if let Some(s) = store {
        c.env("INSTINCT_STORE", s);
    }
    let mut child = c.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap();
    // A hook may finish before reading everything; a closed pipe is not a test failure.
    if let Err(e) = child.stdin.take().unwrap().write_all(stdin.as_bytes()) {
        assert_eq!(e.kind(), std::io::ErrorKind::BrokenPipe, "unexpected write error: {e}");
    }
    let out = child.wait_with_output().unwrap();
    assert!(out.stderr.is_empty(), "guard must not write stderr: {}", String::from_utf8_lossy(&out.stderr));
    (out.status.code().unwrap(), String::from_utf8(out.stdout).unwrap())
}

fn claude(command: &str, cwd: &str) -> String {
    format!(
        "{{\"session_id\":\"s\",\"cwd\":\"{cwd}\",\"hook_event_name\":\"PreToolUse\",\"tool_name\":\"Bash\",\"tool_input\":{{\"command\":\"{command}\"}}}}"
    )
}

const WHEN: &str = "pkill -f server kills the shell that runs it";

#[test]
fn a_matching_command_adds_context_in_the_claude_code_form() {
    let s = store("match");
    bank(&s, WHEN, None);
    let (code, out) = guard(Some(&s), &[], &claude("pkill -f server", "/tmp"));
    assert_eq!(code, 0);
    // The user-facing top-level systemMessage comes first; the rest is exactly the shape it always had.
    assert!(out.starts_with("{\"systemMessage\":\"Instinct tripwire: t (advisory, nothing was blocked)\","), "{out}");
    let out = out.replacen("\"systemMessage\":\"Instinct tripwire: t (advisory, nothing was blocked)\",", "", 1);
    assert!(out.starts_with("{\"hookSpecificOutput\":{\"hookEventName\":\"PreToolUse\",\"additionalContext\":\""), "{out}");
    assert!(out.contains("kill the exact PID"));
    assert!(!out.contains("permissionDecision"));
    assert_eq!(out.matches('\n').count(), 1, "one JSON line only");
}

#[test]
fn an_unrelated_command_is_silent() {
    let s = store("nomatch");
    bank(&s, WHEN, None);
    assert_eq!(guard(Some(&s), &[], &claude("ls -la", "/tmp")), (0, String::new()));
}

#[test]
fn bad_input_is_silent_and_exits_zero() {
    let s = store("bad");
    bank(&s, WHEN, None);
    for input in ["", "not json", "{", "[]", "{\"tool_name\":\"Bash\"}", "{\"tool_name\":\"Bash\",\"tool_input\":{}}", "{\"tool_input\":{\"command\":\"pkill -f server\"}}"] {
        assert_eq!(guard(Some(&s), &[], input), (0, String::new()), "input {input:?}");
    }
}

#[test]
fn a_missing_or_unreadable_store_is_silent() {
    // About an empty bank: the first-run seeding is switched off so the bank stays empty.
    let off = [("INSTINCT_STARTER", "0")];
    assert_eq!(guard_env(None, &[], &claude("pkill -f server", "/tmp"), &off), (0, String::new()));
    let gone = store("gone");
    assert_eq!(guard_env(Some(&gone), &[], &claude("pkill -f server", "/tmp"), &off), (0, String::new()));
}

#[test]
fn file_tools_match_on_their_path() {
    let s = store("path");
    bank(&s, "editing migrations/schema.sql by hand drifts from generated schema", None);
    let input = "{\"cwd\":\"/tmp\",\"tool_name\":\"Edit\",\"tool_input\":{\"file_path\":\"/r/migrations/schema.sql\"}}";
    let (code, out) = guard(Some(&s), &[], input);
    assert_eq!(code, 0);
    assert!(out.contains("generated schema"), "{out}");
}

#[test]
fn project_scope_is_the_same_as_prompt() {
    let s = store("project");
    bank(&s, WHEN, Some("studio"));
    assert!(guard(Some(&s), &["--project", "studio"], &claude("pkill -f server", "/tmp")).1.contains("exact PID"));
    assert_eq!(guard(Some(&s), &["--project", "other"], &claude("pkill -f server", "/tmp")).1, "");
    // cwd names the project when --project is absent, exactly as `instinct prompt` does.
    assert_eq!(guard(Some(&s), &[], &claude("pkill -f server", "/work/other")).1, "");
}

#[test]
fn copilot_and_gemini_payloads_parse_but_stay_silent_without_a_documented_context_channel() {
    let s = store("others");
    bank(&s, WHEN, None);
    let copilot = "{\"toolName\":\"bash\",\"toolArgs\":\"{\\\"command\\\":\\\"pkill -f server\\\"}\",\"cwd\":\"/tmp\"}";
    let gemini = "{\"hook_event_name\":\"BeforeTool\",\"tool_name\":\"run_shell_command\",\"tool_input\":{\"command\":\"pkill -f server\"}}";
    for input in [copilot, gemini] {
        assert_eq!(guard(Some(&s), &[], input), (0, String::new()));
        let (code, out) = guard(Some(&s), &["--format", "text"], input);
        assert_eq!(code, 0);
        assert!(out.contains("exact PID") && !out.starts_with('{'), "{out}");
    }
}

#[test]
fn codex_payload_gets_the_same_json_form() {
    let s = store("codex");
    bank(&s, WHEN, None);
    let input = "{\"session_id\":\"s\",\"turn_id\":\"t\",\"cwd\":\"/tmp\",\"hook_event_name\":\"PreToolUse\",\"model\":\"m\",\"permission_mode\":\"default\",\"tool_name\":\"Bash\",\"tool_use_id\":\"u\",\"tool_input\":{\"command\":\"pkill -f server\"}}";
    assert!(guard(Some(&s), &[], input).1.contains("\"hookEventName\":\"PreToolUse\""));
}

/// `instinct prompt` is a UserPromptSubmit hook. Claude Code treats exit 2 as "block and erase the
/// prompt", so every failure (no store, bad payload, damaged bank) must exit 0.
#[test]
fn the_prompt_hook_never_blocks_the_users_prompt() {
    let run = |store: Option<&PathBuf>, stdin: &str| -> i32 {
        let mut c = Command::new(bin());
        c.arg("prompt").env_remove("INSTINCT_STORE").env_remove("XDG_DATA_HOME").env("HOME", empty_home());
        if let Some(s) = store {
            c.env("INSTINCT_STORE", s);
        }
        let mut child = c.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap();
        if let Err(e) = child.stdin.take().unwrap().write_all(stdin.as_bytes()) {
            assert_eq!(e.kind(), std::io::ErrorKind::BrokenPipe, "unexpected write error: {e}");
        }
        child.wait_with_output().unwrap().status.code().unwrap()
    };
    let payload = "{\"prompt\":\"run the test suite\",\"cwd\":\"/tmp\"}";
    assert_eq!(run(None, payload), 0, "no store");
    let good = store("prompt-badjson");
    bank(&good, "running the test suite offline", None);
    assert_eq!(run(Some(&good), "not json"), 0, "bad payload");
    let damaged = store("prompt-damaged");
    std::fs::write(&damaged, b"this is not a bank\n\x00\x01").unwrap();
    assert_eq!(run(Some(&damaged), payload), 0, "damaged bank");
    assert_eq!(run(Some(&good), payload), 0, "normal run");
}

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

/// Claude Code output must stay byte-for-byte what it was, and a real Codex 0.172 payload (extra fields:
/// turn_id, model, permission_mode, transcript_path, tool_use_id) must produce the identical bytes: the one
/// JSON form works in both, so nothing in `guard` branches on the harness.
#[test]
fn claude_code_output_is_byte_identical_and_codex_gets_the_same_bytes() {
    let s = store("bytes");
    bank(&s, WHEN, None);
    let (_, claude_out) = guard(Some(&s), &[], &claude("pkill -f server", "/tmp/w"));
    let codex_in = "{\"session_id\":\"s\",\"turn_id\":\"t1\",\"transcript_path\":\"/tmp/x.jsonl\",\"cwd\":\"/tmp/w\",\"hook_event_name\":\"PreToolUse\",\"model\":\"gpt\",\"permission_mode\":\"bypassPermissions\",\"tool_name\":\"Bash\",\"tool_input\":{\"command\":\"pkill -f server\"},\"tool_use_id\":\"exec-1\"}";
    let s2 = store("bytes2");
    bank(&s2, WHEN, None);
    let (_, codex_out) = guard(Some(&s2), &[], codex_in);
    // Lesson ids differ between two banks; compare with the id masked.
    let mask = |o: &str| {
        let a = o.find("[in-").expect("lesson id");
        let b = a + o[a..].find(']').unwrap();
        format!("{}[ID]{}", &o[..a], &o[b + 1..])
    };
    assert_eq!(mask(&claude_out), mask(&codex_out));
    let expect_head = "{\"systemMessage\":\"Instinct tripwire: t (advisory, nothing was blocked)\",\"hookSpecificOutput\":{\"hookEventName\":\"PreToolUse\",\"additionalContext\":\"Instinct tripwire (advisory, nothing is blocked): a saved lesson fits this action.\\n[in-";
    assert!(claude_out.starts_with(expect_head), "{claude_out}");
    assert!(claude_out.ends_with("\"}}\n"), "{claude_out}");
}