instinct-cli 0.3.7

Shared local memory for coding agents. Save a fix once and find it again in a new session or another connected tool.
//! `instinct audit` and `instinct import`: numbers on a fixture, dry run vs apply, idempotency, bad input.
use std::path::PathBuf;
use std::process::Command;

const FIXTURE: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/CLAUDE.md");

fn dir(name: &str) -> PathBuf {
    let d = std::env::temp_dir().join(format!("instinct-audit-test-{}-{}-{name}", std::process::id(), uniq()));
    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 = dir("home");
    c.env_remove("INSTINCT_STORE").env_remove("XDG_DATA_HOME").env("HOME", &home).env("LOCALAPPDATA", home.join(".local").join("share")).env_remove("INSTINCT_OLLAMA").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 bank_lines(store: &PathBuf) -> usize {
    std::fs::read_to_string(store)
        .map(|t| t.lines().filter(|l| l.contains("\"title\"")).count())
        .unwrap_or(0)
}

#[test]
fn audit_numbers_on_fixture() {
    let bytes = std::fs::metadata(FIXTURE).unwrap().len() as usize;
    let (code, out, _) = run(&["audit", FIXTURE, "--json"], None);
    assert_eq!(code, 0);
    assert!(out.contains(&format!("\"bytes\":{bytes}")), "{out}");
    assert!(out.contains(&format!("\"tokens_per_prompt\":{}", bytes.div_ceil(4))), "{out}");
    assert!(out.contains(&format!("\"tokens_per_100_prompts\":{}", bytes.div_ceil(4) * 100)), "{out}");
    assert!(out.contains("\"rules\":35"), "{out}");
    assert!(out.contains("\"sections\":10"), "{out}");
    assert!(out.contains("\"grade\":\"B\""), "{out}");
    assert!(out.contains("\"unrelated_questions\":5,\"unrelated_empty\":5"), "{out}");
    assert!(out.contains("\"own_rule_found\":35"), "{out}");
    assert!(out.contains("top 1, temporary bank"), "{out}");
    let (_, k5, _) = run(&["audit", FIXTURE, "--json", "--k", "5"], None);
    assert!(k5.contains("top 5, temporary bank"), "{k5}");
    let (_, text, _) = run(&["audit", FIXTURE], None);
    assert!(text.contains("about 4 bytes per token"));
    assert!(text.contains("A <= 400, B <= 1000, C <= 2500, D <= 5000"));
    let (_, share, _) = run(&["audit", "--share", FIXTURE], None);
    assert_eq!(share.trim().lines().count(), 1, "{share}");
    assert!(share.contains("grade B"), "{share}");
    let (_, help, _) = run(&["audit", "--help"], None);
    assert!(help.contains("A <= 400"));
}

#[test]
fn import_dry_run_apply_and_idempotent() {
    let d = dir("import");
    let store = d.join("bank.hxdb");
    let (code, out, _) = run(&["import", FIXTURE], Some(&store));
    assert_eq!(code, 0);
    assert!(out.contains("would bank: 35 new, 0 already banked"), "{out}");
    assert!(!store.exists(), "dry run must not write");

    let (code, out, _) = run(&["import", FIXTURE, "--apply", "--project", "acme"], Some(&store));
    assert_eq!(code, 0, "{out}");
    assert!(out.contains("banked: 35 new, 0 already banked"), "{out}");
    assert_eq!(bank_lines(&store), 35);

    let (code, out, _) = run(&["import", FIXTURE, "--apply", "--project", "acme"], Some(&store));
    assert_eq!(code, 0);
    assert!(out.contains("banked: 0 new, 35 already banked"), "{out}");
    assert_eq!(bank_lines(&store), 35, "second import must not duplicate");

    // dry run against a populated store reports what is already there
    let (_, out, _) = run(&["import", FIXTURE, "--project", "acme"], Some(&store));
    assert!(out.contains("would bank: 0 new, 35 already banked"), "{out}");

    // the lesson is recallable and carries its provenance
    let mut c = Command::new(env!("CARGO_BIN_EXE_instinct"));
    let o = c
        .env("INSTINCT_STORE", &store)
        .env("INSTINCT_PROJECT", "acme")
        .env_remove("INSTINCT_OLLAMA")
        .args(["recall", "--q", "money stored as integer cents"])
        .output()
        .unwrap();
    let text = String::from_utf8_lossy(&o.stdout);
    assert!(text.contains("Money is stored as integer cents"), "{text}");
    assert!(text.contains("Imported from") && text.contains("CLAUDE.md line 30"), "{text}");
}

#[test]
fn apply_without_a_store_banks_into_the_default_one() {
    let home = dir("apply-home");
    let o = Command::new(env!("CARGO_BIN_EXE_instinct"))
        .args(["import", FIXTURE, "--apply"])
        .env_remove("INSTINCT_STORE")
        .env_remove("XDG_DATA_HOME")
        .env("HOME", &home)
        .env("LOCALAPPDATA", home.join(".local").join("share"))
        .output()
        .unwrap();
    assert_eq!(o.status.code(), Some(0), "{}", String::from_utf8_lossy(&o.stderr));
    assert!(bank_lines(&home.join(".local/share/instinct/bank.hxdb")) > 0);
}

#[test]
fn missing_and_empty_files() {
    let d = dir("bad");
    let (code, _, err) = run(&["audit", d.join("nope.md").to_str().unwrap()], None);
    assert_eq!(code, 2);
    assert!(err.contains("nope.md"), "{err}");
    let empty = d.join("empty.md");
    std::fs::write(&empty, "  \n\n").unwrap();
    for cmd in ["audit", "import"] {
        let (code, _, err) = run(&[cmd, empty.to_str().unwrap()], None);
        assert_eq!(code, 2);
        assert!(err.contains("empty"), "{err}");
    }
    // run in an empty folder: the repo root has its own AGENTS.md
    let o = Command::new(env!("CARGO_BIN_EXE_instinct")).arg("audit").current_dir(&d).env("HOME", &d).output().unwrap();
    let (code, err) = (o.status.code().unwrap_or(-1), String::from_utf8_lossy(&o.stderr).into_owned());
    assert_eq!(code, 2);
    assert!(err.contains("no memory file found") && err.contains("instinct audit path/to/CLAUDE.md"), "{err}");
    // a file with only headings and code has no rules but still audits
    let none = d.join("none.md");
    std::fs::write(&none, "# Only a heading\n\n```\n- code\n```\n").unwrap();
    let (code, out, _) = run(&["audit", none.to_str().unwrap()], None);
    assert_eq!(code, 0);
    assert!(out.contains("0 rules in 1 sections") && out.contains("nothing to measure"), "{out}");
}

/// A number no other call in this test process has seen, so parallel tests never share a folder.
fn uniq() -> usize {
    static N: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
    N.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
}