use std::path::PathBuf;
use std::process::Command;
fn fx(name: &str) -> String {
format!("{}/tests/fixtures/transcripts/{name}", env!("CARGO_MANIFEST_DIR"))
}
fn dir(name: &str) -> PathBuf {
let d = std::env::temp_dir().join(format!("instinct-mine-test-{}-{name}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).unwrap();
d
}
fn run(args: &[&str], store: Option<&PathBuf>) -> (i32, String, String) {
let mut c = Command::new(env!("CARGO_BIN_EXE_instinct"));
let home = std::env::temp_dir().join(format!("instinct-mine-test-home-{}", std::process::id()));
c.env_remove("INSTINCT_STORE").env_remove("INSTINCT_OLLAMA").env("XDG_DATA_HOME", &home).env("LOCALAPPDATA", &home).args(args);
if let Some(s) = store {
c.env("INSTINCT_STORE", s);
}
let o = c.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 lessons(store: &PathBuf) -> usize {
std::fs::read_to_string(store)
.map(|t| t.lines().filter(|l| l.contains("\"title\"")).count())
.unwrap_or(0)
}
#[test]
fn claude_correction_window() {
let (code, out, _) = run(&["mine", &fx("claude-correction.jsonl")], None);
assert_eq!(code, 0, "{out}");
assert!(out.contains("1 new"), "{out}");
assert!(out.contains("when: add a --json flag to the report command"), "{out}");
assert!(out.contains("The user rejected it: \"no, do not rewrite the parser"), "{out}");
assert!(out.contains("`cargo test --locked --offline` then passed and the user confirmed"), "{out}");
assert!(out.contains("evidence: mined from claude-correction.jsonl turn 2 (line 4)"), "{out}");
assert!(out.contains("conf 0.95"), "{out}");
}
#[test]
fn claude_recovery_window() {
let (_, out, _) = run(&["mine", &fx("claude-recovery.jsonl"), "--json"], None);
assert!(out.contains("\"kind\":\"recovery\""), "{out}");
assert!(out.contains("\"when\":\"build the release binary for the deploy box\""), "{out}");
assert!(out.contains("`cargo build --release` failed"), "{out}");
assert!(out.contains("`cargo build --release --offline` succeeded instead. Added --offline."), "{out}");
assert!(out.contains("\"tags\":\"mined,recovery,cargo\""), "{out}");
}
#[test]
fn codex_windows() {
let (_, c, _) = run(&["mine", &fx("codex-correction.jsonl"), "--json"], None);
assert!(c.contains("\"kind\":\"correction\""), "{c}");
assert!(c.contains("The agent ran `sed -i '/^$/d' data/*.csv`"), "{c}");
assert!(c.contains("`pytest -q` then passed"), "{c}");
assert!(c.contains("turn 2 (line 7)"), "{c}");
let (_, r, _) = run(&["mine", &fx("codex-recovery.jsonl"), "--json"], None);
assert!(r.contains("\"kind\":\"recovery\""), "{r}");
assert!(r.contains("`npm run build --prefix web` succeeded instead"), "{r}");
}
#[test]
fn noise_never_becomes_a_lesson() {
let (_, out, _) = run(&["mine", &fx("claude-noise.jsonl"), "--json"], None);
assert!(out.contains("\"candidates\":0"), "{out}");
assert!(
out.contains("\"skipped\":{\"no_success\":1,\"probe\":1,\"transient\":1,\"env_dump\":1,\"rejected\":1,\"script\":1,\"credentials\":0,\"low_confidence\":0}"),
"{out}"
);
}
#[test]
fn secrets_are_redacted() {
let d = dir("secrets");
let gh = format!("{}{}", "ghp_", "Zq81xKp0Lm3Vb7Nc2Rt5Yw9Ud4Fh6Jg1Aa3S");
let key = format!("{}{}", "sk-", "proj-Q1w2E3r4T5y6U7i8O9p0");
let env = "hunter2hunter2";
let bearer = format!("{}{}", "eyJhbGciOiJIUzI1NiJ9.", "eyJzdWIiOiIxMjM0NTY3ODkwIn0.c2lnbmF0dXJlMTIz");
let pass = "p4ssw0rdValue";
let t = std::fs::read_to_string(fx("claude-secrets.template.jsonl"))
.unwrap()
.replace("@GH@", &gh)
.replace("@KEY@", &key)
.replace("@ENVVAL@", env)
.replace("@BEARER@", &bearer)
.replace("@PASS@", pass);
let f = d.join("secrets.jsonl");
std::fs::write(&f, t).unwrap();
let (code, out, _) = run(&["mine", f.to_str().unwrap(), "--json"], None);
assert_eq!(code, 0, "{out}");
assert!(out.contains("\"candidates\":1"), "{out}");
for s in [gh.as_str(), key.as_str(), env, bearer.as_str(), pass] {
assert!(!out.contains(s), "leaked {s}: {out}");
}
assert!(out.contains("[REDACTED]"), "{out}");
assert!(!out.contains("\"redactions\":0"), "{out}");
assert!(out.contains("read DEPLOY_TOKEN="), "{out}");
assert!(out.contains("Authorization: Bearer [REDACTED]"), "{out}");
}
#[test]
fn dry_run_then_apply_and_dedupe() {
let d = dir("apply");
let store = d.join("bank.jsonl");
let (a, b) = (fx("claude-correction.jsonl"), fx("codex-recovery.jsonl"));
let (_, dry, _) = run(&["mine", &a, &a, &b], Some(&store));
assert!(dry.contains("dry run, add --apply"), "{dry}");
assert!(dry.contains("would bank: 2 new, 0 already banked, 1 repeated in this run"), "{dry}");
assert!(!store.exists(), "dry run created the bank");
let (code, applied, _) = run(&["mine", &a, &b, "--apply"], Some(&store));
assert_eq!(code, 0, "{applied}");
assert!(applied.contains("banked: 2 new"), "{applied}");
assert_eq!(lessons(&store), 2);
let text = std::fs::read_to_string(&store).unwrap();
assert_eq!(text.matches("\"source\":\"mined\"").count(), 2, "{text}");
assert!(text.contains("\"state\":\"candidate\"") && text.contains("\"evidence_status\":\"unverified\""), "{text}");
assert!(text.contains("mined,correction") && text.contains("mined from claude-correction.jsonl turn 2"), "{text}");
let (_, again, _) = run(&["mine", &a, &b, "--apply"], Some(&store));
assert!(again.contains("banked: 0 new, 2 already banked"), "{again}");
assert_eq!(lessons(&store), 2);
}
#[test]
fn mined_lessons_stay_quiet_until_they_earn_a_hit() {
let d = dir("quiet");
let store = d.join("bank.jsonl");
run(&["mine", &fx("claude-correction.jsonl"), "--apply"], Some(&store));
let (_, out, _) = run(&["recall", "--q", "add a --json flag to the report command"], Some(&store));
assert!(!out.contains("do not rewrite the parser"), "mined lesson surfaced without a hit: {out}");
let id = std::fs::read_to_string(&store)
.unwrap()
.split("\"id\":\"")
.nth(1)
.and_then(|s| s.split('"').next())
.unwrap()
.to_string();
run(&["hit", &id], Some(&store));
let (_, after, _) = run(&["recall", "--q", "add a --json flag to the report command"], Some(&store));
assert!(after.contains("do not rewrite the parser"), "hit did not unlock the lesson: {after}");
}
#[test]
fn apply_uses_the_default_bank_and_options_are_checked() {
let home = dir("default-bank");
let mut c = Command::new(env!("CARGO_BIN_EXE_instinct"));
c.env_remove("INSTINCT_STORE").env_remove("INSTINCT_OLLAMA").env("XDG_DATA_HOME", &home).env("LOCALAPPDATA", &home);
let o = c.args(["mine", &fx("claude-correction.jsonl"), "--apply"]).output().unwrap();
assert!(o.status.success(), "{}", String::from_utf8_lossy(&o.stderr));
let bank = home.join("instinct").join("bank.hxdb");
assert_eq!(lessons(&bank), 1, "default bank not written");
assert!(std::fs::read_to_string(&bank).unwrap().contains("\"source\":\"mined\""));
let (code, _, err) = run(&["mine", "--since", "soon"], None);
assert_ne!(code, 0);
assert!(err.contains("--since"), "{err}");
let (code, _, err) = run(&["mine", "/nonexistent/transcripts"], None);
assert_ne!(code, 0);
assert!(err.contains("no such file"), "{err}");
let (_, help, _) = run(&["mine", "--help"], None);
assert!(help.contains("dry run") && help.contains("--apply"), "{help}");
}
#[test]
fn folders_since_and_project_filters() {
let d = dir("filters");
let proj = d.join("-home-me-alpha");
std::fs::create_dir_all(&proj).unwrap();
std::fs::copy(fx("claude-correction.jsonl"), proj.join("s1.jsonl")).unwrap();
let other = d.join("-home-me-beta");
std::fs::create_dir_all(&other).unwrap();
std::fs::copy(fx("claude-recovery.jsonl"), other.join("s2.jsonl")).unwrap();
let root = d.to_str().unwrap();
let (_, all, _) = run(&["mine", root, "--json"], None);
assert!(all.contains("\"transcripts\":2") && all.contains("\"candidates\":2"), "{all}");
let (_, one, _) = run(&["mine", root, "--project", "alpha", "--json"], None);
assert!(one.contains("\"transcripts\":1") && one.contains("\"kind\":\"correction\""), "{one}");
let (_, recent, _) = run(&["mine", root, "--since", "1d", "--json"], None);
assert!(recent.contains("\"transcripts\":2"), "{recent}");
let (_, high, _) = run(&["mine", root, "--min-confidence", "0.9", "--json"], None);
assert!(high.contains("\"candidates\":1") && high.contains("\"low_confidence\":1"), "{high}");
}
#[test]
fn credential_and_access_changes_are_never_mined() {
let (code, out, _) = run(&["mine", &fx("claude-credentials.jsonl"), "--json", "--min-confidence", "0"], None);
assert_eq!(code, 0, "{out}");
assert!(out.contains("\"candidates\":0"), "{out}");
assert!(out.contains("\"credentials\":3"), "{out}");
assert!(!out.contains("authorized_keys") && !out.contains("hunter2") && !out.contains("wrongpass"), "{out}");
let (_, text, _) = run(&["mine", &fx("claude-credentials.jsonl")], None);
assert!(text.contains("3 credentials"), "{text}");
}
#[test]
fn limit_ranks_by_confidence_and_counts_the_rest() {
let (a, b) = (fx("claude-correction.jsonl"), fx("claude-recovery.jsonl"));
let (_, out, _) = run(&["mine", &a, &b, "--json", "--limit", "1"], None);
assert!(out.contains("\"candidates\":1,\"cut_by_limit\":1"), "{out}");
assert!(out.contains("\"kind\":\"correction\"") && !out.contains("\"kind\":\"recovery\""), "{out}");
let (_, text, _) = run(&["mine", &a, &b, "--limit", "1"], None);
assert!(text.contains("1 more candidate(s) found and cut by --limit 1"), "{text}");
let d = dir("limit");
let store = d.join("bank.jsonl");
run(&["mine", &a, &b, "--limit", "1", "--apply"], Some(&store));
assert_eq!(lessons(&store), 1);
let (code, _, err) = run(&["mine", "--limit", "0"], None);
assert_ne!(code, 0);
assert!(err.contains("--limit"), "{err}");
let (_, help, _) = run(&["mine", "--help"], None);
assert!(help.contains("Mining finds candidates; you decide what to bank."), "{help}");
}