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")
}
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 }
}
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}");
let g = Fresh::new("notice-guard");
let first = text(&g.guard(RM_RF));
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");
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"));
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);
}
#[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()); 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}");
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}");
}
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");
}