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.
#![cfg(unix)]
//! The `sed -i` and `git branch -D` tripwires stay quiet where the risk is not real, and only there: tracked and
//! unmodified files, a branch whose commits live on elsewhere. Real repositories, the real `instinct guard`.
use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};

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

fn git(cwd: &Path, args: &[&str]) {
    let ok = Command::new("git")
        .args(["-c", "user.name=t", "-c", "user.email=t@t"])
        .args(args)
        .current_dir(cwd)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status()
        .unwrap()
        .success();
    assert!(ok, "git {args:?}");
}

/// A bank with the starter tripwires, and a guard runner for a command in a directory: true when a tripwire is shown.
struct Guard {
    bank: PathBuf,
}

impl Guard {
    fn new(name: &str) -> Guard {
        let bank = dir(name).join("bank.jsonl");
        let g = Guard { bank };
        assert!(Command::new(env!("CARGO_BIN_EXE_instinct"))
            .args(["starter", "--apply"])
            .envs(g.env())
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .status()
            .unwrap()
            .success());
        g
    }
    fn env(&self) -> Vec<(&'static str, PathBuf)> {
        vec![("INSTINCT_STORE", self.bank.clone()), ("INSTINCT_TEAM", "0".into()), ("INSTINCT_STARTER", "0".into())]
    }
    fn warns(&self, cwd: &Path, command: &str) -> bool {
        let ev = format!(
            "{{\"hook_event_name\":\"PreToolUse\",\"tool_name\":\"Bash\",\"cwd\":{:?},\"tool_input\":{{\"command\":{:?}}}}}",
            cwd.to_str().unwrap(),
            command
        );
        let mut c = Command::new(env!("CARGO_BIN_EXE_instinct"))
            .args(["guard", "--format", "text"])
            .envs(self.env())
            .current_dir(cwd)
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::null())
            .spawn()
            .unwrap();
        c.stdin.take().unwrap().write_all(ev.as_bytes()).unwrap();
        let out = String::from_utf8_lossy(&c.wait_with_output().unwrap().stdout).into_owned();
        out.lines().any(|l| l.starts_with("[in-"))
    }
}

fn repo(name: &str) -> PathBuf {
    let d = dir(name);
    git(&d, &["init", "-q"]);
    fs::create_dir_all(d.join("src")).unwrap();
    fs::write(d.join("src/a.rs"), "a\n").unwrap();
    fs::write(d.join("notes.md"), "n\n").unwrap();
    git(&d, &["add", "-A"]);
    git(&d, &["commit", "-q", "-m", "init"]);
    d
}

#[test]
fn sed_in_place_warns_unless_every_file_is_tracked_and_unmodified() {
    let g = Guard::new("sed-bank");
    let r = repo("sed");
    // quiet: tracked and clean, also after cd and through a variable, and for a heredoc that only writes the text
    assert!(!g.warns(&r, "sed -i 's/a/b/' src/a.rs"));
    assert!(!g.warns(&r, "cd src && sed -i 's/a/b/' a.rs"));
    assert!(!g.warns(&r, "f=notes.md; sed -i 's/n/m/' \"$f\""));
    assert!(!g.warns(&r, "cat > fix.sh <<'EOF'\nsed -i 's/a/b/' src/a.rs\nEOF"));
    // loud: untracked, modified, missing, a glob, fan-out, a variable it cannot resolve
    fs::write(r.join("scratch.txt"), "s\n").unwrap();
    assert!(g.warns(&r, "sed -i 's/a/b/' scratch.txt"));
    assert!(g.warns(&r, "sed -i 's/a/b/' src/none.rs"));
    assert!(g.warns(&r, "sed -i 's/a/b/' src/*.rs"));
    assert!(g.warns(&r, "find . -name '*.rs' | xargs sed -i 's/a/b/'"));
    assert!(g.warns(&r, "for f in src/a.rs notes.md; do sed -i 's/a/b/' $f; done"));
    assert!(g.warns(&r, "sed -i 's/a/b/' $UNKNOWN"));
    fs::write(r.join("src/a.rs"), "changed\n").unwrap();
    assert!(g.warns(&r, "sed -i 's/a/b/' src/a.rs"));
    // outside any repository
    let plain = dir("sed-plain");
    fs::write(plain.join("f.txt"), "x\n").unwrap();
    assert!(g.warns(&plain, "sed -i 's/a/b/' f.txt"));
    // a file in another repository is judged there, not in the directory the command runs in
    let other = repo("sed-other");
    assert!(!g.warns(&plain, &format!("sed -i 's/a/b/' {}/notes.md", other.display())));
    assert!(g.warns(&plain, &format!("sed -i 's/a/b/' {}/missing.md", other.display())));
}

#[test]
fn branch_delete_warns_unless_the_commits_live_elsewhere() {
    let g = Guard::new("branch-bank");
    let r = repo("branch");
    git(&r, &["branch", "merged"]);
    git(&r, &["checkout", "-q", "-b", "wip"]);
    fs::write(r.join("wip.txt"), "w\n").unwrap();
    git(&r, &["add", "-A"]);
    git(&r, &["commit", "-q", "-m", "wip"]);
    git(&r, &["checkout", "-q", "-"]);
    assert!(!g.warns(&r, "git branch -D merged"));
    assert!(g.warns(&r, "git branch -D wip"));
    assert!(g.warns(&r, "git branch -D merged wip"));
    assert!(!g.warns(&r, "git branch -D ghost"));
}