instinct-cli 0.3.10

Shared local memory for coding agents. Save a fix once and find it again in a new session or another connected tool.
//! `instinct learn`: tripwires and fixes proposed from transcripts. Fixture transcripts are written in Claude Code's JSONL
//! shape into a temp folder; nothing reads a real home folder.
use std::path::{Path, PathBuf};
use std::process::{Command, Output};

struct Box_ {
    root: PathBuf,
    n: std::cell::Cell<usize>,
}

impl Box_ {
    fn new(name: &str) -> Box_ {
        let root = std::env::temp_dir().join(format!("instinct-learn-test-{}-{name}", std::process::id()));
        let _ = std::fs::remove_dir_all(&root);
        std::fs::create_dir_all(root.join("t")).unwrap();
        std::fs::create_dir_all(root.join("home")).unwrap();
        Box_ { root, n: std::cell::Cell::new(0) }
    }
    fn dir(&self) -> PathBuf {
        self.root.join("t")
    }
    fn bank(&self) -> PathBuf {
        self.root.join("bank.hxdb")
    }
    /// One session: `steps` are (command, worked). A user line comes first, so each session is one turn.
    fn session(&self, steps: &[(&str, bool)]) -> PathBuf {
        let k = self.n.get();
        self.n.set(k + 1);
        let mut lines = vec![r#"{"type":"user","message":{"role":"user","content":"please run the thing"}}"#.to_string()];
        for (i, (cmd, ok)) in steps.iter().enumerate() {
            let id = format!("t{k}x{i}");
            lines.push(format!(
                r#"{{"type":"assistant","message":{{"role":"assistant","content":[{{"type":"tool_use","id":"{id}","name":"Bash","input":{{"command":"{}"}}}}]}}}}"#,
                cmd.replace('\\', "\\\\").replace('"', "\\\"")
            ));
            lines.push(format!(
                r#"{{"type":"user","message":{{"role":"user","content":[{{"type":"tool_result","tool_use_id":"{id}","is_error":{},"content":"{}"}}]}}}}"#,
                !ok,
                if *ok { "ok" } else { "error: failed" }
            ));
        }
        let p = self.dir().join(format!("s{k}.jsonl"));
        std::fs::write(&p, lines.join("\n") + "\n").unwrap();
        p
    }
    /// A session where the user corrects the agent right after `cmd`.
    fn corrected(&self, cmd: &str) -> PathBuf {
        let k = self.n.get();
        self.n.set(k + 1);
        let id = format!("c{k}");
        let lines = [
            r#"{"type":"user","message":{"role":"user","content":"deploy it"}}"#.to_string(),
            format!(r#"{{"type":"assistant","message":{{"role":"assistant","content":[{{"type":"tool_use","id":"{id}","name":"Bash","input":{{"command":"{cmd}"}}}}]}}}}"#),
            format!(r#"{{"type":"user","message":{{"role":"user","content":[{{"type":"tool_result","tool_use_id":"{id}","is_error":false,"content":"ok"}}]}}}}"#),
            r#"{"type":"user","message":{"role":"user","content":"no, don't do that, that's wrong"}}"#.to_string(),
        ];
        let p = self.dir().join(format!("s{k}.jsonl"));
        std::fs::write(&p, lines.join("\n") + "\n").unwrap();
        p
    }
    fn learn(&self, args: &[&str]) -> Output {
        Command::new(env!("CARGO_BIN_EXE_instinct"))
            .arg("learn")
            .arg(self.dir())
            .args(args)
            .env("HOME", self.root.join("home"))
            .env("INSTINCT_STORE", self.bank())
            .output()
            .unwrap()
    }
    /// A pile of ordinary commands that worked the first time: the replay denominator.
    fn quiet_history(&self, sessions: usize) {
        for _ in 0..sessions {
            self.session(&[("ls -la", true), ("git status", true), ("cargo build", true), ("pgrep -A -f svc", true), ("npm ci", true)]);
        }
    }
}

impl Drop for Box_ {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.root);
    }
}

fn out(o: &Output) -> String {
    String::from_utf8_lossy(&o.stdout).into_owned()
}

fn history(b: &Box_) {
    // The same flag edit in two sessions, a subcommand swap in two, a one-off, and a path edit that must not generalise.
    b.session(&[("pgrep -f myservice", false), ("pgrep -A -f myservice", true)]);
    b.session(&[("pgrep -f otherservice", false), ("pgrep -A -f otherservice", true)]);
    b.session(&[("npm i", false), ("npm ci", true)]);
    b.session(&[("npm i --silent", false), ("npm ci --silent", true)]);
    b.session(&[("make -j8", false), ("make -j8 -k", true)]);
    b.session(&[("cat /etc/hosts", false), ("cat /etc/hostname", true)]);
    b.session(&[("cat /var/log/a", false), ("cat /var/log/b", true)]);
    b.quiet_history(60);
}

#[test]
fn a_repeated_edit_becomes_a_tripwire_with_a_fix_and_counts_only() {
    let b = Box_::new("proposals");
    history(&b);
    let o = b.learn(&[]);
    assert!(o.status.success(), "{}", String::from_utf8_lossy(&o.stderr));
    let r = out(&o);
    assert!(r.contains("tripwire  cmd:pgrep -f !-A"), "{r}");
    assert!(r.contains("fix       add -A"), "{r}");
    assert!(r.contains("tripwire  cmd:npm i"), "{r}");
    assert!(r.contains("fix       ci instead of i"), "{r}");
    assert!(r.contains("evidence  2 retries in 2 sessions,"), "{r}");
    assert!(r.contains("would bank: 2 as candidate lessons (dry run, add --apply to bank)"), "{r}");
    // One-offs and argument edits never become proposals, and no transcript text leaks.
    assert!(!r.contains("make -j8") && !r.contains("/etc/host") && !r.contains("myservice") && !r.contains("otherservice"), "{r}");
    assert!(!b.bank().exists(), "a dry run writes nothing");
}

#[test]
fn replay_reports_the_false_alarm_rate_and_the_failures_caught() {
    let b = Box_::new("replay");
    history(&b);
    let r = out(&b.learn(&["--json"]));
    assert!(r.contains("\"retried_in_corrected_form\":7"), "{r}");
    assert!(r.contains("\"proposals\":2") && r.contains("\"with_fix\":2"), "{r}");
    assert!(r.contains("\"too_few_uses\":1"), "make -j8 -k was seen once: {r}");
    assert!(r.contains("\"false_alarms\":0"), "{r}");
    assert!(r.contains("\"false_alarm_pct\":0.00,\"limit_pct\":1"), "{r}");
    assert!(r.contains("\"failures_caught\":4"), "both tripwires catch their two failures: {r}");
    assert!(r.contains("\"tripwire\":\"cmd:pgrep -f !-A\",\"fix\":\"add -A\""), "{r}");
}

#[test]
fn a_pattern_that_would_fire_on_commands_that_worked_is_dropped() {
    let b = Box_::new("noisy");
    // `npm i` swapped for `npm ci` twice, but `npm i` worked first time 40 times in 100: far over 1%.
    b.session(&[("npm i", false), ("npm ci", true)]);
    b.session(&[("npm i", false), ("npm ci", true)]);
    for _ in 0..40 {
        b.session(&[("npm i", true)]);
    }
    for _ in 0..60 {
        b.session(&[("ls", true)]);
    }
    let r = out(&b.learn(&["--json"]));
    assert!(r.contains("\"proposals\":0") && r.contains("\"dropped_for_false_alarms\":1"), "{r}");
    let text = out(&b.learn(&[]));
    assert!(text.contains("nothing repeated often enough yet"), "{text}");
}

#[test]
fn repeated_corrections_after_a_command_propose_a_tripwire_without_a_fix() {
    let b = Box_::new("corrections");
    b.corrected("terraform apply");
    b.corrected("terraform apply -auto-approve");
    b.quiet_history(60);
    let r = out(&b.learn(&[]));
    assert!(r.contains("`terraform apply` was corrected afterwards"), "{r}");
    assert!(r.contains("tripwire  cmd:terraform apply"), "{r}");
    assert!(r.contains("2 corrections in 2 sessions"), "{r}");
    assert!(!r.contains("   fix "), "a correction has no fix: {r}");
}

#[test]
fn apply_banks_candidate_lessons_once() {
    let b = Box_::new("apply");
    history(&b);
    let o = b.learn(&["--apply", "--project", "apply"]);
    assert!(o.status.success(), "{}", String::from_utf8_lossy(&o.stderr));
    assert!(out(&o).contains("banked: 2 as candidate lessons (0 already in the bank)"), "{}", out(&o));
    let bank = std::fs::read_to_string(b.bank()).unwrap();
    assert!(bank.contains("cmd:pgrep -f !-A") && bank.contains("fix:add -A") && bank.contains("cmd:npm i"), "{bank}");
    assert!(bank.contains("\"mined\"") || bank.contains("mined"), "banked as a candidate (source mined): {bank}");
    assert!(!bank.contains("myservice"), "no transcript text in the bank");
    let again = b.learn(&["--apply", "--project", "apply"]);
    assert!(out(&again).contains("banked: 0 as candidate lessons (2 already in the bank)"), "{}", out(&again));
}

#[test]
fn the_days_window_leaves_out_old_transcripts() {
    let b = Box_::new("days");
    history(&b);
    // With no paths, learn reads the home folder; point it at fixture projects there and age the files.
    let proj = b.root.join("home/.claude/projects/p1");
    std::fs::create_dir_all(&proj).unwrap();
    for f in std::fs::read_dir(b.dir()).unwrap() {
        let f = f.unwrap().path();
        std::fs::copy(&f, proj.join(f.file_name().unwrap())).unwrap();
    }
    let run = |days: &str| {
        let o = Command::new(env!("CARGO_BIN_EXE_instinct"))
            .args(["learn", "--json", "--days", days])
            .env("HOME", b.root.join("home"))
            .env("INSTINCT_STORE", b.bank())
            .output()
            .unwrap();
        out(&o)
    };
    assert!(run("30").contains("\"proposals\":2"), "{}", run("30"));
    let old = std::time::SystemTime::now() - std::time::Duration::from_secs(90 * 86_400);
    for f in std::fs::read_dir(&proj).unwrap() {
        std::fs::File::options().write(true).open(f.unwrap().path()).unwrap().set_modified(old).unwrap();
    }
    let r = run("30");
    assert!(r.contains("\"transcripts\":0") && r.contains("\"proposals\":0"), "{r}");
    assert!(run("120").contains("\"proposals\":2"));
}

#[test]
fn credentials_are_never_read_into_a_proposal() {
    let b = Box_::new("secrets");
    for _ in 0..2 {
        b.session(&[("ssh -i ~/.ssh/id_ed25519 host ls", false), ("ssh -o StrictHostKeyChecking=no -i ~/.ssh/id_ed25519 host ls", true)]);
    }
    b.quiet_history(60);
    let r = out(&b.learn(&[]));
    assert!(r.contains("would bank") || r.contains("nothing repeated"), "{r}");
    assert!(!r.contains("ssh") && !r.contains("id_ed25519"), "{r}");
}

#[test]
fn bad_options_print_usage_and_help_works() {
    let b = Box_::new("usage");
    let o = Command::new(env!("CARGO_BIN_EXE_instinct")).args(["learn", "--bogus"]).env("HOME", b.root.join("home")).output().unwrap();
    assert!(!o.status.success());
    assert!(String::from_utf8_lossy(&o.stderr).contains("usage: instinct learn"), "{}", String::from_utf8_lossy(&o.stderr));
    let h = Command::new(env!("CARGO_BIN_EXE_instinct")).args(["learn", "--help"]).output().unwrap();
    assert!(h.status.success() && out(&h).contains("Only flags and subcommand words are used"), "{}", out(&h));
    let _ = Path::new("");
}

#[test]
fn a_different_command_after_a_failure_is_not_a_retry() {
    let b = Box_::new("notretry");
    for _ in 0..3 {
        b.session(&[("cd app && make test", false), ("cd lib && cargo build --release", true), ("make test -j4", true)]);
    }
    let r = out(&b.learn(&["--json"]));
    // Neither later command is the failed one again (different first word), so nothing counts as a retry.
    assert!(r.contains("\"failed\":3") && r.contains("\"retried_in_corrected_form\":0"), "{r}");
}