instinct-cli 0.3.9

Shared local memory for coding agents. Save a fix once and find it again in a new session or another connected tool.
//! The savings meter end to end: accounting, opt-out, identical output, corrupt file, windows.
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-meter-it-{}-{}-{name}", std::process::id(), uniq()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    dir.join("bank.hxdb")
}

fn meter_file(s: &PathBuf) -> PathBuf {
    PathBuf::from(format!("{}.meter", s.display()))
}

fn bank(s: &PathBuf, n: usize) {
    for i in 0..n {
        let st = Command::new(bin())
            .env("INSTINCT_STORE", s)
            .args(["bank", "--title", &format!("lesson {i}"), "--when", &format!("running tool{i} on the staging cluster"), "--found", "it hangs", "--how", "restart the worker first", "--evidence", "seen twice"])
            .output()
            .unwrap();
        assert!(st.status.success());
    }
}

fn run(s: &PathBuf, meter_off: bool, args: &[&str], stdin: Option<&str>) -> (String, String) {
    let mut c = Command::new(bin());
    c.args(args).env("INSTINCT_STORE", s).env_remove("INSTINCT_METER");
    if meter_off {
        c.env("INSTINCT_METER", "0");
    }
    let mut child = c.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap();
    if let Some(t) = stdin {
        child.stdin.take().unwrap().write_all(t.as_bytes()).ok();
    }
    drop(child.stdin.take());
    let o = child.wait_with_output().unwrap();
    (String::from_utf8(o.stdout).unwrap(), String::from_utf8(o.stderr).unwrap())
}

const PROMPT: &str = "{\"prompt\":\"running tool3 on the staging cluster\",\"cwd\":\"/tmp\"}";
const GUARD: &str = "{\"hook_event_name\":\"PreToolUse\",\"tool_name\":\"Bash\",\"cwd\":\"/tmp\",\"tool_input\":{\"command\":\"running tool2 on the staging cluster\"}}";

#[test]
fn meter_on_and_off_return_identical_output() {
    let s = store("ident");
    bank(&s, 5);
    let _ = std::fs::remove_file(meter_file(&s));
    for off in [false, true] {
        let _ = off;
    }
    let calls: Vec<(&[&str], Option<&str>)> = vec![
        (&["recall", "--q", "running tool1 on the staging cluster"], None),
        (&["recall", "--q", "nothing like it zzz"], None),
        (&["decide", "--q", "running tool4 on the staging cluster"], None),
        (&["prompt"], Some(PROMPT)),
        (&["guard"], Some(GUARD)),
    ];
    for (args, stdin) in calls {
        let on = run(&s, false, args, stdin);
        let off = run(&s, true, args, stdin);
        assert_eq!(on, off, "{args:?}");
    }
}

#[test]
fn every_path_records_counts_and_opt_out_records_nothing() {
    let s = store("paths");
    bank(&s, 4);
    let _ = std::fs::remove_file(meter_file(&s));
    run(&s, true, &["recall", "--q", "running tool1 on the staging cluster"], None);
    assert!(!meter_file(&s).exists(), "INSTINCT_METER=0 must not create the file");

    run(&s, false, &["recall", "--q", "running tool1 on the staging cluster", "--k", "2"], None);
    run(&s, false, &["recall", "--q", "zzzz qqqq"], None);
    run(&s, false, &["decide", "--q", "running tool2 on the staging cluster"], None);
    run(&s, false, &["prompt"], Some(PROMPT));
    run(&s, false, &["guard"], Some(GUARD));
    let text = std::fs::read_to_string(meter_file(&s)).unwrap();
    let rows: Vec<Vec<&str>> = text.lines().map(|l| l.split(' ').collect()).collect();
    let kinds: Vec<&str> = rows.iter().map(|r| r[1]).collect();
    assert_eq!(kinds, ["recall", "recall", "decide", "prompt", "guard"]);
    assert!(rows.iter().all(|r| r.len() == 6 && r.iter().enumerate().all(|(i, w)| i == 1 || w.parse::<u64>().is_ok())));
    assert!(!text.contains("tool") && !text.contains("staging"), "no query or lesson text");
    assert!(rows[0][2].parse::<u32>().unwrap() >= 1);
    assert_eq!(rows[1][2], "0", "a miss is recorded as zero lessons");
    let whole: u64 = rows[0][4].parse().unwrap();
    let delivered: u64 = rows[0][3].parse().unwrap();
    assert!(whole >= delivered && whole > 0);
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        assert_eq!(std::fs::metadata(meter_file(&s)).unwrap().permissions().mode() & 0o777, 0o600);
    }
}

#[test]
fn stats_reports_json_share_and_survives_a_corrupt_meter() {
    let s = store("stats");
    bank(&s, 3);
    run(&s, false, &["recall", "--q", "running tool1 on the staging cluster"], None);
    run(&s, false, &["recall", "--q", "zzzz qqqq"], None);
    let (plain, err) = run(&s, false, &["stats"], None);
    assert!(err.is_empty());
    assert!(plain.starts_with("store "), "{plain}");
    assert!(plain.contains("lookups served       2 (1 found a lesson, 1 found nothing)"), "{plain}");
    assert!(plain.contains("about 4 bytes per token"), "{plain}");
    let (json, _) = run(&s, false, &["stats", "--json", "--since", "30d"], None);
    assert!(json.contains("\"lookups\":2") && json.contains("\"found\":1") && json.contains("\"since\":\"30d\""), "{json}");
    let (share, _) = run(&s, false, &["stats", "--share"], None);
    assert!(share.starts_with("Instinct kept about ") && share.contains("estimate") && share.contains("2 lookups"), "{share}");
    assert!(run(&s, false, &["stats", "--since", "bogus"], None).0.is_empty());

    std::fs::write(meter_file(&s), b"\x00\xff junk\n1 recall 9\n").unwrap();
    let (after, err) = run(&s, false, &["stats"], None);
    assert!(err.is_empty() && after.contains("no metered lookups"), "{after}");
    std::fs::remove_file(meter_file(&s)).unwrap();
    assert!(run(&s, false, &["stats"], None).0.contains("no metered lookups"));
    // old lines fall outside a 7-day window
    std::fs::write(meter_file(&s), "1000 recall 1 10 100 5\n").unwrap();
    assert!(run(&s, false, &["stats", "--since", "7d"], None).0.contains("no metered lookups"));
    assert!(run(&s, false, &["stats", "--since", "all"], None).0.contains("lookups served       1"));
}

#[test]
fn an_unwritable_meter_never_fails_the_lookup() {
    let s = store("unwritable");
    bank(&s, 2);
    // a directory where the meter file should be: every append fails
    std::fs::create_dir(meter_file(&s)).unwrap();
    let (out, err) = run(&s, false, &["recall", "--q", "running tool1 on the staging cluster"], None);
    assert!(out.contains("lesson") && err.is_empty(), "{out} {err}");
}

/// 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)
}