use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::{Duration, SystemTime};
fn sandbox(name: &str) -> PathBuf {
static N: AtomicUsize = AtomicUsize::new(0);
let d = std::env::temp_dir().join(format!("instinct-scan-test-{}-{}-{name}", std::process::id(), N.fetch_add(1, Ordering::Relaxed)));
let _ = fs::remove_dir_all(&d);
fs::create_dir_all(&d).unwrap();
d
}
fn scan(home: &Path, args: &[&str]) -> (i32, String, String) {
let o = Command::new(env!("CARGO_BIN_EXE_instinct"))
.env("HOME", home)
.env("USERPROFILE", home)
.env("LOCALAPPDATA", home.join(".local").join("share"))
.env_remove("XDG_DATA_HOME")
.env_remove("INSTINCT_STORE")
.env_remove("CLAUDE_CONFIG_DIR")
.env_remove("CODEX_HOME")
.arg("scan")
.args(args)
.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 age(path: &Path, days: u64) {
let t = SystemTime::now() - Duration::from_secs(days * 86_400);
fs::OpenOptions::new().write(true).open(path).unwrap().set_modified(t).unwrap();
}
fn write(path: &Path, text: &str) {
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(path, text).unwrap();
}
fn cu(text: &str) -> String {
format!("{{\"type\":\"user\",\"message\":{{\"role\":\"user\",\"content\":\"{text}\"}}}}\n")
}
fn cbash(id: &str, cmd: &str) -> String {
let cmd = cmd.replace('\\', "\\\\").replace('"', "\\\"");
format!("{{\"type\":\"assistant\",\"message\":{{\"role\":\"assistant\",\"content\":[{{\"type\":\"tool_use\",\"id\":\"{id}\",\"name\":\"Bash\",\"input\":{{\"command\":\"{cmd}\"}}}}]}}}}\n")
}
fn cread(id: &str) -> String {
format!("{{\"type\":\"assistant\",\"message\":{{\"role\":\"assistant\",\"content\":[{{\"type\":\"tool_use\",\"id\":\"{id}\",\"name\":\"Read\",\"input\":{{\"file_path\":\"git push --force\"}}}}]}}}}\n")
}
fn cresult(id: &str) -> String {
format!("{{\"type\":\"user\",\"message\":{{\"role\":\"user\",\"content\":[{{\"type\":\"tool_result\",\"tool_use_id\":\"{id}\",\"content\":\"ok\"}}]}}}}\n")
}
fn ctext(text: &str) -> String {
format!("{{\"type\":\"assistant\",\"message\":{{\"role\":\"assistant\",\"content\":[{{\"type\":\"text\",\"text\":\"{text}\"}}]}}}}\n")
}
fn xmeta() -> String {
"{\"type\":\"session_meta\",\"payload\":{\"id\":\"sess-1\"}}\n".to_string()
}
fn xu(text: &str) -> String {
format!("{{\"type\":\"response_item\",\"payload\":{{\"type\":\"message\",\"role\":\"user\",\"content\":[{{\"type\":\"input_text\",\"text\":\"{text}\"}}]}}}}\n")
}
fn xcmd(id: &str, cmd: &str) -> String {
let inner = cmd.replace('\\', "\\\\").replace('"', "\\\"");
let args_json = format!("{{\"command\":[\"bash\",\"-lc\",\"{inner}\"]}}");
let args = args_json.replace('\\', "\\\\").replace('"', "\\\"");
format!("{{\"type\":\"response_item\",\"payload\":{{\"type\":\"function_call\",\"name\":\"shell\",\"call_id\":\"{id}\",\"arguments\":\"{args}\"}}}}\n")
}
fn xout(id: &str) -> String {
format!("{{\"type\":\"response_item\",\"payload\":{{\"type\":\"function_call_output\",\"call_id\":\"{id}\",\"output\":\"ok\"}}}}\n")
}
fn xa(text: &str) -> String {
format!("{{\"type\":\"response_item\",\"payload\":{{\"type\":\"message\",\"role\":\"assistant\",\"content\":[{{\"type\":\"output_text\",\"text\":\"{text}\"}}]}}}}\n")
}
fn claude_session() -> String {
[
cu("ZEBRAMARKER build the thing"),
cbash("a", "git push --force origin main"),
cresult("a"),
ctext("QUOKKAMARKER pushed"),
cu("no, use pnpm not npm"),
cbash("b", "rm -rf $BUILD/*"),
cresult("b"),
cread("r"),
cresult("r"),
cu("no, that's wrong, you broke the build"),
cbash("c", "ls -la"),
cresult("c"),
cu("thanks, looks good"),
ctext("done"),
cu("now add tests"),
]
.concat()
}
fn codex_session() -> String {
[
xmeta(),
xu("run the migration"),
xcmd("x1", "psql -c \"DROP TABLE users\""),
xout("x1"),
xa("done"),
xu("no, that's wrong, you broke it"),
xcmd("x2", "echo hi"),
xout("x2"),
]
.concat()
}
fn fixture_home(name: &str) -> PathBuf {
let home = sandbox(name);
write(&home.join(".claude/projects/p1/s1.jsonl"), &claude_session());
write(&home.join(".codex/sessions/2026/12/01/rollout-1.jsonl"), &codex_session());
home
}
fn tree(dir: &Path, out: &mut Vec<String>) {
let mut es: Vec<_> = fs::read_dir(dir).map(|r| r.flatten().map(|e| e.path()).collect()).unwrap_or_default();
es.sort();
for p in es {
let m = fs::metadata(&p).unwrap();
out.push(format!("{} {} {:?}", p.display(), m.len(), m.modified().unwrap()));
if p.is_dir() {
tree(&p, out);
}
}
}
#[test]
fn counts_are_deterministic_on_both_formats() {
let home = fixture_home("counts");
let (code, out, err) = scan(&home, &["--json"]);
assert_eq!(code, 0, "{err}");
assert!(out.contains("\"files\":{\"scanned\":2,\"claude_code\":1,\"codex\":1,\"skipped_old\":0,\"unreadable\":0}"), "{out}");
assert!(out.contains("\"prompts\":7,\"commands\":5,"), "{out}");
assert!(out.contains("\"risky\":{\"flagged\":3,"), "{out}");
assert!(out.contains("\"title\":\"git push --force overwrites commits other people pushed\",\"count\":1"), "{out}");
assert!(out.contains("\"corrections\":{\"count\":3,"), "{out}");
assert!(out.contains("\"after_correction\":{\"replies\":2,\"repeated\":1,\"rate\":0.5000}"), "{out}");
assert!(out.contains("\"after_other\":{\"replies\":3,\"repeated\":2,\"rate\":0.6667}"), "{out}");
assert!(out.contains("\"ratio\":null"), "fewer than 20 pairs: no ratio: {out}");
let (_, again, _) = scan(&home, &["--json"]);
let strip = |s: &str| s.split("\"elapsed_ms\"").next().unwrap().to_string();
assert_eq!(strip(&out), strip(&again));
assert!(out.contains("\"count\":1,\"examples\":[\"git push --force origin main\"]"), "{out}");
}
#[test]
fn text_report_has_the_four_sections_and_a_footer() {
let home = fixture_home("text");
fs::write(home.join(".claude/CLAUDE.md"), "x".repeat(400)).unwrap();
let (code, out, _) = scan(&home, &[]);
assert_eq!(code, 0);
for h in ["1. Risky commands: 3 of 5", "2. Corrections: 3 of 7 prompts", "3. Memory files", "4. Next steps"] {
assert!(out.contains(h), "missing {h:?} in\n{out}");
}
assert!(out.contains("CLAUDE.md (user level): about 100 tokens on every prompt"), "{out}");
assert!(out.contains("about 500 tokens"), "{out}");
assert!(out.contains("No ratio yet"), "{out}");
assert!(out.contains("instinct starter --apply"), "{out}");
assert!(out.contains("Scanned in ") && out.contains(" s. Nothing was written or uploaded."), "{out}");
}
#[test]
fn ratio_prints_when_both_groups_have_twenty() {
let home = sandbox("ratio");
let mut s = String::new();
for _ in 0..25 {
s.push_str(&cu("no, that's wrong"));
s.push_str(&ctext("ok"));
s.push_str(&cu("fine, carry on"));
s.push_str(&ctext("ok"));
}
for _ in 0..25 {
s.push_str(&cu("no, that's wrong"));
s.push_str(&ctext("ok"));
s.push_str(&cu("no, that's wrong again, you broke it"));
s.push_str(&ctext("ok"));
}
write(&home.join(".claude/projects/p/s.jsonl"), &s);
let (_, out, _) = scan(&home, &["--json"]);
assert!(out.contains("\"ratio\":"), "{out}");
assert!(!out.contains("\"ratio\":null"), "{out}");
let (_, text, _) = scan(&home, &[]);
assert!(text.contains("Ratio: ") && text.contains("x more likely"), "{text}");
}
#[test]
fn secrets_are_redacted_and_snippets_are_60_chars() {
let home = sandbox("redact");
let long = format!("git push --force origin {}", "feature/x".repeat(20));
let s = [
cu("go"),
cbash("a", "git push --force https://user:hunter2pass@example.test/r.git"),
cbash("b", "API_KEY=abc deploy.sh && git push --force origin main"),
cbash("c", "git push --force origin 3f2a9c1d4b5e6f708192a3b4c5d6e7f801234567"),
cbash("d", &long),
cbash("e", "GITHUB_TOKEN=ghp_abcdefghijklmnopqrstuvwxyz0123456789 git push --force"),
cbash("f", "git push --force sk-abcdefghijklmnopqrstuvwxyz1234"),
]
.concat();
write(&home.join(".claude/projects/p/s.jsonl"), &s);
let (_, out, _) = scan(&home, &["--json"]);
for secret in ["hunter2pass", "abc deploy", "API_KEY=abc", "3f2a9c1d", "ghp_", "sk-abc", "abcdefghijklmnop"] {
assert!(!out.contains(secret), "{secret} leaked:\n{out}");
}
assert!(out.contains("***"), "{out}");
let (_, text, _) = scan(&home, &[]);
assert!(!text.contains("ghp_") && !text.contains("hunter2pass"), "{text}");
let ex = out.split("\"examples\":[").nth(1).unwrap().split(']').next().unwrap();
let items: Vec<&str> = ex.split("\",\"").collect();
assert!(items.len() <= 3, "{ex}");
for i in items {
assert!(i.trim_matches('"').chars().count() <= 60, "{i}");
}
}
#[test]
fn no_prompt_or_reply_text_is_ever_printed() {
let home = fixture_home("privacy");
for args in [&[][..], &["--json"][..], &["--share"][..]] {
let (_, out, err) = scan(&home, args);
for marker in ["ZEBRAMARKER", "QUOKKAMARKER", "build the thing", "use pnpm", "run the migration"] {
assert!(!out.contains(marker) && !err.contains(marker), "{marker} printed with {args:?}:\n{out}");
}
}
}
#[test]
fn files_older_than_the_window_are_skipped() {
let home = fixture_home("window");
let old = home.join(".claude/projects/p2/old.jsonl");
write(&old, &[cu("go"), cbash("o", "git push --force origin main"), cbash("o2", "git reset --hard")].concat());
age(&old, 40);
let (_, out, _) = scan(&home, &["--json"]);
assert!(out.contains("\"scanned\":2,") && out.contains("\"skipped_old\":1,"), "{out}");
assert!(out.contains("\"commands\":5,"), "old file not counted: {out}");
let (_, wide, _) = scan(&home, &["--days", "60", "--json"]);
assert!(wide.contains("\"scanned\":3,") && wide.contains("\"skipped_old\":0,"), "{wide}");
assert!(wide.contains("\"commands\":7,"), "{wide}");
let (_, narrow, _) = scan(&home, &["--days", "30", "--json"]);
assert!(narrow.contains("\"days\":30"), "default is 30: {narrow}");
}
#[test]
fn missing_and_empty_folders_are_friendly_and_exit_zero() {
let none = sandbox("missing");
let (code, out, err) = scan(&none, &[]);
assert_eq!(code, 0, "{err}");
assert!(out.contains("No Claude Code or Codex transcripts"), "{out}");
assert!(out.contains("Nothing was written or uploaded"), "{out}");
let empty = sandbox("empty");
fs::create_dir_all(empty.join(".claude/projects/p")).unwrap();
fs::create_dir_all(empty.join(".codex/sessions")).unwrap();
write(&empty.join(".claude/projects/p/blank.jsonl"), "");
write(&empty.join(".claude/projects/p/junk.jsonl"), "not json\n{\"x\":1}\n");
let (code, out, _) = scan(&empty, &[]);
assert_eq!(code, 0);
assert!(out.contains("prompts, 0 shell commands"), "{out}");
for args in [&["--json"][..], &["--share"][..]] {
let (code, out, _) = scan(&none, args);
assert_eq!(code, 0);
assert!(!out.trim().is_empty());
}
}
#[test]
fn share_is_one_plain_block_of_at_most_280_chars() {
let home = fixture_home("share");
let (code, out, _) = scan(&home, &["--share"]);
assert_eq!(code, 0);
let t = out.trim_end();
assert!(t.chars().count() <= 280, "{} chars: {t}", t.chars().count());
assert!(t.contains("https://github.com/koscak-labs/instinct"), "{t}");
assert!(t.contains("3 of 5"), "{t}");
assert!(!t.contains('\n') && !t.contains('\u{2014}'), "{t}");
let (_, empty, _) = scan(&sandbox("share-empty"), &["--share"]);
assert!(empty.trim_end().chars().count() <= 280);
}
#[test]
fn it_writes_nothing() {
let home = fixture_home("readonly");
fs::write(home.join(".claude/CLAUDE.md"), "rules").unwrap();
let (mut before, mut after) = (Vec::new(), Vec::new());
tree(&home, &mut before);
scan(&home, &[]);
scan(&home, &["--json"]);
scan(&home, &["--share"]);
tree(&home, &mut after);
assert_eq!(before, after);
assert!(!home.join(".local").exists());
}
#[test]
fn bad_arguments_fail_with_a_message() {
let home = sandbox("args");
let (code, _, err) = scan(&home, &["--days", "0"]);
assert_ne!(code, 0);
assert!(err.contains("--days"), "{err}");
let (code, _, err) = scan(&home, &["--nope"]);
assert_ne!(code, 0);
assert!(err.contains("unknown argument"), "{err}");
let (code, out, _) = scan(&home, &["--help"]);
assert_eq!(code, 0);
assert!(out.contains("usage: instinct scan"));
}
fn jesc(s: &str) -> String {
let mut out = String::new();
for c in s.chars() {
match c {
'\\' => out.push_str("\\\\"),
'"' => out.push_str("\\\""),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
c => out.push(c),
}
}
out
}
fn cuc(text: &str, cwd: &Path) -> String {
let cwd = jesc(&cwd.display().to_string());
format!("{{\"type\":\"user\",\"cwd\":\"{cwd}\",\"message\":{{\"role\":\"user\",\"content\":\"{text}\"}}}}\n")
}
fn pairs_session(correction_pairs: usize, other_pairs: usize) -> String {
let mut s = String::new();
for _ in 0..correction_pairs {
s.push_str(&cu("no, that's wrong"));
s.push_str(&ctext("ok"));
s.push_str(&cu("fine, carry on"));
s.push_str(&ctext("ok"));
}
for _ in 0..other_pairs {
s.push_str(&cu("carry on"));
s.push_str(&ctext("ok"));
s.push_str(&cu("and then"));
s.push_str(&ctext("ok"));
}
s
}
#[test]
fn share_leaves_the_percentages_out_below_twenty_pairs() {
let home = fixture_home("share-small");
let (_, share, _) = scan(&home, &["--share"]);
assert!(!share.contains('%') && !share.contains(" vs "), "{share}");
assert!(share.contains("I corrected it 3 times"), "{share}");
let (_, json, _) = scan(&home, &["--json"]);
assert!(json.contains("\"ratio\":null"), "{json}");
assert!(!json.contains("\"share\":\"") || !json.split("\"share\":\"").nth(1).unwrap().contains(" vs "), "{json}");
let home = sandbox("share-10");
write(&home.join(".claude/projects/p/s.jsonl"), &pairs_session(10, 40));
let (_, share, _) = scan(&home, &["--share"]);
assert!(!share.contains('%') && !share.contains(" vs "), "{share}");
let home = sandbox("share-30");
write(&home.join(".claude/projects/p/s.jsonl"), &pairs_session(30, 30));
let (_, share, _) = scan(&home, &["--share"]);
assert!(!share.contains('%') && !share.contains(" vs "), "{share}");
assert!(share.chars().count() <= 280, "{share}");
let (_, report, _) = scan(&home, &[]);
assert!(report.contains("Ratio:") && report.contains("a floor"), "{report}");
}
#[test]
fn project_memory_files_are_counted_per_project() {
let home = sandbox("projects");
fs::create_dir_all(home.join(".claude")).unwrap();
fs::write(home.join(".claude/CLAUDE.md"), "u".repeat(400)).unwrap(); fs::write(home.join("CLAUDE.md"), "h".repeat(40)).unwrap(); for i in 1..=7u32 {
let dir = home.join(format!("proj{i}"));
fs::create_dir_all(&dir).unwrap();
fs::write(dir.join("CLAUDE.md"), "m".repeat(40 * i as usize)).unwrap();
write(&home.join(format!(".claude/projects/p{i}/s.jsonl")), &[cuc("hello", &dir), ctext("hi")].concat());
}
fs::write(home.join("proj7/AGENTS.md"), "a".repeat(400)).unwrap();
let cx = [
format!("{{\"type\":\"session_meta\",\"payload\":{{\"id\":\"s\",\"cwd\":\"{}\"}}}}\n", jesc(&home.join("proj7").display().to_string())),
xu("one"),
xa("ok"),
xu("two"),
]
.concat();
write(&home.join(".codex/sessions/2026/12/01/r.jsonl"), &cx);
write(&home.join(".claude/projects/gone/s.jsonl"), &[cuc("hello", &home.join("deleted-project")), ctext("hi")].concat());
write(&home.join(".claude/projects/home/s.jsonl"), &[cuc("hello", &home), ctext("hi")].concat());
let (code, out, err) = scan(&home, &["--json"]);
assert_eq!(code, 0, "{err}");
assert!(out.contains("\"user_tokens_in_window\":990,"), "{out}");
assert!(out.contains("\"projects_with_memory\":7,"), "{out}");
assert!(out.contains("\"tokens_in_window\":1470}"), "overall = 990 + 210 + 270: {out}");
let top = out.split("\"top_projects\":[").nth(1).unwrap().split("],\"tokens_in_window\"").next().unwrap();
let paths: Vec<&str> = top.split("\"path\":\"").skip(1).map(|p| p.split('"').next().unwrap()).collect();
assert_eq!(paths, ["~/proj7", "~/proj6", "~/proj5", "~/proj4", "~/proj3"], "{top}");
assert!(!out.contains(&home.display().to_string()) && !out.contains(&jesc(&home.display().to_string())), "full path leaked: {out}");
let (_, text, _) = scan(&home, &[]);
assert!(text.contains("top 5 of 7 projects"), "{text}");
assert!(text.contains("~/proj7 (3 prompts)") && !text.contains("~/proj2"), "{text}");
assert!(text.contains("Overall: about 1,470 tokens"), "{text}");
assert!(!text.contains(&home.display().to_string()), "full path leaked: {text}");
}
#[test]
fn one_and_two_read_as_words_not_1_times() {
let home = sandbox("singular");
fs::write(home.join(".claude/CLAUDE.md"), "").ok();
fs::create_dir_all(home.join(".claude")).unwrap();
fs::write(home.join(".claude/CLAUDE.md"), "rule").unwrap(); let proj = home.join("proj");
fs::create_dir_all(&proj).unwrap();
fs::write(proj.join("CLAUDE.md"), "rule").unwrap(); write(
&home.join(".claude/projects/p/s.jsonl"),
&[cuc("no, that's wrong", &proj), cbash("a", "git push --force origin main")].concat(),
);
let old = home.join(".claude/projects/p/old.jsonl");
write(&old, &cu("hello"));
age(&old, 40);
let (_, text, _) = scan(&home, &["--days", "1"]);
for want in [
"the last day (read-only",
"Read 1 transcript (1 Claude Code, 0 Codex): 1 prompt, 1 shell command.",
"1. Risky commands: 1 of 1 would have drawn",
"2. Corrections: 1 of 1 prompt told the agent",
"CLAUDE.md (user level): about 1 token on every prompt",
"across 1 prompt (1 Claude Code, 0 Codex): about 1 token.",
"top 1 of 1 project ",
"(1 prompt)",
"Overall: about 2 tokens",
"(1 file skipped as older than the window, 0 unreadable)",
] {
assert!(text.contains(want), "missing {want:?} in\n{text}");
}
let (_, share, _) = scan(&home, &["--days", "1", "--share"]);
assert!(share.starts_with("My coding agent, last day: 1 of 1 shell command would have drawn"), "{share}");
assert!(share.contains("I corrected it once."), "{share}");
for s in [&text, &share] {
for bad in ["1 times", "1 prompts", "1 transcripts", "1 shell commands", "1 tokens", "1 projects", "1 files", "1 days", "2 times"] {
assert!(!s.contains(bad), "{bad:?} in {s}");
}
}
write(&home.join(".claude/projects/p/s.jsonl"), &[cu("no, that's wrong"), ctext("a"), cu("no, that's wrong")].concat());
let (_, two, _) = scan(&home, &["--share"]);
assert!(two.contains("I corrected it twice"), "{two}");
write(&home.join(".claude/projects/p/s.jsonl"), &[cu("no, that's wrong"), ctext("a"), cu("no, that's wrong"), ctext("b"), cu("no, that's wrong")].concat());
let (_, three, _) = scan(&home, &["--share"]);
assert!(three.contains("I corrected it 3 times"), "{three}");
}
fn json_scan(home: &Path) -> String {
scan(home, &["--json"]).1
}
fn cu_with(extra: &str, text: &str) -> String {
format!("{{\"type\":\"user\",{extra}\"message\":{{\"role\":\"user\",\"content\":\"{text}\"}}}}\n")
}
#[test]
fn words_inside_pasted_blocks_are_not_corrections() {
let home = sandbox("pasted");
write(
&home.join(".claude/projects/p/s.jsonl"),
&[
cu("please review <pasted_content id=\\\"1\\\">no, that's wrong, you broke it, stop doing that</pasted_content> thanks"),
ctext("ok"),
cu("<system-reminder>no, that's wrong</system-reminder>look at this <local-command-stdout>you broke it</local-command-stdout>"),
ctext("ok"),
cu("<pasted_content>no, that's wrong"), ]
.concat(),
);
let out = json_scan(&home);
assert!(out.contains("\"prompts\":2,"), "{out}");
assert!(out.contains("\"corrections\":{\"count\":0,"), "{out}");
write(&home.join(".claude/projects/p/s.jsonl"), &[cu("no, that's wrong, you broke it, stop doing that"), ctext("ok")].concat());
assert!(json_scan(&home).contains("\"corrections\":{\"count\":1,"));
write(&home.join(".claude/projects/p/s.jsonl"), &[cu("<system-reminder>context</system-reminder>\\nno, that's wrong"), ctext("ok")].concat());
let out = json_scan(&home);
assert!(out.contains("\"prompts\":1,") && out.contains("\"corrections\":{\"count\":1,"), "{out}");
}
#[test]
fn a_notification_between_two_typed_messages_does_not_break_the_pair() {
let home = sandbox("notification");
write(
&home.join(".claude/projects/p/s.jsonl"),
&[
cu("no, that's wrong"),
ctext("ok"),
cu("<task-notification>Task done: no, that's wrong</task-notification>"),
cu("<cross-session-message>no, that's wrong</cross-session-message>"),
cu_with("", "<command-name>/clear</command-name><command-message>clear</command-message>"),
cu_with("\"toolUseResult\":{\"stdout\":\"x\"},", "no, that's wrong from a tool"),
ctext("still working"),
cu("no, that's wrong again"),
ctext("ok"),
cu("fine"),
]
.concat(),
);
let out = json_scan(&home);
assert!(out.contains("\"prompts\":3,"), "{out}");
assert!(out.contains("\"corrections\":{\"count\":2,"), "{out}");
assert!(out.contains("\"after_correction\":{\"replies\":2,\"repeated\":1,"), "{out}");
}
#[test]
fn subagent_and_meta_prompts_are_ignored_but_subagent_commands_count() {
let home = sandbox("sidechain");
write(
&home.join(".claude/projects/p/s.jsonl"),
&[
cu("start"),
cu_with("\"isSidechain\":true,", "no, that's wrong"),
format!("{{\"type\":\"assistant\",\"isSidechain\":true,\"message\":{{\"role\":\"assistant\",\"content\":[{{\"type\":\"tool_use\",\"id\":\"s\",\"name\":\"Bash\",\"input\":{{\"command\":\"git push --force origin main\"}}}}]}}}}\n"),
cu_with("\"isMeta\":true,", "no, that's wrong"),
cbash("m", "ls"),
]
.concat(),
);
let out = json_scan(&home);
assert!(out.contains("\"prompts\":1,\"commands\":2,"), "{out}");
assert!(out.contains("\"flagged\":1,"), "{out}");
assert!(out.contains("\"corrections\":{\"count\":0,"), "{out}");
}
#[test]
fn codex_context_blocks_and_tool_output_are_not_typed() {
let home = sandbox("codex-typed");
write(
&home.join(".codex/sessions/2026/12/01/r.jsonl"),
&[
xmeta(),
xu("<environment_context>no, that's wrong</environment_context>"),
xu("fix the build <user_instructions>no, that's wrong, you broke it</user_instructions>"),
xcmd("x1", "echo hi"),
xout("x1"),
xa("done"),
xu("no, that's wrong"),
]
.concat(),
);
let out = json_scan(&home);
assert!(out.contains("\"prompts\":2,"), "{out}");
assert!(out.contains("\"corrections\":{\"count\":1,"), "{out}");
assert!(out.contains("\"after_other\":{\"replies\":1,\"repeated\":1,"), "{out}");
}
#[test]
fn zero_shell_commands_drop_the_tripwire_clause() {
let home = sandbox("no-commands");
write(&home.join(".claude/projects/p/s.jsonl"), &[cu("hello"), ctext("hi"), cu("no, that's wrong"), ctext("ok")].concat());
let (_, share, _) = scan(&home, &["--share"]);
assert!(!share.contains("shell commands") && !share.contains("tripwire") && !share.contains("0 of 0"), "{share}");
assert!(share.contains("I corrected it once") && share.contains("https://github.com/koscak-labs/instinct"), "{share}");
let (_, text, _) = scan(&home, &[]);
assert!(text.contains("1. Risky commands: No shell commands in the window.\n"), "{text}");
assert!(!text.contains("0 of 0") && !text.contains("None matched"), "{text}");
let (_, with, _) = scan(&fixture_home("with-commands"), &["--share"]);
assert!(with.contains("3 of 5 shell commands would have drawn an Instinct tripwire warning"), "{with}");
}
#[test]
fn credentials_in_urls_and_flags_are_redacted_end_to_end() {
let home = sandbox("creds");
let s = [
cu("go"),
cbash("a", "git push --force https://alice:s3cr3tpw@github.com/o/r.git"),
cbash("b", "mysql -psupersecret -h db && git push --force"),
cbash("c", "git push --force --password=topsecret1"),
cbash("d", "PGPASSWORD=pgsecret1 psql -c 'DROP TABLE users'"),
]
.concat();
write(&home.join(".claude/projects/p/s.jsonl"), &s);
let (_, out, _) = scan(&home, &["--json"]);
for secret in ["s3cr3tpw", "alice:", "supersecret", "topsecret1", "pgsecret1"] {
assert!(!out.contains(secret), "{secret} leaked:\n{out}");
}
for shown in ["https://***@github.com", "mysql -p*** -h db", "--password=***", "PGPASSWORD=*** psql"] {
assert!(out.contains(shown), "{shown} missing:\n{out}");
}
}
#[test]
fn replay_counts_rewrites_and_warnings_in_process() {
let home = sandbox("replay");
let mut s = cu("go");
s += &cbash("a", "S=/tmp/x; rm -rf $S/h1; echo ok");
s += &cbash("b", "S=/tmp/x; rm -rf $S/h1; echo ok");
s += &cbash("c", "rm -rf $X/");
s += &cbash("d", "ls -la");
write(&home.join(".claude/projects/p/s.jsonl"), &s);
let (code, out, err) = scan(&home, &["--format", "json"]);
assert_eq!(code, 0, "{err}");
assert!(out.contains("\"commands\":4,"), "{out}");
assert!(out.contains("\"replay\":{\"unique\":3,\"rewritten\":{\"unique\":2,\"runs\":3,"), "{out}");
assert!(out.contains("{\"rule\":\"guard-var\",\"runs\":3}"), "{out}");
assert!(out.contains("\"warned\":{\"unique\":2,\"runs\":3,\"by_title\":[{\"title\":\"rm -rf on a shell variable that may be empty or unset\",\"runs\":3}]"), "{out}");
assert!(out.contains("\"before\":\"S=/tmp/x; rm -rf $S/h1; echo ok\",\"after\":\"S=/tmp/x; rm -rf \\\"${S:?}\\\"/h1; echo ok\""), "{out}");
let (_, text, _) = scan(&home, &[]);
assert!(text.contains("Safe rewrites: instinct fix would have changed 2 of 3 distinct commands"), "{text}");
assert!(text.contains("rule guard-var"), "{text}");
let (code, bad, _) = scan(&home, &["--format", "yaml"]);
assert_ne!(code, 0, "{bad}");
}
fn jq(s: &str) -> String {
s.replace('\\', "\\\\").replace('"', "\\\"")
}
fn tbash(ts: &str, id: &str, cmd: &str, background: bool) -> String {
let bg = if background { ",\"run_in_background\":true" } else { "" };
format!("{{\"type\":\"assistant\",\"timestamp\":\"{ts}\",\"message\":{{\"role\":\"assistant\",\"content\":[{{\"type\":\"tool_use\",\"id\":\"{id}\",\"name\":\"Bash\",\"input\":{{\"command\":\"{}\"{bg}}}}}]}}}}\n", jq(cmd))
}
fn tresult(ts: &str, id: &str, text: &str) -> String {
format!("{{\"type\":\"user\",\"timestamp\":\"{ts}\",\"toolUseResult\":{{\"stdout\":\"\"}},\"message\":{{\"role\":\"user\",\"content\":[{{\"type\":\"tool_result\",\"tool_use_id\":\"{id}\",\"content\":\"{}\"}}]}}}}\n", jq(text))
}
fn tnotice(ts: &str, id: &str, status: &str) -> String {
let c = format!("<task-notification>\n<task-id>b1</task-id>\n<tool-use-id>{id}</tool-use-id>\n<status>{status}</status>\n</task-notification>");
format!("{{\"type\":\"queue-operation\",\"operation\":\"enqueue\",\"timestamp\":\"{ts}\",\"content\":\"{}\"}}\n", jq(&c).replace('\n', "\\n"))
}
fn xtcmd(ts: &str, id: &str, cmd: &str) -> String {
xcmd(id, cmd).replacen("{\"type\"", &format!("{{\"timestamp\":\"{ts}\",\"type\""), 1)
}
fn xtout(ts: &str, id: &str) -> String {
xout(id).replacen("{\"type\"", &format!("{{\"timestamp\":\"{ts}\",\"type\""), 1)
}
fn waiting_home(name: &str) -> PathBuf {
let home = sandbox(name);
let mut c = String::new();
c.push_str(&cu("wait for the job"));
c.push_str(&tbash("2026-11-30T10:00:00.000Z", "a1", "until ! pgrep -f sales_report; do sleep 30; done", false));
c.push_str(&tresult("2026-11-30T10:10:00.000Z", "a1", "ok"));
c.push_str(&tbash("2026-11-30T11:00:00.000Z", "c1", "while true; do [ -f out.done ] && break; sleep 5; done", true));
c.push_str(&tresult("2026-11-30T11:00:01.000Z", "c1", "Command running in background with ID: b1. Output is being written to: /tmp/x"));
c.push_str(&tnotice("2026-11-30T12:00:00.000Z", "c1", "completed"));
c.push_str(&tbash("2026-11-30T13:00:00.000Z", "b1", "tail --pid=$(pgrep -f train.py | head -1) -f train.log", false));
c.push_str(&tbash("2026-11-30T14:00:00.000Z", "n1", "timeout 600 bash -c 'until [ -f out.done ]; do sleep 5; done'", false));
c.push_str(&tresult("2026-11-30T14:09:00.000Z", "n1", "ok"));
c.push_str(&tbash("2026-11-30T15:00:00.000Z", "n2", "cmd & p=$!; wait $p", false));
c.push_str(&tresult("2026-11-30T15:30:00.000Z", "n2", "ok"));
write(&home.join(".claude/projects/p/s.jsonl"), &c);
let mut x = xmeta();
x.push_str(&xu("wait"));
x.push_str(&xtcmd("2026-11-30T09:00:00.000Z", "x1", "until [ -f /tmp/ready ]; do sleep 2; done"));
x.push_str(&xtout("2026-11-30T09:00:30.000Z", "x1"));
write(&home.join(".codex/sessions/2026/11/30/rollout-1.jsonl"), &x);
home
}
#[test]
fn waiting_counts_the_three_classes_and_times_what_it_can() {
let home = waiting_home("wait-json");
let (code, out, _) = scan(&home, &["--json"]);
assert_eq!(code, 0, "{out}");
assert!(out.contains("\"id\":\"wait-pgrep-self-match\",\"count\":1,\"measured\":1,\"measured_background\":0,\"seconds\":600,\"longest_seconds\":600"), "{out}");
assert!(out.contains("\"id\":\"wait-pid-from-pgrep\",\"count\":1,\"measured\":0,\"measured_background\":0,\"seconds\":0,\"longest_seconds\":0"), "{out}");
assert!(out.contains("\"id\":\"wait-no-deadline\",\"count\":3,\"measured\":3,\"measured_background\":1,\"seconds\":4230,\"longest_seconds\":3600"), "{out}");
assert!(out.contains("\"total\":{\"count\":4,\"measured\":3,\"measured_background\":1,\"seconds\":4230,\"longest_seconds\":3600}"), "{out}");
assert!(out.contains("\"measured_as\":\"floor"), "{out}");
assert!(out.contains("\"risky\":{\"flagged\":0,"), "{out}");
}
#[test]
fn waiting_section_says_it_is_a_floor_and_how_it_was_measured() {
let home = waiting_home("wait-text");
let (_, out, _) = scan(&home, &[]);
assert!(out.contains("4. Waiting: 4 shell commands that wait badly"), "{out}");
assert!(out.contains(" 3 poll loop with no deadline and no counter") || out.contains(" 3 poll loop with no deadline and no counter"), "{out}");
assert!(out.contains("pgrep -f loop that matches its own shell"), "{out}");
assert!(out.contains("Time: at least 1 h 10 min of wall time across 3 of the 4 (longest 1 h 00 min)."), "{out}");
assert!(out.contains("this is a floor"), "{out}");
assert!(out.contains("launch to the completion notice"), "{out}");
assert!(out.contains("\n5. Next steps"), "{out}");
assert!(!out.contains("wait for the job"), "{out}");
}
#[test]
fn no_waiting_section_without_wait_commands() {
let home = fixture_home("wait-none");
let (_, out, _) = scan(&home, &[]);
assert!(!out.contains("Waiting"), "{out}");
assert!(out.contains("\n4. Next steps"), "{out}");
}
#[test]
fn a_wait_without_timestamps_is_counted_and_not_timed() {
let home = sandbox("wait-notime");
let mut c = cu("wait");
c.push_str(&cbash("a1", "while pgrep -f job; do sleep 5; done"));
c.push_str(&cresult("a1"));
write(&home.join(".claude/projects/p/s.jsonl"), &c);
let (_, out, _) = scan(&home, &["--json"]);
assert!(out.contains("\"id\":\"wait-pgrep-self-match\",\"count\":1,\"measured\":0"), "{out}");
let (_, text, _) = scan(&home, &[]);
assert!(text.contains("no time is reported"), "{text}");
}
#[test]
fn a_claude_file_that_mentions_payload_is_still_read_as_claude() {
let home = sandbox("payload-word");
let mut c = String::new();
c.push_str("{\"type\":\"attachment\",\"attachment\":{\"text\":\"the hook \\\"payload\\\" is JSON\"}}\n");
c.push_str(&cu("go"));
c.push_str(&tbash("2026-11-30T10:00:00.000Z", "a1", "until [ -f done ]; do sleep 5; done", false));
c.push_str(&tresult("2026-11-30T10:01:00.000Z", "a1", "ok"));
write(&home.join(".claude/projects/p/s.jsonl"), &c);
let (_, out, _) = scan(&home, &["--json"]);
assert!(out.contains("\"prompts\":1,\"commands\":1,"), "{out}");
assert!(out.contains("\"total\":{\"count\":1,\"measured\":1,"), "{out}");
}
fn xcell(id: &str, js: &str) -> String {
let input = js.replace('\\', "\\\\").replace('"', "\\\"").replace('\n', "\\n");
format!("{{\"type\":\"response_item\",\"payload\":{{\"type\":\"custom_tool_call\",\"status\":\"completed\",\"call_id\":\"{id}\",\"name\":\"exec\",\"input\":\"{input}\"}}}}\n")
}
#[test]
fn codex_exec_cells_count_as_shell_commands_by_harness() {
let home = sandbox("codex-cells");
write(
&home.join(".codex/sessions/2026/12/01/r.jsonl"),
&[
xmeta(),
xu("clean up"),
xcell("c1", "const a = await tools.exec_command({cmd: \"git push --force origin main\", workdir: \"/repo\"});\nconst b = await tools.exec_command({cmd: `rm -rf ${dir}/cache`, workdir: \"/repo\"});\ntext(a.output + b.output)"),
xcell("c2", "const r = await tools.apply_patch({input: patch}); text(r)"),
xcell("c3", "const c = 'ls'; await tools.exec_command({cmd: c})"),
xcmd("x1", "echo hi"),
]
.concat(),
);
write(&home.join(".claude/projects/p/s.jsonl"), &[cu("go"), cbash("a", "ls -la")].concat());
let (code, out, err) = scan(&home, &["--json"]);
assert_eq!(code, 0, "{err}");
assert!(out.contains("\"commands\":4,\"commands_by_harness\":{\"claude_code\":1,\"codex\":3}"), "{out}");
assert!(out.contains("\"title\":\"git push --force overwrites commits other people pushed\""), "{out}");
assert!(out.contains("\"flagged\":2,"), "{out}");
let (_, text, _) = scan(&home, &[]);
assert!(text.contains("Shell commands by harness: 1 Claude Code, 3 Codex."), "{text}");
}