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.
//! Session memory for the hooks (`<store>.sessions`), `instinct settle`, and the title gate.
use std::io::Write;
use std::path::PathBuf;
use std::process::{Command, Stdio};

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

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

/// Runs the binary with stdin; returns (exit code, stdout). Stderr must stay empty.
fn run(store: Option<&PathBuf>, args: &[&str], stdin: &str) -> (i32, String) {
    let mut c = Command::new(bin());
    c.args(args).env_remove("INSTINCT_STORE");
    if let Some(s) = store {
        c.env("INSTINCT_STORE", s);
    }
    let mut child = c.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap();
    if let Err(e) = child.stdin.take().unwrap().write_all(stdin.as_bytes()) {
        assert_eq!(e.kind(), std::io::ErrorKind::BrokenPipe, "unexpected write error: {e}");
    }
    let out = child.wait_with_output().unwrap();
    (out.status.code().unwrap(), String::from_utf8(out.stdout).unwrap())
}

/// Banks one lesson whose `when` and tags never match the test queries; returns (id, bank output).
fn bank(store: &PathBuf, title: &str, tags: Option<&str>) -> (String, String) {
    let mut args = vec![
        "bank", "--title", title, "--when", "zzzz yyyy", "--found", "f", "--how", "use the vendored dir",
        "--evidence", "seen twice",
    ];
    if let Some(t) = tags {
        args.extend(["--tags", t]);
    }
    let (code, out) = run(Some(store), &args, "");
    assert_eq!(code, 0, "{out}");
    let id = out.split_whitespace().nth(1).unwrap().to_owned();
    (id, out)
}

const TITLE: &str = "Cargo registry mirror outage";
const PROMPT: &str = "the cargo registry mirror is down again";

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

fn guard(sid: &str, command: &str) -> String {
    format!(
        "{{\"session_id\":\"{sid}\",\"hook_event_name\":\"PreToolUse\",\"tool_name\":\"Bash\",\"tool_input\":{{\"command\":\"{command}\"}}}}"
    )
}

fn stop(sid: &str) -> String {
    format!("{{\"session_id\":\"{sid}\",\"hook_event_name\":\"Stop\",\"stop_hook_active\":false}}")
}

#[test]
fn the_same_lesson_is_not_delivered_twice_in_one_session() {
    let s = store("dedupe");
    let (id, _) = bank(&s, TITLE, Some("qqqq wwww"));
    let (_, first) = run(Some(&s), &["prompt"], &prompt("a", PROMPT));
    assert!(first.contains(&id), "{first}");
    let (code, second) = run(Some(&s), &["prompt"], &prompt("a", PROMPT));
    assert_eq!(code, 0);
    assert!(!second.contains(TITLE), "repeat delivery: {second}");
    // The second prompt carries the once-per-session question about the first lesson instead.
    assert!(second.contains(&format!("instinct hit {id}")), "{second}");
    // Another session still gets it.
    let (_, other) = run(Some(&s), &["prompt"], &prompt("b", PROMPT));
    assert!(other.contains(&id), "{other}");
    // The record holds ids and counts only.
    let rec = std::fs::read_to_string(format!("{}.sessions", s.display())).unwrap();
    assert_eq!(rec.lines().count(), 3, "delivered a, reminded a, delivered b: {rec}");
    assert!(rec.lines().all(|l| (4..=5).contains(&l.split('\t').count())), "{rec}");
}

#[test]
fn guard_and_prompt_share_the_session_record() {
    let s = store("shared");
    let (id, _) = bank(&s, TITLE, Some("qqqq wwww"));
    let (_, first) = run(Some(&s), &["prompt"], &prompt("a", PROMPT));
    assert!(first.contains(&id));
    let (code, out) = run(Some(&s), &["guard"], &guard("a", "cargo registry mirror down"));
    assert_eq!(code, 0);
    assert!(out.trim().is_empty(), "guard repeated the lesson: {out}");
    let (_, other) = run(Some(&s), &["guard"], &guard("b", "cargo registry mirror down"));
    assert!(other.contains(&id), "{other}");
}

#[test]
fn without_a_session_id_nothing_is_remembered() {
    let s = store("nosession");
    let (id, _) = bank(&s, TITLE, Some("qqqq wwww"));
    for _ in 0..2 {
        let (_, out) = run(Some(&s), &["prompt"], &format!("{{\"prompt\":\"{PROMPT}\"}}"));
        assert!(out.contains(&id), "{out}");
    }
    assert!(!PathBuf::from(format!("{}.sessions", s.display())).exists());
}

#[test]
fn old_session_lines_are_pruned_on_write() {
    let s = store("prune");
    let (id, _) = bank(&s, TITLE, Some("qqqq wwww"));
    let file = format!("{}.sessions", s.display());
    std::fs::write(&file, "1000\told\tD\tin-old\n").unwrap();
    let (_, out) = run(Some(&s), &["prompt"], &prompt("a", PROMPT));
    assert!(out.contains(&id));
    let rec = std::fs::read_to_string(&file).unwrap();
    assert!(!rec.contains("in-old"), "{rec}");
    assert_eq!(rec.lines().count(), 1, "{rec}");
}

#[test]
fn settle_reminds_once_with_the_documented_stop_form() {
    let s = store("settle");
    let (id, _) = bank(&s, TITLE, Some("qqqq wwww"));
    run(Some(&s), &["prompt"], &prompt("a", PROMPT));
    let (code, out) = run(Some(&s), &["settle"], &stop("a"));
    assert_eq!(code, 0);
    let want = format!(
        "{{\"hookSpecificOutput\":{{\"hookEventName\":\"Stop\",\"additionalContext\":\"You used lesson {id} this session. If it helped, run `instinct hit {id} --note '…'`; if it misled you, `instinct miss {id} --note '…'`.\"}}}}"
    );
    assert_eq!(out.trim(), want);
    let (code, again) = run(Some(&s), &["settle"], &stop("a"));
    assert_eq!(code, 0);
    assert!(again.trim().is_empty(), "second reminder: {again}");
}

#[test]
fn settle_codex_form_and_text_form() {
    let s = store("settle-forms");
    let (id, _) = bank(&s, TITLE, Some("qqqq wwww"));
    run(Some(&s), &["prompt"], &prompt("a", PROMPT));
    let (_, out) = run(Some(&s), &["settle", "--format", "codex"], &stop("a"));
    assert!(out.starts_with("{\"decision\":\"block\",\"reason\":\"You used lesson "), "{out}");
    assert!(out.contains(&id));
    run(Some(&s), &["prompt"], &prompt("t", PROMPT));
    let (_, text) = run(Some(&s), &["settle", "--format", "text"], &stop("t"));
    assert!(text.starts_with("You used lesson "), "{text}");
}

#[test]
fn settle_is_silent_when_nothing_is_owed_and_never_fails() {
    let s = store("silent");
    let (id, _) = bank(&s, TITLE, Some("qqqq wwww"));
    // Nothing delivered in this session.
    let (code, out) = run(Some(&s), &["settle"], &stop("a"));
    assert_eq!((code, out.trim()), (0, ""));
    // Delivered, then a hit recorded: settled.
    run(Some(&s), &["prompt"], &prompt("a", PROMPT));
    let (code, _) = run(Some(&s), &["hit", &id, "--note", "worked"], "");
    assert_eq!(code, 0);
    let (code, out) = run(Some(&s), &["settle"], &stop("a"));
    assert_eq!((code, out.trim()), (0, ""));
    // A miss settles too.
    run(Some(&s), &["prompt"], &prompt("m", PROMPT));
    run(Some(&s), &["miss", &id, "--note", "misled", "--outcome-id", "o2"], "");
    let (code, out) = run(Some(&s), &["settle"], &stop("m"));
    assert_eq!((code, out.trim()), (0, ""));
    // A Stop hook that is itself the continuation of a Stop hook stays silent.
    run(Some(&s), &["prompt"], &prompt("c", PROMPT));
    let (code, out) = run(
        Some(&s),
        &["settle"],
        "{\"session_id\":\"c\",\"stop_hook_active\":true}",
    );
    assert_eq!((code, out.trim()), (0, ""));
    // Bad input, empty input, a payload without session_id, and a missing store all exit 0 and print nothing.
    for input in ["", "not json", "{}", "{\"session_id\":\"\"}", "[1,2]"] {
        let (code, out) = run(Some(&s), &["settle"], input);
        assert_eq!((code, out.trim()), (0, ""), "input {input:?}");
    }
    let (code, out) = run(None, &["settle"], &stop("a"));
    assert_eq!((code, out.trim()), (0, ""));
}

#[test]
fn settle_exit_code_is_zero_with_an_unreadable_session_file() {
    let s = store("garbled");
    bank(&s, TITLE, Some("qqqq wwww"));
    std::fs::write(format!("{}.sessions", s.display()), b"\xff\xfe\nnot\ttabs\n").unwrap();
    let (code, out) = run(Some(&s), &["settle"], &stop("a"));
    assert_eq!((code, out.trim()), (0, ""));
}

#[test]
fn the_title_counts_toward_the_two_word_trigger() {
    let s = store("title");
    let (id, _) = bank(&s, TITLE, Some("qqqq wwww"));
    let (_, out) = run(Some(&s), &["prompt"], &prompt("t1", PROMPT));
    assert!(out.contains(&id), "title-only match was not recalled: {out}");
    // One shared word is not a trigger.
    let (_, one) = run(Some(&s), &["prompt"], &prompt("t2", "my cargo build is slow today"));
    assert!(one.trim().is_empty(), "{one}");
}

#[test]
fn banking_without_tags_derives_one_phrase_from_the_title() {
    let s = store("derive");
    bank(&s, "Cargo registry mirror outage during the build", None);
    let (_, out) = run(Some(&s), &["recall", "--q", "cargo registry mirror outage"], "");
    assert!(out.contains("TAGS: cargo registry mirror outage"), "{out}");
    // Explicit tags are never replaced.
    bank(&s, "Another distinct lesson title here", Some("mine"));
    let (_, kept) = run(Some(&s), &["recall", "--q", "another distinct lesson title"], "");
    assert!(kept.contains("TAGS: mine"), "{kept}");
    // A title with fewer than two distinctive words gets no tag.
    bank(&s, "The fix", None);
    let (_, none) = run(Some(&s), &["recall", "--q", "fix"], "");
    assert!(!none.contains("TAGS:"), "{none}");
}

/// A Claude Code transcript for session `sid`, stamped in 2099 so every event is after the delivery.
fn transcript(s: &PathBuf, sid: &str, with_tool: bool) -> PathBuf {
    let u = |t: &str, content: &str| {
        format!("{{\"type\":\"user\",\"sessionId\":\"{sid}\",\"timestamp\":\"2099-01-01T00:00:{t}Z\",\"message\":{{\"role\":\"user\",\"content\":{content}}}}}\n")
    };
    let a = |t: &str, content: &str| {
        format!("{{\"type\":\"assistant\",\"sessionId\":\"{sid}\",\"timestamp\":\"2099-01-01T00:00:{t}Z\",\"message\":{{\"role\":\"assistant\",\"content\":[{content}]}}}}\n")
    };
    let mut text = u("00", &format!("\"{PROMPT}\""));
    if with_tool {
        text += &a("05", "{\"type\":\"tool_use\",\"id\":\"t1\",\"name\":\"Bash\",\"input\":{\"command\":\"cargo fetch --offline\"}}");
        text += &u("06", "[{\"type\":\"tool_result\",\"tool_use_id\":\"t1\",\"content\":\"ok\",\"is_error\":false}]");
    }
    text += &a("07", "{\"type\":\"text\",\"text\":\"Use the vendored sources while the mirror is down.\"}");
    let path = s.with_file_name(format!("{sid}.jsonl"));
    std::fs::write(&path, text).unwrap();
    path
}

fn stop_with(sid: &str, transcript: &PathBuf) -> String {
    format!(
        "{{\"session_id\":\"{sid}\",\"hook_event_name\":\"Stop\",\"stop_hook_active\":false,\"transcript_path\":\"{}\"}}",
        // A Windows path is full of backslashes, which JSON must escape.
        transcript.display().to_string().replace(String::from(92 as char).as_str(), "\\\\")
    )
}

#[test]
fn settle_stays_silent_after_a_plain_answer_so_the_answer_is_the_last_word() {
    let s = store("settle-qa");
    bank(&s, TITLE, Some("qqqq wwww"));
    run(Some(&s), &["prompt"], &prompt("qa", PROMPT));
    let t = transcript(&s, "qa", false);
    let (code, out) = run(Some(&s), &["settle"], &stop_with("qa", &t));
    assert_eq!(code, 0);
    assert!(out.trim().is_empty(), "nothing to judge yet, so no reminder: {out}");
    // Silence records nothing, so once the session does something the reminder can still come.
    let t = transcript(&s, "qa", true);
    let (_, later) = run(Some(&s), &["settle"], &stop_with("qa", &t));
    assert!(later.contains("instinct hit"), "after a tool call the reminder comes: {later}");
}

#[test]
fn settle_reminds_when_a_tool_ran_after_the_lesson() {
    let s = store("settle-tool");
    let (id, _) = bank(&s, TITLE, Some("qqqq wwww"));
    run(Some(&s), &["prompt"], &prompt("tool", PROMPT));
    let t = transcript(&s, "tool", true);
    let (code, out) = run(Some(&s), &["settle"], &stop_with("tool", &t));
    assert_eq!(code, 0);
    assert!(out.contains(&format!("instinct hit {id}")), "{out}");
}

#[test]
fn settle_with_an_unreadable_transcript_asks_as_before() {
    let s = store("settle-notranscript");
    let (id, _) = bank(&s, TITLE, Some("qqqq wwww"));
    run(Some(&s), &["prompt"], &prompt("gone", PROMPT));
    let missing = s.with_file_name("missing.jsonl");
    let (code, out) = run(Some(&s), &["settle"], &stop_with("gone", &missing));
    assert_eq!(code, 0);
    assert!(out.contains(&format!("instinct hit {id}")), "{out}");
}

#[test]
fn the_question_about_a_lesson_rides_on_the_next_prompt_once() {
    let s = store("followup");
    let (id, _) = bank(&s, TITLE, Some("qqqq wwww"));
    let (_, first) = run(Some(&s), &["prompt"], &prompt("f", PROMPT));
    assert!(first.contains(&id) && !first.contains("earlier in this session"), "not asked in the turn it arrives: {first}");
    let (code, next) = run(Some(&s), &["prompt"], &prompt("f", "that worked, thanks"));
    assert_eq!(code, 0);
    assert!(next.contains(&format!("instinct hit {id}")) && next.contains("earlier in this session"), "{next}");
    let (_, third) = run(Some(&s), &["prompt"], &prompt("f", "one more thing"));
    assert!(!third.contains("earlier in this session"), "asked once per session: {third}");
}

#[test]
fn no_question_once_the_lesson_has_a_verdict() {
    let s = store("followup-judged");
    let (id, _) = bank(&s, TITLE, Some("qqqq wwww"));
    run(Some(&s), &["prompt"], &prompt("j", PROMPT));
    run(Some(&s), &["hit", &id, "--note", "used it"], "");
    let (_, next) = run(Some(&s), &["prompt"], &prompt("j", "next question"));
    assert!(!next.contains("earlier in this session"), "{next}");
}