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 eval` on a fixture bank with crafted hits, misses, deliveries and meter lines.
use std::fs;
use std::io::Write;
use std::path::PathBuf;
use std::process::{Command, Stdio};
use std::time::{SystemTime, UNIX_EPOCH};

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

const DAY: u64 = 86_400;

fn now() -> u64 {
    SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs()
}

fn run(store: &PathBuf, args: &[&str], stdin: &str) -> (i32, String, String) {
    let mut child = Command::new(bin())
        .args(args)
        .env("INSTINCT_STORE", store)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .unwrap();
    child.stdin.take().unwrap().write_all(stdin.as_bytes()).unwrap();
    let o = child.wait_with_output().unwrap();
    (o.status.code().unwrap(), String::from_utf8(o.stdout).unwrap(), String::from_utf8(o.stderr).unwrap())
}

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

fn append(path: &PathBuf, text: &str) {
    let mut f = fs::OpenOptions::new().create(true).append(true).open(path).unwrap();
    f.write_all(text.as_bytes()).unwrap();
}

fn mark(store: &PathBuf, kind: &str, id: &str, days_ago: u64) {
    append(store, &format!("{{\"kind\":\"{kind}\",\"id\":\"{id}\",\"ts\":{},\"note\":\"\"}}\n", now() - days_ago * DAY));
}

fn deliver(store: &PathBuf, sid: &str, id: &str, days_ago: u64) {
    let p = PathBuf::from(format!("{}.sessions", store.display()));
    append(&p, &format!("{}\t{sid}\tD\t{id}\n", now() - days_ago * DAY));
}

fn meter_line(store: &PathBuf, days_ago: u64, lessons: u64, bytes: u64, whole: u64) {
    let p = PathBuf::from(format!("{}.meter", store.display()));
    append(&p, &format!("{} prompt {lessons} {bytes} {whole} 900\n", now() - days_ago * DAY));
}

/// Moves a lesson's `ts` back so it is past the one-day grace and "banked a while ago".
fn age_lesson(store: &PathBuf, id: &str, days_ago: u64) {
    let text = fs::read_to_string(store).unwrap();
    let out: Vec<String> = text
        .lines()
        .map(|l| {
            if l.contains("\"kind\":\"discovery\"") && l.contains(&format!("\"id\":\"{id}\"")) {
                let i = l.find("\"ts\":").unwrap() + 5;
                let j = i + l[i..].find(',').unwrap();
                format!("{}{}{}", &l[..i], now() - days_ago * DAY, &l[j..])
            } else {
                l.to_owned()
            }
        })
        .collect();
    fs::write(store, out.join("\n") + "\n").unwrap();
}

struct Fx {
    store: PathBuf,
    paid: String,
    misled: String,
    dropped: String,
    unjudged: String,
    never: String,
    dup_a: String,
    dup_b: String,
    retracted: String,
}

fn fixture(name: &str) -> Fx {
    let dir = std::env::temp_dir().join(format!("instinct-eval-it-{}-{}-{name}", std::process::id(), uniq()));
    let _ = fs::remove_dir_all(&dir);
    fs::create_dir_all(&dir).unwrap();
    let store = dir.join("bank.jsonl");
    let paid = bank(&store, "Terraform plan hangs on staging", "running terraform plan against the staging cluster hangs");
    let misled = bank(&store, "Redis flush fixes cache", "stale cache entries after the deploy on production");
    let dropped = bank(&store, "Rebase before merge", "merging a long lived feature branch into main");
    let unjudged = bank(&store, "Docker prune frees disk", "docker images fill the build machine disk");
    let never = bank(&store, "Kubernetes ingress timeout", "ingress controller returns gateway timeout under load");
    let dup_a = bank(&store, "Restart replica after failover", "restarting the postgres replica after the primary failover");
    let dup_b = bank(&store, "Postgres replica restart", "restart the postgres replica after primary failover happens");
    let retracted = bank(&store, "Lint hook slow", "pre commit lint hook takes minutes on monorepo");
    for id in [&paid, &misled, &dropped, &unjudged, &never, &dup_a, &dup_b, &retracted] {
        age_lesson(&store, id, 20);
    }
    // paid: 3 hits in the last week, one hit 40 days ago (outside a 30d window)
    for d in [1, 2, 3] {
        mark(&store, "hit", &paid, d);
    }
    mark(&store, "hit", &paid, 40);
    // misled: two misses, no hits
    mark(&store, "miss", &misled, 1);
    mark(&store, "miss", &misled, 2);
    // dropped: earned strength long ago, then four misses and a hit this week
    mark(&store, "hit", &dropped, 40);
    mark(&store, "hit", &dropped, 39);
    mark(&store, "hit", &dropped, 3);
    for d in [1, 1, 2, 2] {
        mark(&store, "miss", &dropped, d);
    }
    // retracted: a hit that was retracted must not count
    mark(&store, "hit", &retracted, 1);
    append(&store, &format!("{{\"kind\":\"retract\",\"of\":\"hit\",\"id\":\"{retracted}\",\"ts\":{}}}\n", now() - DAY / 2));
    // deliveries
    for (sid, d) in [("s1", 3), ("s2", 2), ("s3", 1)] {
        deliver(&store, sid, &paid, d);
        deliver(&store, sid, &unjudged, d);
    }
    deliver(&store, "s4", &misled, 2);
    deliver(&store, "s4", &dropped, 2);
    deliver(&store, "s5", &retracted, 1);
    // meter: two lookups in the last week, one 20 days ago
    meter_line(&store, 1, 1, 400, 6000);
    meter_line(&store, 2, 1, 500, 6000);
    meter_line(&store, 20, 0, 0, 6000);
    Fx { store, paid, misled, dropped, unjudged, never, dup_a, dup_b, retracted }
}

fn eval(f: &Fx, args: &[&str]) -> String {
    let mut a = vec!["eval"];
    a.extend_from_slice(args);
    let (code, out, err) = run(&f.store, &a, "");
    assert_eq!(code, 0, "{out}{err}");
    assert_eq!(err, "", "stderr must stay empty");
    out
}

fn section<'a>(out: &'a str, title: &str) -> &'a str {
    let i = out.find(&format!("\n{title} (")).unwrap_or_else(|| panic!("no section {title} in\n{out}")) + 1;
    let rest = &out[i..];
    let end = rest[1..].find("\n\n").map(|e| e + 1).unwrap_or(rest.len());
    &rest[..end]
}

#[test]
fn paid_off_lists_hits_rate_and_proven() {
    let f = fixture("paid");
    let out = eval(&f, &["--since", "30d"]);
    let s = section(&out, "Paid off");
    assert!(s.starts_with("Paid off (2)"), "{s}");
    let line = s.lines().position(|l| l.contains(&f.paid)).expect(&s);
    let detail = s.lines().nth(line + 1).unwrap();
    assert!(detail.contains("3 hits") && detail.contains("0 misses") && detail.contains("100% hit rate"), "{detail}");
    // 4 hits ever, strength 0.83: proven in use even though the 40 day old hit is outside the window
    assert!(detail.contains("proven in use"), "{detail}");
    // the retracted hit does not count
    assert!(!s.contains(&f.retracted), "{s}");
}

#[test]
fn misled_lists_quarantine_candidates_and_strength_drops() {
    let f = fixture("misled");
    let out = eval(&f, &["--since", "30d"]);
    let s = section(&out, "Misled");
    assert!(s.contains(&f.misled) && s.contains("quarantine: 2 misses and no hits"), "{s}");
    assert!(s.contains(&f.dropped) && s.contains("strength fell from 0.75 to 0.44"), "{s}");
    assert!(s.contains("Nothing was changed"), "{s}");
}

#[test]
fn delivered_but_never_judged_gives_exact_commands() {
    let f = fixture("unjudged");
    let out = eval(&f, &[]);
    let s = section(&out, "Delivered but never judged");
    assert!(s.starts_with("Delivered but never judged (2)"), "{s}");
    assert!(s.contains("delivered 3 times"), "{s}");
    assert!(s.contains(&format!("instinct hit {} --note '…'", f.unjudged)), "{s}");
    assert!(s.contains(&format!("instinct miss {} --note '…'", f.unjudged)), "{s}");
    // delivered lessons that were judged or retracted-to-nothing: the retracted one has a delivery and no standing outcome
    assert!(s.contains(&f.retracted), "{s}");
}

#[test]
fn never_fired_shows_when_and_a_dream_check() {
    let f = fixture("never");
    let out = eval(&f, &[]);
    let s = section(&out, "Never fired");
    assert!(s.contains(&f.never), "{s}");
    assert!(s.contains("when: ingress controller returns gateway timeout under load"), "{s}");
    assert!(
        s.contains("instinct dream --q \"ingress controller returns gateway timeout under load\" --changed \"<a reworded version>\""),
        "{s}"
    );
    // delivered or judged lessons are not listed
    assert!(!s.contains(&f.paid) && !s.contains(&f.unjudged), "{s}");
}

#[test]
fn near_duplicates_are_found_and_a_merge_is_suggested() {
    let f = fixture("dups");
    let out = eval(&f, &[]);
    let s = section(&out, "Near-duplicates");
    assert!(s.starts_with("Near-duplicates (1)"), "{s}");
    assert!(s.contains(&f.dup_a) && s.contains(&f.dup_b), "{s}");
    assert!(s.contains("--state quarantined --reason \"duplicate of"), "{s}");
}

#[test]
fn savings_reuse_the_meter_numbers_and_follow_the_window() {
    let f = fixture("savings");
    let week = eval(&f, &["--since", "7d"]);
    assert!(week.contains("Savings, the last 7 days") && week.contains("lookups served       2 "), "{week}");
    let month = eval(&f, &["--since", "30d"]);
    assert!(month.contains("lookups served       3 "), "{month}");
    // the same numbers `instinct stats` prints
    let (_, stats, _) = run(&f.store, &["stats", "--since", "7d"], "");
    assert!(stats.contains("kept out of prompts  11,100 bytes"), "{stats}");
    assert!(week.contains("kept out of prompts  11,100 bytes"), "{week}");
}

#[test]
fn since_window_changes_what_counts() {
    let f = fixture("window");
    let week = eval(&f, &["--since", "7d"]);
    // within 7 days the old hits are out: paid has 3 hits either way, dropped has 1 hit and 4 misses
    assert!(section(&week, "Paid off").contains("3 hits"), "{week}");
    let all = eval(&f, &["--since", "all"]);
    assert!(section(&all, "Paid off").contains("4 hits"), "{all}");
    assert!(all.starts_with("Instinct eval, all recorded time"), "{all}");
    let (code, _, err) = run(&f.store, &["eval", "--since", "soon"], "");
    assert_eq!(code, 2);
    assert!(err.contains("--since takes"), "{err}");
}

#[test]
fn next_three_actions_are_runnable_and_ranked() {
    let f = fixture("actions");
    let out = eval(&f, &[]);
    let s = &out[out.find("Next three actions").unwrap()..];
    let cmds: Vec<&str> = s.lines().filter(|l| l.trim_start().starts_with("instinct ")).collect();
    assert_eq!(cmds.len(), 3, "{s}");
    assert!(cmds[0].trim() == "instinct eval --apply-quarantine", "{s}");
    assert!(cmds[1].contains(&format!("instinct hit {}", f.unjudged)), "{s}");
    assert!(cmds[2].contains("instinct review"), "{s}");
}

#[test]
fn json_has_every_section_and_is_balanced() {
    let f = fixture("json");
    let out = eval(&f, &["--json"]);
    let j = out.trim();
    for key in [
        "\"schema\":\"instinct-eval/1\"", "\"since\":\"30d\"", "\"paid_off\":[", "\"misled\":[", "\"to_quarantine\":[",
        "\"delivered_never_judged\":[", "\"never_fired\":[", "\"near_duplicates\":[", "\"savings\":{", "\"next_actions\":[",
        "\"applied_quarantine\":[]", "\"hit_rate_percent\":100", "\"lookups\":3",
    ] {
        assert!(j.contains(key), "missing {key} in {j}");
    }
    assert!(j.starts_with('{') && j.ends_with('}') && !j.contains('\n'), "{j}");
    let depth = j.chars().fold((0i32, false, false), |(d, in_s, esc), c| match (in_s, esc, c) {
        (true, true, _) => (d, true, false),
        (true, false, '\\') => (d, true, true),
        (true, false, '"') => (d, false, false),
        (false, _, '"') => (d, true, false),
        (false, _, '{' | '[') => (d + 1, false, false),
        (false, _, '}' | ']') => (d - 1, false, false),
        _ => (d, in_s, false),
    });
    assert_eq!(depth.0, 0, "{j}");
}

#[test]
fn eval_never_changes_the_bank() {
    let f = fixture("readonly");
    let files = |s: &PathBuf| {
        ["", ".sessions", ".meter"].map(|ext| fs::read(PathBuf::from(format!("{}{ext}", s.display()))).unwrap())
    };
    let before = files(&f.store);
    for args in [vec![], vec!["--json"], vec!["--since", "7d"], vec!["--since", "all", "--json"]] {
        eval(&f, &args);
    }
    assert!(files(&f.store) == before, "eval changed a store file");
}

#[test]
fn apply_quarantine_needs_the_flag_prints_what_it_did_and_is_idempotent() {
    let f = fixture("apply");
    let out = eval(&f, &["--apply-quarantine"]);
    assert!(out.contains("Applied --apply-quarantine"), "{out}");
    assert!(out.contains(&format!("quarantined {}", f.misled)) && out.contains(&format!("quarantined {}", f.dropped)), "{out}");
    let journal = fs::read_to_string(&f.store).unwrap();
    assert_eq!(journal.matches("\"kind\":\"review\"").count(), 2, "{journal}");
    // quarantined lessons are out of the report, the rest is untouched
    let again = eval(&f, &[]);
    assert!(!section(&again, "Misled").contains(&f.misled), "{again}");
    assert!(!again.contains("Applied"), "{again}");
    assert!(section(&again, "Paid off").contains(&f.paid), "{again}");
    let third = eval(&f, &["--apply-quarantine"]);
    assert!(!third.contains("Applied"), "{third}");
    assert_eq!(fs::read_to_string(&f.store).unwrap().matches("\"kind\":\"review\"").count(), 2);
}

#[test]
fn empty_bank_and_missing_record_are_plain() {
    let dir = std::env::temp_dir().join(format!("instinct-eval-it-{}-{}-empty", std::process::id(), uniq()));
    let _ = fs::remove_dir_all(&dir);
    fs::create_dir_all(&dir).unwrap();
    let store = dir.join("bank.jsonl");
    let (code, out, _) = run(&store, &["eval"], "");
    assert_eq!(code, 0);
    assert!(out.contains("The bank is empty"), "{out}");
    // a bank with no delivery record does not claim every lesson never fired
    let id = bank(&store, "One lesson", "some situation about frobnicating widgets");
    age_lesson(&store, &id, 10);
    let (_, out, _) = run(&store, &["eval"], "");
    assert!(out.contains("Never fired (0)") && out.contains("no recorded deliveries"), "{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)
}