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());
}
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();
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);
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() {
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, "");
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\""));
}
#[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");
}
fn uniq() -> usize {
static N: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
N.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
}