use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
const SECRET: &str = "sk-test-SECRET123";
struct Machine {
root: PathBuf,
}
impl Machine {
fn new(name: &str) -> Machine {
let root = std::env::temp_dir().join(format!("instinct-doctor-test-{}-{}-{name}", std::process::id(), uniq()));
let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(root.join("home")).unwrap();
std::fs::create_dir_all(root.join("xdg")).unwrap();
std::fs::create_dir_all(root.join("local")).unwrap();
Machine { root }
}
fn home(&self) -> PathBuf {
self.root.join("home")
}
fn put(&self, rel: &str, text: &str) {
let p = self.home().join(rel);
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
std::fs::write(p, text).unwrap();
}
fn dir(&self, rel: &str) {
std::fs::create_dir_all(self.home().join(rel)).unwrap();
}
fn cmd(&self, args: &[&str]) -> Command {
let mut c = Command::new(env!("CARGO_BIN_EXE_instinct"));
c.env_remove("INSTINCT_STORE")
.env_remove("INSTINCT_METER")
.env("HOME", self.home())
.env("USERPROFILE", self.home())
.env("XDG_DATA_HOME", self.root.join("xdg"))
.env("LOCALAPPDATA", self.root.join("local"))
.current_dir(&self.root)
.args(args);
c
}
fn doctor(&self, args: &[&str]) -> (i32, String, String) {
let mut a = vec!["doctor"];
a.extend_from_slice(args);
let o = self.cmd(&a).output().unwrap();
(
o.status.code().unwrap_or(-1),
String::from_utf8_lossy(&o.stdout).into_owned(),
String::from_utf8_lossy(&o.stderr).into_owned(),
)
}
fn guard(&self) {
let payload = "{\"cwd\":\"/home/dev/app\",\"hook_event_name\":\"PreToolUse\",\"tool_name\":\"Bash\",\"tool_input\":{\"command\":\"rm -rf $DIR/\"}}";
let mut c = self.cmd(&["guard"]);
c.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped());
let mut child = c.spawn().unwrap();
child.stdin.take().unwrap().write_all(payload.as_bytes()).unwrap();
assert!(child.wait_with_output().unwrap().status.success());
}
fn snapshot(&self) -> Vec<(String, u64)> {
fn walk(d: &Path, out: &mut Vec<(String, u64)>) {
for e in std::fs::read_dir(d).unwrap().flatten() {
let m = e.metadata().unwrap();
out.push((e.path().display().to_string(), if m.is_dir() { 0 } else { m.len() }));
if m.is_dir() {
walk(&e.path(), out);
}
}
}
let mut v = Vec::new();
walk(&self.root, &mut v);
v.sort();
v
}
}
impl Drop for Machine {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.root);
}
}
fn line_with<'a>(text: &'a str, needle: &str) -> &'a str {
text.lines().find(|l| l.contains(needle)).unwrap_or_else(|| panic!("no line with {needle:?} in:\n{text}"))
}
fn keys(json: &str) -> Vec<String> {
let b = json.as_bytes();
let mut out = Vec::new();
let mut i = 0;
while i < b.len() {
if b[i] == b'"' {
let start = i + 1;
let mut j = start;
while j < b.len() && b[j] != b'"' {
if b[j] == b'\\' {
j += 1;
}
j += 1;
}
if b.get(j + 1) == Some(&b':') {
out.push(json[start..j].to_string());
}
i = j;
}
i += 1;
}
out
}
#[test]
fn an_empty_machine_is_all_absent_with_next_steps_and_exit_0() {
let m = Machine::new("empty");
let before = m.snapshot();
let (code, out, err) = m.doctor(&[]);
assert_eq!(code, 0, "{err}");
assert!(out.contains("does not exist yet"), "{out}");
assert!(line_with(&out, "prompt ").contains("never"), "{out}");
assert!(line_with(&out, "guard ").contains("never"), "{out}");
assert!(out.contains("not found on this machine: Claude Code, Codex CLI, Gemini CLI, Cursor, Windsurf, Warp"), "{out}");
assert!(out.contains("next steps"), "{out}");
assert!(out.contains("instinct starter --apply"), "{out}");
assert!(out.contains("npx skills add koscak-labs/instinct --skill instinct"), "{out}");
assert_eq!(m.snapshot(), before, "doctor must not create or change any file");
let (code, json, _) = m.doctor(&["--json"]);
assert_eq!(code, 0);
assert!(json.contains("\"found\":false"), "{json}");
assert!(!json.contains("\"found\":true"), "{json}");
assert!(json.contains("\"exists\":false"), "{json}");
assert_eq!(m.snapshot(), before);
}
#[test]
fn an_enabled_claude_code_plugin_means_tripwires_on() {
let m = Machine::new("plugin");
m.put(".claude/settings.json", "{\"enabledPlugins\":{\"instinct@koscak-labs\":true}}");
let (code, out, _) = m.doctor(&[]);
assert_eq!(code, 0);
assert!(line_with(&out, "tripwires (instinct guard)").contains("on (plugin)"), "{out}");
assert!(line_with(&out, "automatic lookup").contains("off"), "{out}");
assert!(out.contains("claude plugin install instinct-autorecall@koscak-labs"), "{out}");
assert!(!out.contains("claude plugin install instinct@koscak-labs"), "{out}");
let (_, json, _) = m.doctor(&["--json"]);
assert!(json.contains("{\"id\":\"tripwires\",\"state\":\"present\",\"via\":\"plugin\"}"), "{json}");
assert!(json.contains("{\"id\":\"autorecall\",\"state\":\"absent\",\"via\":null}"), "{json}");
}
#[test]
fn claude_code_hooks_and_a_per_project_mcp_server_are_found() {
let m = Machine::new("claude-hooks");
m.put(
".claude/settings.json",
"{\"hooks\":{\"PreToolUse\":[{\"matcher\":\"Bash\",\"hooks\":[{\"type\":\"command\",\"command\":\"/opt/bin/instinct guard\"}]}],\"UserPromptSubmit\":[{\"hooks\":[{\"type\":\"command\",\"command\":\"instinct prompt\"}]}]}}",
);
m.put(".claude.json", "{\"projects\":{\"/work/app\":{\"mcpServers\":{\"instinct\":{\"command\":\"instinct\"}}}}}");
let (_, out, _) = m.doctor(&[]);
assert!(line_with(&out, "tripwires (instinct guard)").contains("on (hook)"), "{out}");
assert!(line_with(&out, "automatic lookup").contains("on (hook)"), "{out}");
assert!(line_with(&out, "MCP server").contains("on (mcp server)"), "{out}");
}
#[test]
fn codex_gemini_and_cursor_are_each_detected() {
let m = Machine::new("others");
m.put(
".codex/hooks.json",
"{\"hooks\":{\"PreToolUse\":[{\"matcher\":\"Bash\",\"hooks\":[{\"type\":\"command\",\"command\":\"instinct guard\"}]}],\"UserPromptSubmit\":[{\"hooks\":[{\"type\":\"command\",\"command\":\"instinct prompt\"}]}]}}",
);
m.put(".codex/config.toml", "model = \"x\"\n[mcp_servers.instinct]\ncommand = \"instinct\"\nargs = [\"mcp\"]\n");
m.dir(".agents/skills/instinct");
m.put(
".gemini/settings.json",
"{\"hooks\":{\"BeforeAgent\":[{\"hooks\":[{\"type\":\"command\",\"command\":\"instinct prompt\"}]}]},\"mcpServers\":{\"instinct\":{\"command\":\"instinct\"}}}",
);
m.put(".cursor/mcp.json", "{\"mcpServers\":{\"instinct\":{\"command\":\"instinct\",\"args\":[\"mcp\"]}}}");
let (code, out, _) = m.doctor(&[]);
assert_eq!(code, 0);
let section = |name: &str| -> String {
let at = out.find(name).unwrap_or_else(|| panic!("no {name} in {out}"));
out[at..].split("\n\n").next().unwrap().to_string()
};
let codex = section("Codex CLI (");
for l in ["tripwires", "automatic lookup", "MCP server", "skill folder"] {
assert!(line_with(&codex, l).contains("on"), "{codex}");
assert!(!line_with(&codex, l).contains("off"), "{codex}");
}
let gemini = section("Gemini CLI (");
assert!(line_with(&gemini, "automatic lookup").contains("on (hook)"), "{gemini}");
assert!(line_with(&gemini, "MCP server").contains("on (settings.json)"), "{gemini}");
let cursor = section("Cursor (");
assert!(line_with(&cursor, "MCP server").contains("on (mcp.json)"), "{cursor}");
assert!(out.contains("not found on this machine: Claude Code"), "{out}");
}
#[test]
fn guard_activity_after_a_real_guard_call_shows_up() {
let m = Machine::new("activity");
m.guard();
let (code, out, _) = m.doctor(&[]);
assert_eq!(code, 0);
assert!(line_with(&out, "guard ").contains("last ran just now"), "{out}");
assert!(line_with(&out, "prompt ").contains("never"), "{out}");
assert!(out.contains("lessons;") || out.contains("lesson;"), "{out}");
let (_, json, _) = m.doctor(&["--json"]);
assert!(json.contains("\"guard\":{\"last_unix\":1"), "{json}");
assert!(json.contains("\"prompt\":{\"last_unix\":null,\"seconds_ago\":null}"), "{json}");
}
#[test]
fn doctor_on_a_populated_machine_changes_nothing() {
let m = Machine::new("readonly");
m.guard();
m.put(".claude/settings.json", "{\"enabledPlugins\":{\"instinct@koscak-labs\":true}}");
let before = m.snapshot();
let _ = m.doctor(&[]);
let _ = m.doctor(&["--json"]);
assert_eq!(m.snapshot(), before);
}
#[test]
fn a_secret_in_any_config_never_appears_in_any_output() {
let m = Machine::new("secret");
let doc = format!(
"{{\"apiKey\":\"{SECRET}\",\"env\":{{\"TOKEN\":\"{SECRET}\"}},\"enabledPlugins\":{{\"instinct@koscak-labs\":true}},\"hooks\":{{\"PreToolUse\":[{{\"hooks\":[{{\"type\":\"command\",\"command\":\"instinct guard --key {SECRET}\"}}]}}]}},\"mcpServers\":{{\"instinct\":{{\"env\":{{\"K\":\"{SECRET}\"}}}},\"other\":{{\"env\":{{\"K\":\"{SECRET}\"}}}}}}}}"
);
m.put(".claude/settings.json", &doc);
m.put(".claude.json", &doc);
m.put(".codex/hooks.json", &doc);
m.put(".codex/config.toml", &format!("key = \"{SECRET}\"\n[mcp_servers.instinct.env]\nK = \"{SECRET}\"\n"));
m.put(".gemini/settings.json", &doc);
m.put(".cursor/mcp.json", &doc);
m.put(".codeium/windsurf/mcp_config.json", &doc);
m.put(".warp/.mcp.json", &doc);
for args in [&[][..], &["--json"][..]] {
let (code, out, err) = m.doctor(args);
assert_eq!(code, 0);
assert!(!out.contains("SECRET123") && !err.contains("SECRET123"), "secret leaked:\n{out}\n{err}");
assert!(out.contains("on"), "the entries should still be found: {out}");
}
for f in [".claude/settings.json", ".claude.json", ".codex/hooks.json", ".gemini/settings.json", ".cursor/mcp.json", ".codeium/windsurf/mcp_config.json", ".warp/.mcp.json"] {
m.put(f, &format!("{{\"apiKey\":\"{SECRET}\",,"));
}
for args in [&[][..], &["--json"][..]] {
let (code, out, err) = m.doctor(args);
assert_eq!(code, 0);
assert!(!out.contains("SECRET123") && !err.contains("SECRET123"), "secret leaked:\n{out}\n{err}");
}
}
#[test]
fn malformed_configs_report_unreadable_and_nothing_panics() {
let m = Machine::new("malformed");
m.put(".claude/settings.json", "{not json");
m.put(".claude.json", "[1,2,");
m.put(".codex/hooks.json", "");
m.put(".gemini/settings.json", "\u{1}garbage");
m.put(".cursor/mcp.json", "{\"mcpServers\":");
m.put(".codeium/windsurf/mcp_config.json", "{\"mcpServers\":");
m.put(".warp/.mcp.json", "{\"mcpServers\":");
let (code, out, err) = m.doctor(&[]);
assert_eq!(code, 0, "{err}");
assert!(!err.contains("panicked") && !out.contains("panicked"), "{err}");
for l in ["tripwires (instinct guard)", "MCP server"] {
assert!(out.lines().any(|x| x.contains(l) && x.contains("unreadable")), "{l}: {out}");
}
assert!(out.matches("unreadable (could not parse the config file)").count() >= 8, "{out}");
let (code, json, _) = m.doctor(&["--json"]);
assert_eq!(code, 0);
assert!(json.contains("\"state\":\"unreadable\""), "{json}");
assert!(!json.contains("\"state\":\"present\""), "{json}");
}
#[test]
fn the_json_schema_is_stable() {
let m = Machine::new("schema");
m.put(".claude/settings.json", "{}");
m.put(".codex/config.toml", "");
m.put(".gemini/settings.json", "{}");
m.put(".cursor/mcp.json", "{}");
let (code, json, _) = m.doctor(&["--json"]);
assert_eq!(code, 0);
assert_eq!(json.trim_end().lines().count(), 1, "one JSON document on one line");
let items = |n: usize| (0..n).flat_map(|_| ["id", "state", "via"]).map(String::from).collect::<Vec<_>>();
let harness = |n: usize| {
let mut v: Vec<String> = ["id", "name", "config_dir", "found", "items"].iter().map(|s| s.to_string()).collect();
v.extend(items(n));
v
};
let mut want: Vec<String> = [
"schema", "binary", "version", "path", "on_path", "path_binary", "path_binary_is_this", "bank", "path", "exists", "lessons", "readable",
"folder_writable", "activity", "prompt", "last_unix", "seconds_ago", "guard", "last_unix", "seconds_ago",
"harnesses",
]
.iter()
.map(|s| s.to_string())
.collect();
want.extend(harness(3)); want.extend(harness(4)); want.extend(harness(2)); want.extend(harness(1)); want.extend(harness(0)); want.extend(harness(0)); want.push("next_steps".into());
assert_eq!(keys(&json), want, "{json}");
assert!(json.starts_with("{\"schema\":1,"), "{json}");
assert!(json.contains(&format!("\"version\":\"{}\"", env!("CARGO_PKG_VERSION"))));
let mut at = 0;
for id in ["claude_code", "codex", "gemini_cli", "cursor", "windsurf", "warp"] {
let p = json[at..].find(&format!("{{\"id\":\"{id}\"")).unwrap_or_else(|| panic!("{id} out of order in {json}"));
at += p + 1;
}
}
fn doctor_with_path(m: &Machine, path_dirs: &[&Path], args: &[&str]) -> (i32, String) {
let joined = std::env::join_paths(path_dirs).unwrap();
let mut a = vec!["doctor"];
a.extend_from_slice(args);
let o = m.cmd(&a).env("PATH", joined).output().unwrap();
(o.status.code().unwrap_or(-1), String::from_utf8_lossy(&o.stdout).into_owned())
}
fn stub_dir(m: &Machine) -> PathBuf {
let d = m.root.join("stubbin");
std::fs::create_dir_all(&d).unwrap();
let name = if cfg!(windows) { "instinct.exe" } else { "instinct" };
let f = d.join(name);
std::fs::write(&f, "#!/bin/sh\necho instinct 0.0.1\n").unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&f, std::fs::Permissions::from_mode(0o755)).unwrap();
}
d
}
#[test]
fn a_different_instinct_first_on_path_is_called_out() {
let m = Machine::new("pathmismatch");
let d = stub_dir(&m);
let name = if cfg!(windows) { "instinct.exe" } else { "instinct" };
let canon = std::fs::canonicalize(d.join(name)).unwrap().display().to_string();
let stub = canon.strip_prefix(r"\\?\").map(str::to_string).unwrap_or(canon.clone());
let (code, out) = doctor_with_path(&m, &[&d], &[]);
assert_eq!(code, 0);
let l = line_with(&out, "binary ");
assert!(l.contains(&format!("your hooks run {stub} instead (first on PATH)")), "{out}");
assert!(!l.contains("found on PATH"), "{out}");
assert!(!out.contains(r"\\?\"), "no verbatim Windows prefix in the report: {out}");
assert!(out.contains(&format!("check the version your hooks run: {stub} --version, and update it if it is older")), "{out}");
let (_, json) = doctor_with_path(&m, &[&d], &["--json"]);
assert!(json.contains("\"on_path\":true"), "{json}");
assert!(json.contains(&format!("\"path_binary\":\"{}\"", stub.replace('\\', "\\\\"))), "{json}");
assert!(json.contains("\"path_binary_is_this\":false"), "{json}");
}
#[test]
fn path_set_to_the_binarys_own_dir_gives_no_mismatch() {
let m = Machine::new("pathsame");
let me = std::path::Path::new(env!("CARGO_BIN_EXE_instinct")).parent().unwrap().to_path_buf();
let (code, out) = doctor_with_path(&m, &[&me], &[]);
assert_eq!(code, 0);
assert!(line_with(&out, "binary ").contains("found on PATH"), "{out}");
assert!(!out.contains("your hooks run"), "{out}");
assert!(!out.contains("check the version your hooks run"), "{out}");
let (_, json) = doctor_with_path(&m, &[&me], &["--json"]);
assert!(json.contains("\"path_binary_is_this\":true"), "{json}");
}
#[test]
fn no_instinct_on_path_keeps_the_not_found_wording() {
let m = Machine::new("pathnone");
let empty = m.root.join("emptybin");
std::fs::create_dir_all(&empty).unwrap();
let (_, out) = doctor_with_path(&m, &[&empty], &[]);
assert!(line_with(&out, "binary ").contains("not found on PATH"), "{out}");
let (_, json) = doctor_with_path(&m, &[&empty], &["--json"]);
assert!(json.contains("\"on_path\":false,\"path_binary\":null,\"path_binary_is_this\":null"), "{json}");
}
#[test]
fn wiring_steps_come_first_and_starter_only_when_no_tripwire_hook_is_on() {
let m = Machine::new("order");
m.dir(".claude");
m.dir(".codex");
let (_, out, _) = m.doctor(&[]);
let at = |s: &str| out.find(s).unwrap_or_else(|| panic!("no {s} in {out}"));
assert!(at("claude plugin marketplace add") < at("codex mcp add"), "{out}");
assert!(at("codex mcp add") < at("or add the starter tripwires now without hooks: instinct starter --apply"), "{out}");
m.put(".claude/settings.json", "{\"enabledPlugins\":{\"instinct@koscak-labs\":true}}");
let (_, out, _) = m.doctor(&[]);
assert!(!out.contains("starter --apply"), "{out}");
let m2 = Machine::new("order2");
m2.guard();
let (_, out, _) = m2.doctor(&[]);
assert!(!out.contains("starter --apply"), "{out}");
}
#[test]
fn a_store_flag_points_doctor_at_another_bank() {
let m = Machine::new("store");
let bank = m.root.join("elsewhere").join("my.hxdb");
let (code, out, _) = m.doctor(&["--store", bank.to_str().unwrap()]);
assert_eq!(code, 0);
assert!(out.contains(bank.to_str().unwrap()), "{out}");
assert!(!m.root.join("elsewhere").exists(), "doctor must not create the folder");
}
#[test]
fn an_unknown_flag_is_a_usage_error_not_a_report() {
let m = Machine::new("badflag");
let (code, out, err) = m.doctor(&["--frobnicate"]);
assert_ne!(code, 0);
assert!(out.is_empty());
assert!(err.contains("usage: instinct doctor"), "{err}");
}
#[test]
fn windsurf_and_warp_mcp_entries_are_detected_read_only() {
let m = Machine::new("windsurf-warp");
let entry = "{\"mcpServers\":{\"instinct\":{\"command\":\"instinct\",\"args\":[\"mcp\"]}}}";
m.put(".codeium/windsurf/mcp_config.json", "{\"mcpServers\":{\"other\":{\"command\":\"x\"}}}");
m.put(".warp/.mcp.json", entry);
let (code, out, _) = m.doctor(&[]);
assert_eq!(code, 0);
let section = |out: &str, name: &str| -> String {
let at = out.find(name).unwrap_or_else(|| panic!("no {name} in {out}"));
out[at..].split("\n\n").next().unwrap().to_string()
};
assert!(line_with(§ion(&out, "Warp ("), "MCP server").contains("on (.mcp.json)"), "{out}");
assert!(line_with(§ion(&out, "Windsurf ("), "MCP server").contains("off"), "{out}");
assert!(out.contains("Windsurf MCP: add the mcpServers snippet"), "{out}");
m.put(".config/devin/mcp_config.json", entry);
let before = m.snapshot();
let (_, out, _) = m.doctor(&[]);
assert!(line_with(§ion(&out, "Windsurf ("), "MCP server").contains("on (mcp_config.json)"), "{out}");
assert_eq!(m.snapshot(), before);
}
fn uniq() -> usize {
static N: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
N.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
}
#[test]
fn a_bank_with_no_starter_tripwires_is_flagged_with_the_exact_command_for_that_bank() {
let m = Machine::new("nostarter");
let bank = m.root.join("mine").join("bank.hxdb");
std::fs::create_dir_all(bank.parent().unwrap()).unwrap();
let b = m
.cmd(&["bank", "--store", bank.to_str().unwrap(), "--title", "One lesson", "--when", "running the tests", "--found", "f", "--how", "h", "--evidence", "e"])
.output()
.unwrap();
assert!(b.status.success(), "{}", String::from_utf8_lossy(&b.stderr));
let (code, out, _) = m.doctor(&["--store", bank.to_str().unwrap()]);
assert_eq!(code, 0);
let want = format!("instinct starter --apply --store {}", bank.display());
assert!(line_with(&out, "starter ").contains("none of the starter tripwires"), "{out}");
assert!(out.contains(&want), "{out}");
assert!(out.matches(&want).count() >= 2, "also a next step: {out}");
let (_, json, _) = m.doctor(&["--store", bank.to_str().unwrap(), "--json"]);
assert!(json.contains("\"starter_none\":true"), "{json}");
let mut c = m.cmd(&["doctor"]);
c.env("INSTINCT_STORE", &bank);
let o = c.output().unwrap();
assert!(String::from_utf8_lossy(&o.stdout).contains(&want));
let a = m.cmd(&["starter", "--apply", "--store", bank.to_str().unwrap()]).output().unwrap();
assert!(a.status.success());
let (_, out, _) = m.doctor(&["--store", bank.to_str().unwrap()]);
assert!(!out.contains("starter --apply"), "{out}");
let m2 = Machine::new("nostarter-default");
let d = m2.cmd(&["bank", "--title", "One", "--when", "w", "--found", "f", "--how", "h", "--evidence", "e"]).output().unwrap();
assert!(d.status.success());
let (_, out, _) = m2.doctor(&[]);
assert!(out.contains("none of the starter tripwires"), "{out}");
assert!(out.contains("instinct starter --apply\n") && !out.contains("--store"), "{out}");
}
const CODEX_PLUGIN_TOML: &str = "[plugins.\"instinct@koscak-labs\"]\nenabled = true\n";
#[test]
fn codex_plugin_hooks_count_but_an_untrusted_hook_is_reported_as_not_working() {
let m = Machine::new("codex-trust");
m.put(".codex/config.toml", CODEX_PLUGIN_TOML);
let (code, out, _) = m.doctor(&[]);
assert_eq!(code, 0);
let codex = &out[out.find("Codex CLI (").expect("codex section")..];
assert!(line_with(codex, "tripwires").contains("on"), "{codex}");
assert!(line_with(codex, "trusted by Codex").contains("off"), "{codex}");
assert!(out.contains("Codex skips hooks it has not trusted"), "{out}");
m.put(
".codex/config.toml",
&format!("{CODEX_PLUGIN_TOML}\n[hooks.state.\"instinct@koscak-labs:hooks/hooks.json:pre_tool_use:0:0\"]\ntrusted_hash = \"sha256:aa\"\n"),
);
let (_, out, _) = m.doctor(&[]);
let codex = &out[out.find("Codex CLI (").unwrap()..];
assert!(line_with(codex, "trusted by Codex").contains("on"), "{codex}");
assert!(!out.contains("Codex skips hooks it has not trusted"), "{out}");
}
#[cfg(unix)]
#[test]
fn codex_trust_trusts_only_instinct_hooks_and_verifies() {
use std::os::unix::fs::PermissionsExt;
let m = Machine::new("codex-trust-cmd");
let bin = m.root.join("bin");
std::fs::create_dir_all(&bin).unwrap();
let marker = m.root.join("written");
let log = m.root.join("writes.log");
let script = format!(
r#"#!/bin/sh
while read -r line; do
case "$line" in
*'"initialize"'*) echo '{{"id":1,"result":{{}}}}' ;;
*'"hooks/list"'*)
id=$(echo "$line" | sed 's/.*"id":\([0-9]*\).*/\1/')
if [ -f "{marker}" ]; then st=trusted; else st=untrusted; fi
echo '{{"id":'$id',"result":{{"data":[{{"cwd":"/","hooks":[{{"key":"instinct@koscak-labs:hooks/hooks.json:pre_tool_use:0:0","eventName":"preToolUse","command":"instinct guard","currentHash":"sha256:aaa/sha256:bbb","trustStatus":"'$st'"}},{{"key":"other:hooks.json:pre_tool_use:0:0","eventName":"preToolUse","command":"rm -rf /","currentHash":"sha256:ccc","trustStatus":"untrusted"}}]}}]}}}}' ;;
*'"config/batchWrite"'*) echo "$line" >> "{log}"; touch "{marker}"; echo '{{"id":3,"result":{{"status":"ok"}}}}' ;;
esac
done
"#,
marker = marker.display(),
log = log.display()
);
let path = bin.join("codex");
std::fs::write(&path, script).unwrap();
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
let sys = std::env::var("PATH").unwrap_or_default();
let run = |args: &[&str]| {
let o = m.cmd(&["codex-trust"]).args(args).env("PATH", format!("{}:{sys}", bin.display())).output().unwrap();
(o.status.code().unwrap(), String::from_utf8_lossy(&o.stdout).into_owned())
};
let (code, out) = run(&["--check"]);
assert_eq!(code, 0);
assert!(out.contains("untrusted") && !out.contains("rm -rf"), "{out}");
assert!(!marker.exists(), "--check must write nothing");
let (code, out) = run(&[]);
assert_eq!(code, 0, "{out}");
assert!(out.contains("trusted") && !out.contains("untrusted"), "{out}");
let written = std::fs::read_to_string(&log).unwrap();
assert!(written.contains("\"trusted_hash\":\"sha256:aaa\""), "{written}");
assert!(!written.contains("bbb") && !written.contains("ccc") && !written.contains("other:"), "{written}");
}