instinct-cli 0.3.0

Local memory for AI coding agents: an MCP server and CLI that gives Claude Code, Codex, Cursor and any MCP client the one lesson that fits. Lessons that keep failing go quiet.
//! `instinct outcomes` on the fixture week in tests/fixtures/outcomes-week, and the explore arm of the hooks.
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};

fn bin() -> &'static str {
    env!("CARGO_BIN_EXE_instinct")
}

fn fixtures() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/outcomes-week")
}

fn run(store: &Path, args: &[&str], stdin: &str, env: &[(&str, &str)]) -> (i32, String) {
    let mut c = Command::new(bin());
    c.args(args).env("INSTINCT_STORE", store).env_remove("INSTINCT_EXPLORE");
    for (k, v) in env {
        c.env(k, v);
    }
    let mut child = c.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap();
    let _ = child.stdin.take().unwrap().write_all(stdin.as_bytes());
    let out = child.wait_with_output().unwrap();
    let mut text = String::from_utf8(out.stdout).unwrap();
    if !out.status.success() {
        text.push_str(&String::from_utf8_lossy(&out.stderr));
    }
    (out.status.code().unwrap(), text)
}

fn temp(name: &str) -> PathBuf {
    let dir = std::env::temp_dir().join(format!("instinct-outcomes-{}-{name}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    dir.join("bank.hxdb")
}

fn bank(store: &Path, title: &str, when: &str, found: &str, how: &str) -> String {
    let (code, out) = run(
        store,
        &["bank", "--title", title, "--when", when, "--found", found, "--how", how, "--evidence", "seen twice"],
        "",
        &[],
    );
    assert_eq!(code, 0, "{out}");
    out.split_whitespace().nth(1).unwrap().to_owned()
}

/// A store holding the three fixture lessons, and `<store>.sessions` filled from the fixture template.
fn week(name: &str) -> (PathBuf, [String; 3]) {
    let store = temp(name);
    let l1 = bank(
        &store,
        "Cargo registry mirror outage",
        "the cargo registry mirror is down",
        "fetch fails while the mirror is out",
        "use the vendored dir with cargo fetch --offline --vendored-sources",
    );
    let l2 = bank(
        &store,
        "pkill -f kills its own shell",
        "pkill -f worker stop process",
        "pkill -f matches its own shell and exits 144",
        "kill by pid with kill -TERM",
    );
    let l3 = bank(
        &store,
        "Migration lock timeout",
        "the database migration is stuck on a lock",
        "a blocking backend holds the lock",
        "terminate the blocking backend with pg_terminate_backend and set a short lock timeout",
    );
    let tpl = std::fs::read_to_string(fixtures().join("week.sessions")).unwrap();
    let text = tpl.replace("@L1@", &l1).replace("@L2@", &l2).replace("@L3@", &l3);
    let mut sessions = store.as_os_str().to_owned();
    sessions.push(".sessions");
    std::fs::write(sessions, text).unwrap();
    (store, [l1, l2, l3])
}

fn outcomes(store: &Path, extra: &[&str]) -> String {
    let f = fixtures();
    let (claude, codex) = (f.join("claude"), f.join("codex"));
    let mut args = vec!["outcomes", claude.to_str().unwrap(), codex.to_str().unwrap(), "--since", "36500d"];
    args.extend_from_slice(extra);
    let (code, out) = run(store, &args, "", &[]);
    assert_eq!(code, 0, "{out}");
    out
}

fn line_for<'a>(out: &'a str, label: &str, lesson: &str, hook: &str) -> Vec<&'a str> {
    out.lines()
        .filter(|l| {
            let f: Vec<&str> = l.split_whitespace().collect();
            f.first() == Some(&label) && f.get(1) == Some(&lesson) && f.get(2) == Some(&hook)
        })
        .collect()
}

#[test]
fn every_label_is_produced_with_its_evidence() {
    let (store, [l1, l2, l3]) = week("labels");
    let out = outcomes(&store, &[]);
    assert!(out.contains("13 delivered, 7 withheld, 19 transcript(s) read"), "{out}");
    assert!(out.contains("helped 7 . misled 2 . unused 3 . unclear 1"), "{out}");
    // prompt, helped: lesson words that were not in the prompt show up in the next calls, no correction
    assert_eq!(line_for(&out, "helped", &l1, "prompt").len(), 4, "{out}");
    assert!(out.contains("acted on it (fails, fetch, offline); no correction in 3 user turns"), "{out}");
    // prompt, misled: acted on it, then the user said it was wrong
    assert!(out.contains("then the user corrected: \"no, that's wrong, revert that\""), "{out}");
    // prompt, unused
    assert_eq!(line_for(&out, "unused", &l1, "prompt").len(), 1, "{out}");
    assert!(out.contains("not acted on: no lesson words in the next 1 calls; no correction"), "{out}");
    // tripwire: warned call failed once and never again; failed again; succeeded and nothing failed
    assert_eq!(line_for(&out, "helped", &l2, "guard").len(), 2, "{out}");
    assert!(out.contains("warned call failed once; it was not repeated, and the next 4 calls ran clean"), "{out}");
    assert_eq!(line_for(&out, "misled", &l2, "guard").len(), 1, "{out}");
    assert!(out.contains("the warned action failed again: `pkill -f worker --signal 9`"), "{out}");
    assert_eq!(line_for(&out, "unused", &l2, "guard").len(), 1, "{out}");
    // a delivery whose transcript is not here
    assert_eq!(line_for(&out, "unclear", &l3, "prompt").len(), 1, "{out}");
    assert!(out.contains("no transcript found for this session"), "{out}");
    // the Codex session is read the same way
    assert!(out.contains("dddddddd"), "{out}");
    assert!(out.contains("dry run: nothing written"), "{out}");
}

#[test]
fn dry_run_writes_nothing_and_apply_is_idempotent() {
    let (store, [l1, ..]) = week("apply");
    let before = std::fs::read(&store).unwrap();
    outcomes(&store, &[]);
    assert_eq!(std::fs::read(&store).unwrap(), before, "a dry run must not touch the bank");

    let first = outcomes(&store, &["--apply"]);
    assert!(first.contains("applied: 7 hit(s), 2 miss(es) recorded; 0 already recorded"), "{first}");
    let after_first = std::fs::read(&store).unwrap();
    assert_ne!(after_first, before);
    let second = outcomes(&store, &["--apply"]);
    assert!(second.contains("applied: 0 hit(s), 0 miss(es) recorded; 9 already recorded"), "{second}");
    assert_eq!(std::fs::read(&store).unwrap(), after_first, "a rerun must not write anything");

    let (_, listing) = run(&store, &["instincts"], "", &[]);
    assert!(listing.contains(&format!("{l1} · 4 hits")), "{listing}");
}

#[test]
fn an_explicit_hit_is_never_counted_twice() {
    let (store, [l1, ..]) = week("explicit");
    // The agent marked the lesson itself in the session that ended up `helped`. The record carries no
    // session, so the guard is "after the delivery and before that session's transcript ends": the first
    // fixture session starts at 1795609800 and its last event is 30 minutes later.
    let (code, _) = run(&store, &["hit", &l1, "--note", "explicit"], "", &[]);
    assert_eq!(code, 0);
    // Marks are stamped with the real clock, which is long after the fixture week: nothing is suppressed.
    let out = outcomes(&store, &["--apply"]);
    assert!(out.contains("7 hit(s)"), "{out}");
    assert!(out.contains("0 skipped because the agent marked them itself"), "{out}");
}

fn civil_iso(secs: u64) -> String {
    let days = (secs / 86_400) as i64;
    let rem = secs % 86_400;
    let z = days + 719_468;
    let era = z.div_euclid(146_097);
    let doe = z - era * 146_097;
    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let m = if mp < 10 { mp + 3 } else { mp - 9 };
    let y = yoe + era * 400 + i64::from(m <= 2);
    format!("{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}Z", rem / 3600, rem % 3600 / 60, rem % 60)
}

/// A session that is happening now: the lesson is delivered, used, and three calm turns follow.
fn live_session(store: &Path, dir: &Path, sid: &str, lesson: &str) {
    let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs();
    let t = now - 1900;
    let user = |at: u64, text: &str| {
        format!("{{\"type\":\"user\",\"sessionId\":\"{sid}\",\"timestamp\":\"{}\",\"message\":{{\"role\":\"user\",\"content\":\"{text}\"}}}}\n", civil_iso(at))
    };
    let mut lines = user(t, "the cargo registry mirror is down again");
    lines.push_str(&format!(
        "{{\"type\":\"assistant\",\"sessionId\":\"{sid}\",\"timestamp\":\"{}\",\"message\":{{\"role\":\"assistant\",\"content\":[{{\"type\":\"tool_use\",\"id\":\"u1\",\"name\":\"Bash\",\"input\":{{\"command\":\"cargo fetch --offline --vendored-sources\"}}}}]}}}}\n",
        civil_iso(t + 5)
    ));
    lines.push_str(&user(t + 600, "ok now run the tests"));
    lines.push_str(&user(t + 1200, "thanks"));
    lines.push_str(&user(t + 1800, "next task please"));
    std::fs::create_dir_all(dir).unwrap();
    std::fs::write(dir.join(format!("{sid}.jsonl")), lines).unwrap();
    let mut p = store.as_os_str().to_owned();
    p.push(".sessions");
    let mut f = std::fs::OpenOptions::new().create(true).append(true).open(PathBuf::from(p)).unwrap();
    writeln!(f, "{}\t{sid}\tD\t{lesson}\tp", t + 1).unwrap();
}

fn live_outcomes(store: &Path, dir: &Path, extra: &[&str]) -> String {
    let mut args = vec!["outcomes", dir.to_str().unwrap(), "--since", "1d"];
    args.extend_from_slice(extra);
    let (code, out) = run(store, &args, "", &[]);
    assert_eq!(code, 0, "{out}");
    out
}

#[test]
fn an_explicit_mark_in_the_same_session_wins_and_is_never_counted_twice() {
    let store = temp("explicit-live");
    let id = bank(
        &store,
        "Cargo registry mirror outage",
        "the cargo registry mirror is down",
        "fetch fails while the mirror is out",
        "use the vendored dir with cargo fetch --offline --vendored-sources",
    );
    let dir = store.parent().unwrap().join("transcripts");
    live_session(&store, &dir, "live-session-1", &id);

    // Observed alone: helped, one hit.
    let dry = live_outcomes(&store, &dir, &[]);
    assert!(dry.contains(&format!("helped  {id} prompt")), "{dry}");

    // The agent records its own hit during that session (stamped now, inside the session's window).
    let (code, _) = run(&store, &["hit", &id, "--note", "agent said so"], "", &[]);
    assert_eq!(code, 0);
    let out = live_outcomes(&store, &dir, &["--apply"]);
    assert!(out.contains("applied: 0 hit(s), 0 miss(es) recorded; 0 already recorded; 1 skipped because the agent marked them itself"), "{out}");
    let (_, listing) = run(&store, &["recall", "--q", "the cargo registry mirror is down"], "", &[]);
    assert!(listing.contains("1 hit / 0 miss"), "one hit, from the agent only: {listing}");
}

#[test]
fn without_an_explicit_mark_the_same_session_records_exactly_one_hit() {
    let store = temp("observed-live");
    let id = bank(
        &store,
        "Cargo registry mirror outage",
        "the cargo registry mirror is down",
        "fetch fails while the mirror is out",
        "use the vendored dir with cargo fetch --offline --vendored-sources",
    );
    let dir = store.parent().unwrap().join("transcripts");
    live_session(&store, &dir, "live-session-2", &id);
    let out = live_outcomes(&store, &dir, &["--apply"]);
    assert!(out.contains("applied: 1 hit(s), 0 miss(es) recorded; 0 already recorded; 0 skipped"), "{out}");
    let again = live_outcomes(&store, &dir, &["--apply"]);
    assert!(again.contains("applied: 0 hit(s), 0 miss(es) recorded; 1 already recorded"), "{again}");
    let (_, listing) = run(&store, &["recall", "--q", "the cargo registry mirror is down"], "", &[]);
    assert!(listing.contains("1 hit / 0 miss"), "{listing}");
}

#[test]
fn json_output_carries_the_labels_and_the_comparison() {
    let (store, _) = week("json");
    let out = outcomes(&store, &["--json"]);
    assert!(out.starts_with("{\"delivered\":13,\"withheld\":7,"), "{out}");
    assert!(out.contains("\"helped\":7,\"misled\":2,\"unused\":3,\"unclear\":1"), "{out}");
    assert!(out.contains("\"comparison\":{\"lessons\":2,"), "{out}");
    assert!(out.contains("\"outcome_id\":\"outcome:"), "{out}");
}

fn prompt_json(sid: &str, text: &str) -> String {
    format!("{{\"session_id\":\"{sid}\",\"prompt\":\"{text}\"}}")
}

#[test]
fn explore_arm_withholds_records_hold_and_stays_stable() {
    let store = temp("explore");
    let id = bank(&store, "Cargo registry mirror outage", "the cargo registry mirror is down", "fetch fails", "use the vendored dir");
    let q = prompt_json("sess-explore-1", "the cargo registry mirror is down again");
    let sessions = {
        let mut p = store.as_os_str().to_owned();
        p.push(".sessions");
        PathBuf::from(p)
    };

    // Off by default: delivered, recorded as D with the prompt source.
    let (_, out) = run(&store, &["prompt"], &q, &[]);
    assert!(out.contains(&id), "{out}");
    let text = std::fs::read_to_string(&sessions).unwrap();
    assert!(text.lines().any(|l| l.ends_with(&format!("\tD\t{id}\tp"))), "{text}");

    // Share 1: always withheld, recorded as H, nothing printed, and asking again stays the same.
    let (_, out) = run(&store, &["prompt"], &prompt_json("sess-explore-2", "the cargo registry mirror is down again"), &[("INSTINCT_EXPLORE", "1")]);
    assert!(out.trim().is_empty(), "{out}");
    let (_, again) = run(&store, &["prompt"], &prompt_json("sess-explore-2", "the cargo registry mirror is down again"), &[("INSTINCT_EXPLORE", "1")]);
    assert!(again.trim().is_empty(), "{again}");
    let text = std::fs::read_to_string(&sessions).unwrap();
    let held: Vec<&str> = text.lines().filter(|l| l.contains("\tH\t")).collect();
    assert_eq!(held.len(), 1, "a withheld lesson is recorded once per session: {text}");
    assert!(held[0].contains("sess-explore-2") && held[0].ends_with(&format!("\tH\t{id}\tp")), "{text}");

    // Share 0 and junk values mean off.
    for (n, off) in ["0", "", "abc", "-1"].into_iter().enumerate() {
        let (_, out) = run(&store, &["prompt"], &prompt_json(&format!("sess-explore-off-{n}"), "the cargo registry mirror is down again"), &[("INSTINCT_EXPLORE", off)]);
        assert!(out.contains(&id), "INSTINCT_EXPLORE={off:?}: {out}");
    }
}

#[test]
fn explore_arm_covers_the_tripwire_too() {
    let store = temp("explore-guard");
    let (code, out) = run(
        &store,
        &["bank", "--title", "pkill -f kills its own shell", "--when", "pkill -f worker", "--found", "pkill -f matches itself", "--how", "kill by pid", "--evidence", "seen", "--tags", "tool_bash pkill"],
        "",
        &[],
    );
    assert_eq!(code, 0, "{out}");
    let id = out.split_whitespace().nth(1).unwrap().to_owned();
    let payload = "{\"session_id\":\"sess-g-1\",\"hook_event_name\":\"PreToolUse\",\"tool_name\":\"Bash\",\"tool_input\":{\"command\":\"pkill -f worker\"}}";
    let (_, held) = run(&store, &["guard"], payload, &[("INSTINCT_EXPLORE", "1")]);
    assert!(held.trim().is_empty(), "{held}");
    let mut p = store.as_os_str().to_owned();
    p.push(".sessions");
    let text = std::fs::read_to_string(PathBuf::from(p)).unwrap();
    assert!(text.lines().any(|l| l.ends_with(&format!("\tH\t{id}\tg"))), "{text}");
}

#[test]
fn explore_share_is_close_to_the_requested_share() {
    // The hash is stable and uniform (unit-tested in session.rs); here the hook over many sessions.
    let store = temp("explore-share");
    bank(&store, "Cargo registry mirror outage", "the cargo registry mirror is down", "fetch fails", "use the vendored dir");
    let mut held = 0;
    let n = 200;
    for i in 0..n {
        let q = prompt_json(&format!("share-session-{i}"), "the cargo registry mirror is down again");
        let (_, out) = run(&store, &["prompt"], &q, &[("INSTINCT_EXPLORE", "0.25")]);
        if out.trim().is_empty() {
            held += 1;
        }
    }
    let share = held as f64 / n as f64;
    assert!((0.15..0.35).contains(&share), "withheld share {share} for 0.25");
}

fn copy_dir(from: &Path, to: &Path) {
    std::fs::create_dir_all(to).unwrap();
    for e in std::fs::read_dir(from).unwrap().flatten() {
        std::fs::copy(e.path(), to.join(e.file_name())).unwrap();
    }
}

/// Homes for the two harnesses, filled from the fixture week, so `eval` finds the transcripts by itself.
fn harness_homes(store: &Path) -> (String, String) {
    let root = store.parent().unwrap().join("homes");
    copy_dir(&fixtures().join("claude"), &root.join("claude/projects/p"));
    copy_dir(&fixtures().join("codex"), &root.join("codex/sessions/2026/11/28"));
    (root.join("claude").to_string_lossy().into_owned(), root.join("codex").to_string_lossy().into_owned())
}

#[test]
fn eval_counts_only_real_deliveries_and_points_at_outcomes() {
    let (store, [l1, ..]) = week("eval-suggest");
    let (code, out) = run(&store, &["eval", "--since", "all"], "", &[("HOME", "/nonexistent")]);
    assert_eq!(code, 0, "{out}");
    // 13 delivered lines in the record; the 7 withheld (H) lines are not deliveries
    assert!(out.contains("Delivery record: 13 deliveries in 13 sessions."), "{out}");
    assert!(out.contains(&format!("{l1}  Cargo registry mirror outage\n      delivered 6 times")), "{out}");
    // the automatic way to judge them, dry run first
    assert!(out.contains("Judge them from the session transcripts: look first, then record."), "{out}");
    let dry = out.find("instinct outcomes --since all\n").expect("dry run suggestion");
    let apply = out.find("instinct outcomes --since all --apply\n").expect("apply suggestion");
    assert!(dry < apply, "{out}");
    // and the by-hand commands stay
    assert!(out.contains(&format!("instinct hit {l1} --note")), "{out}");
}

#[test]
fn eval_reports_the_explore_comparison_when_held_lines_exist() {
    let (store, _) = week("eval-explore");
    let (claude, codex) = harness_homes(&store);
    let env = [("CLAUDE_CONFIG_DIR", claude.as_str()), ("CODEX_HOME", codex.as_str()), ("HOME", "/nonexistent")];
    let (code, out) = run(&store, &["eval", "--since", "all"], "", &env);
    assert_eq!(code, 0, "{out}");
    assert!(out.contains("Withheld vs delivered (INSTINCT_EXPLORE)"), "{out}");
    assert!(out.contains("prompt, corrections in the next 3 turns: delivered 16.7% (1/6) vs withheld 25.0% (1/4)"), "{out}");
    assert!(out.contains("tripwire, failed share of the next 8 calls: delivered 7.7% (1/13) vs withheld 22.2% (2/9)"), "{out}");
    assert!(out.contains("caveat: only 6 delivered and 4 withheld observations"), "{out}");
    let (code, json) = run(&store, &["eval", "--since", "all", "--json"], "", &env);
    assert_eq!(code, 0, "{json}");
    assert!(json.contains("\"explore\":{\"delivered\":13,\"withheld\":7,\"lessons\":2,"), "{json}");
}

#[test]
fn eval_has_no_explore_section_without_held_lines() {
    let store = temp("eval-no-explore");
    let id = bank(&store, "Cargo registry mirror outage", "the cargo registry mirror is down", "fetch fails", "use the vendored dir");
    let (_, _) = run(&store, &["prompt"], &prompt_json("sess-plain", "the cargo registry mirror is down again"), &[]);
    let (code, out) = run(&store, &["eval", "--since", "all"], "", &[("HOME", "/nonexistent")]);
    assert_eq!(code, 0, "{out}");
    assert!(!out.contains("INSTINCT_EXPLORE"), "{out}");
    assert!(out.contains(&format!("{id}  Cargo registry mirror outage")), "{out}");
    let (_, json) = run(&store, &["eval", "--since", "all", "--json"], "", &[("HOME", "/nonexistent")]);
    assert!(json.contains("\"explore\":null"), "{json}");
}