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.
//! The verified index snapshot `<store>.idx`: identical answers with and without it, and a rebuild
//! whenever the bank, the lexical weights or the snapshot itself is not what it was written for.
#![cfg(unix)]
use std::io::Write;
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};

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

fn run(store: &Path, args: &[&str], stdin: &str, env: &[(&str, &str)]) -> (i32, String) {
    let mut c = Command::new(bin());
    c.args(args)
        .env("INSTINCT_STORE", store)
        .env_remove("INSTINCT_EXPLORE")
        .env_remove("INSTINCT_INDEX")
        .env_remove("INSTINCT_PROJECT")
        .env_remove("INSTINCT_W_WHEN")
        .env_remove("INSTINCT_W_TITLE")
        .env_remove("INSTINCT_W_BODY");
    for (k, v) in env {
        c.env(k, v);
    }
    let mut child = c.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap();
    let _ = child.stdin.take().unwrap().write_all(stdin.as_bytes());
    let out = child.wait_with_output().unwrap();
    let mut text = String::from_utf8(out.stdout).unwrap();
    if !out.status.success() {
        text.push_str(&String::from_utf8_lossy(&out.stderr));
    }
    (out.status.code().unwrap(), text)
}

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

fn idx(store: &Path) -> PathBuf {
    let mut s = store.as_os_str().to_owned();
    s.push(".idx");
    PathBuf::from(s)
}

fn bank(store: &Path, title: &str, when: &str, found: &str, how: &str, extra: &[&str]) -> String {
    let mut a = vec!["bank", "--title", title, "--when", when, "--found", found, "--how", how, "--evidence", "seen twice"];
    a.extend_from_slice(extra);
    let (code, out) = run(store, &a, "", &[]);
    assert_eq!(code, 0, "{out}");
    out.split_whitespace().nth(1).unwrap().to_owned()
}

/// A bank with enough variety to exercise ranking: shared words, a scoped lesson, hits and misses.
fn fixture(name: &str) -> (PathBuf, Vec<String>) {
    let store = temp(name, "bank.hxdb");
    let ids = vec![
        bank(&store, "Pin the lockfile", "A release build resolves dependencies on CI", "Cargo picked a newer crate", "Pass --locked to every cargo build", &[]),
        bank(&store, "Warm the registry", "The build host has no network access", "Cargo tried to refresh the index", "Fetch once then build with --offline", &[]),
        bank(&store, "Thin LTO on small runners", "The linker is killed with signal 9 on a small runner", "Full LTO needed six gigabytes", "Use lto thin and sixteen codegen units", &[]),
        bank(&store, "Replica restart order", "Restarting the postgres replica after a primary failover", "Replica started before the primary", "Restart the primary first and wait for it", &["--project", "payments"]),
        bank(&store, "Image layer cache", "The image build reinstalls every dependency on each commit", "Copy order busted the layer cache", "Copy the lockfile before the sources", &[]),
    ];
    for id in &ids[..3] {
        assert_eq!(run(&store, &["hit", id], "", &[]).0, 0);
    }
    assert_eq!(run(&store, &["miss", &ids[4]], "", &[]).0, 0);
    (store, ids)
}

const QUERIES: &[&str] = &[
    "release build resolves dependencies on CI",
    "linker killed with signal 9 on the runner",
    "restart the postgres replica after failover",
    "the image build reinstalls every dependency",
    "no network access on the build host",
    "something nobody ever banked about kubernetes ingress",
];

/// recall, prompt and guard for one query, with and without the snapshot, in one scope.
fn answers(store: &Path, q: &str, env: &[(&str, &str)]) -> Vec<(String, String)> {
    let esc = q.replace('\\', "\\\\").replace('"', "\\\"");
    let prompt = format!("{{\"prompt\":\"{esc}\"}}");
    let guard = format!("{{\"tool_name\":\"Bash\",\"tool_input\":{{\"command\":\"{esc}\"}}}}");
    let mut off = env.to_vec();
    off.push(("INSTINCT_INDEX", "0"));
    let mut v = Vec::new();
    for (args, stdin) in [(vec!["recall", "--q", q, "--k", "3"], String::new()), (vec!["prompt"], prompt), (vec!["guard"], guard)] {
        let (c1, warm) = run(store, &args, &stdin, env);
        let (c2, cold) = run(store, &args, &stdin, &off);
        assert_eq!((c1, c2), (0, 0), "{args:?} {q}");
        v.push((warm, cold));
    }
    v
}

fn assert_same(store: &Path, env: &[(&str, &str)]) -> usize {
    let mut nonempty = 0;
    for q in QUERIES {
        for (warm, cold) in answers(store, q, env) {
            assert_eq!(warm, cold, "snapshot and cold path disagree for {q:?}");
            if !warm.trim().is_empty() {
                nonempty += 1;
            }
        }
    }
    nonempty
}

fn header_len(path: &Path) -> u64 {
    let b = std::fs::read(path).unwrap();
    assert_eq!(&b[..8], b"INSTIDX3");
    let version = u32::from_le_bytes(b[8..12].try_into().unwrap()) as usize;
    assert_eq!(&b[12..12 + version], env!("CARGO_PKG_VERSION").as_bytes(), "the snapshot names the engine that wrote it");
    u64::from_le_bytes(b[12 + version..20 + version].try_into().unwrap())
}

#[test]
fn v2_snapshot_rebuild_recovers_the_case_decision() {
    // At 3d4e501, running 'recall --q "seal parcel"' on these journal bytes
    // produced this valid v2 cache. That engine skipped the casebook event.
    const JOURNAL: &str = r#"{"kind":"discovery","id":"in-zpyy1v6","ts":1,"title":"Seal parcel","when":"Seal parcel","found":"Seal parcel","how":"Seal parcel","evidence":"Seal parcel","tags":"seal parcel","source":"banked","state":"candidate","evidence_status":"unverified"}
{"kind":"casebook","id":"in-zpyy1v6","binding":"bc833cca5469da48ef578dc0bfa8bb23c878a1db88b8b88c7c8719272707a060","ts":1,"casebook":{"checks":[{"key":"sealed","question":"Sealed?","cost":1}],"examples":[{"ref":"slip-1","facts":{"sealed":true},"action":"send parcel"}]}}
"#;
    const V2_HEX: &str = concat!(
        "494e53544944583205000000302e332e37040200000000000089afcce76bb714f4406b4d2e77d8adfb030101",
        "0101000000c20000000600000062616e6b65640900000063616e6469646174650a000000756e766572696669",
        "6564000000000000000000000000000000000000000000000000000000000a000000696e2d7a707979317636",
        "0b0000005365616c2070617263656c0b0000005365616c2070617263656c0b0000005365616c207061726365",
        "6c0b0000005365616c2070617263656c0b0000005365616c2070617263656c000000000b0000007365616c20",
        "70617263656c0100000000000000000000000000000000000000000e0000000200000000000000060000000a",
        "00000070617263656c7365616c00000000010000000200000000000000000000000700000007000000020000",
        "0000000000060000000a00000070617263656c7365616c000000000200000000000000010000001b3512d81b",
        "6efdd9ce95b25e456b3201",
    );
    let store = temp("v2-case-decision", "bank.jsonl");
    let previous: Vec<u8> = (0..V2_HEX.len()).step_by(2)
        .map(|i| u8::from_str_radix(&V2_HEX[i..i + 2], 16).unwrap()).collect();
    assert_eq!(&previous[..8], b"INSTIDX2");
    assert_eq!(u64::from_le_bytes(previous[17..25].try_into().unwrap()), JOURNAL.len() as u64);
    std::fs::write(&store, JOURNAL).unwrap();
    std::fs::write(idx(&store), previous).unwrap();
    let args = ["decide", "--q", "seal parcel", "--facts", r#"{"sealed":true}"#];
    let env = [("INSTINCT_TEAM", "0"), ("INSTINCT_CONCEPTS", "1")];
    let rebuilt = run(&store, &args, "", &env);
    assert_eq!(rebuilt.0, 0, "{}", rebuilt.1);
    assert!(rebuilt.1.contains(r#""candidate_action":"send parcel""#) && rebuilt.1.contains("slip-1"), "{}", rebuilt.1);
    assert_eq!(header_len(&idx(&store)), JOURNAL.len() as u64);
    assert_eq!(run(&store, &args, "", &env), rebuilt);
    assert_eq!(std::fs::read_to_string(&store).unwrap(), JOURNAL);
}

#[test]
fn answers_are_byte_identical_with_and_without_the_snapshot() {
    let (store, _) = fixture("same");
    let n = assert_same(&store, &[]);
    assert!(n > 6, "the comparison must cover real answers, not only empty ones: {n}");
    // the scoped lesson appears only in its project; other scopes must not see it
    assert_same(&store, &[("INSTINCT_PROJECT", "payments")]);
    assert_same(&store, &[("INSTINCT_PROJECT", "elsewhere")]);
    let meta = std::fs::metadata(idx(&store)).unwrap();
    assert_eq!(meta.permissions().mode() & 0o777, 0o600, "the snapshot is private like the bank");
}

#[test]
fn every_write_invalidates_and_the_next_lookup_rebuilds() {
    let (store, ids) = fixture("writes");
    let q = "release build resolves dependencies on CI";
    let lookup = |store: &Path| run(store, &["recall", "--q", q, "--k", "3"], "", &[]);
    lookup(&store);
    let mut last = std::fs::read(idx(&store)).unwrap();
    let steps: Vec<(&str, Vec<&str>)> = vec![
        ("bank", vec!["bank", "--title", "New lesson", "--when", "a brand new release trigger", "--found", "x", "--how", "y", "--evidence", "z"]),
        ("hit", vec!["hit", &ids[0]]),
        ("miss", vec!["miss", &ids[1]]),
        ("review", vec!["review", &ids[2], "--state", "quarantined", "--reason", "test", "--source-ref", "test"]),
    ];
    for (name, args) in steps {
        let (code, out) = run(&store, &args, "", &[]);
        assert_eq!(code, 0, "{name}: {out}");
        let (_, warm) = lookup(&store);
        let (_, cold) = run(&store, &["recall", "--q", q, "--k", "3"], "", &[("INSTINCT_INDEX", "0")]);
        assert_eq!(warm, cold, "after {name}");
        let now = std::fs::read(idx(&store)).unwrap();
        assert_ne!(now, last, "after {name} the snapshot must be rebuilt");
        assert_eq!(header_len(&idx(&store)), std::fs::metadata(&store).unwrap().len(), "after {name} the snapshot names the new bank");
        last = now;
    }
    assert_same(&store, &[]);
}

#[test]
fn an_external_append_or_replacement_gives_the_cold_answer() {
    // a plain JSONL bank, edited from outside the engine
    let store = temp("external", "bank.jsonl");
    let lesson = |id: &str, when: &str| {
        format!("{{\"kind\":\"discovery\",\"id\":\"{id}\",\"ts\":1,\"title\":\"{id} title\",\"when\":\"{when}\",\"found\":\"found\",\"how\":\"fix\",\"evidence\":\"seen\",\"tags\":\"\",\"reconsider\":\"\",\"embedding\":[],\"source\":\"banked\",\"state\":\"candidate\",\"evidence_status\":\"unverified\"}}\n")
    };
    std::fs::write(&store, lesson("in-aaaa001", "deploy lock timeout on staging") + &lesson("in-aaaa002", "database migration hangs on large table")).unwrap();
    let ask = |env: &[(&str, &str)]| run(&store, &["recall", "--q", "deploy lock timeout on staging", "--k", "3"], "", env).1;
    assert!(ask(&[]).contains("in-aaaa001"));
    assert!(idx(&store).exists());
    // external append: a new lesson that now matches better
    let mut f = std::fs::OpenOptions::new().append(true).open(&store).unwrap();
    f.write_all(lesson("in-aaaa003", "deploy lock timeout on staging again").as_bytes()).ok();
    drop(f);
    let (warm, cold) = (ask(&[]), ask(&[("INSTINCT_INDEX", "0")]));
    assert_eq!(warm, cold);
    assert_eq!(header_len(&idx(&store)), std::fs::metadata(&store).unwrap().len());
    // replacement with the same length and different words: only a hash of the bytes can tell
    run(&store, &["recall", "--q", "database migration stuck on large table", "--k", "3"], "", &[]);
    let before = std::fs::read(&store).unwrap();
    let swapped = String::from_utf8(before.clone()).unwrap().replace("migration hangs", "migration stuck");
    assert_ne!(swapped.as_bytes(), &before[..]);
    assert_eq!(swapped.len(), before.len(), "the swap keeps the byte length, so only the hash can notice it");
    std::fs::write(&store, swapped).unwrap();
    let q = ["recall", "--q", "database migration stuck on large table", "--k", "3"];
    let (warm, cold) = (run(&store, &q, "", &[]).1, run(&store, &q, "", &[("INSTINCT_INDEX", "0")]).1);
    assert_eq!(warm, cold);
    assert!(warm.contains("in-aaaa002") && warm.contains("stuck"), "the replaced file is what gets answered: {warm}");
}

#[test]
fn a_damaged_or_foreign_snapshot_is_ignored_and_rebuilt() {
    let (store, _) = fixture("damage");
    assert_same(&store, &[]);
    let good = std::fs::read(idx(&store)).unwrap();
    let (other, _) = fixture("damage-other");
    run(&other, &["recall", "--q", "anything about the build"], "", &[]);
    let foreign = std::fs::read(idx(&other)).unwrap();
    let mut flipped = good.clone();
    let mid = flipped.len() / 2;
    flipped[mid] ^= 0x40;
    let mut flipped_tail = good.clone();
    let last = flipped_tail.len() - 1;
    flipped_tail[last] ^= 1;
    let damaged: Vec<(&str, Vec<u8>)> = vec![
        ("flipped byte", flipped),
        ("flipped checksum", flipped_tail),
        ("truncated", good[..good.len() / 3].to_vec()),
        ("empty", Vec::new()),
        ("garbage", b"not a snapshot at all".to_vec()),
        ("another bank's snapshot", foreign),
    ];
    for (what, bytes) in damaged {
        std::fs::write(idx(&store), &bytes).unwrap();
        assert_same(&store, &[]);
        assert_eq!(std::fs::read(idx(&store)).unwrap(), good, "{what}: the snapshot is rewritten from the bank");
    }
}

#[test]
fn index_zero_neither_reads_nor_writes_the_snapshot() {
    let (store, _) = fixture("off");
    let off = [("INSTINCT_INDEX", "0")];
    let _ = std::fs::remove_file(idx(&store));
    run(&store, &["recall", "--q", "release build"], "", &off);
    run(&store, &["stats"], "", &off);
    assert!(!idx(&store).exists(), "disabled means nothing is written");
    std::fs::write(idx(&store), b"planted").unwrap();
    run(&store, &["recall", "--q", "release build"], "", &off);
    assert_eq!(std::fs::read(idx(&store)).unwrap(), b"planted", "disabled means the file is left alone");
}

#[test]
fn the_lexical_weights_belong_to_the_key() {
    let (store, _) = fixture("weights");
    assert_same(&store, &[]);
    let before = std::fs::read(idx(&store)).unwrap();
    assert_same(&store, &[("INSTINCT_W_WHEN", "1"), ("INSTINCT_W_TITLE", "4")]);
    assert_ne!(std::fs::read(idx(&store)).unwrap(), before, "a different weighting writes a different snapshot");
}

#[test]
fn nothing_but_the_snapshot_is_left_behind() {
    let (store, _) = fixture("litter");
    assert_same(&store, &[]);
    let names: Vec<String> = std::fs::read_dir(store.parent().unwrap()).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect();
    assert!(names.iter().all(|n| !n.contains(".tmp")), "{names:?}");
    assert!(names.iter().any(|n| n == "bank.hxdb.idx"), "{names:?}");
}

#[test]
fn the_rare_word_gate_and_synonyms_match_the_cold_path() {
    // 40 lessons: "release" and "page" are in most of them, so they are common anchors; a few have rare ones
    let store = temp("gate", "bank.jsonl");
    let mut text = String::new();
    for i in 0..40 {
        let (when, title, tags) = match i {
            0 => ("a release page that needs the memory limit raised", "Raise the pod memory limit", "release page"),
            1 => ("a release page with a stale cache header", "Purge the edge cache", "release page"),
            2 => ("the ram on a worker runs out during a release", "Add swap on workers", "worker ram"),
            3 => ("the test suite hangs on the ci runner", "Fix the hanging suite", "suite hang"),
            _ => ("the release page build number is wrong on a branch", "Rebuild the release page", "release page build"),
        };
        text.push_str(&format!("{{\"kind\":\"discovery\",\"id\":\"in-gate{i:03}\",\"ts\":1,\"title\":\"{title} {i}\",\"when\":\"{when} {i}\",\"found\":\"found {i}\",\"how\":\"how {i}\",\"evidence\":\"seen\",\"tags\":\"{tags}\",\"reconsider\":\"\",\"embedding\":[],\"source\":\"banked\",\"state\":\"candidate\",\"evidence_status\":\"unverified\"}}\n"));
    }
    std::fs::write(&store, text).unwrap();
    for q in ["release page", "the release page is wrong", "release page memory limit", "worker memory runs out in a release", "stale cache header on the release page", "pod ram limit", "test suite", "the spec suite is slow", "test suite hangs on the runner"] {
        for env in [vec![], vec![("INSTINCT_RARE", "0")], vec![("INSTINCT_CONCEPTS", "0")], vec![("INSTINCT_RARE", "0"), ("INSTINCT_CONCEPTS", "0")]] {
            let esc = format!("{{\"prompt\":\"{q}\"}}");
            let mut off = env.clone();
            off.push(("INSTINCT_INDEX", "0"));
            let warm = run(&store, &["prompt"], &esc, &env).1;
            let cold = run(&store, &["prompt"], &esc, &off).1;
            assert_eq!(warm, cold, "{q} {env:?}");
            let warm = run(&store, &["recall", "--q", q, "--k", "3"], "", &env).1;
            let cold = run(&store, &["recall", "--q", q, "--k", "3"], "", &off).1;
            assert_eq!(warm, cold, "{q} {env:?}");
        }
    }
    assert!(idx(&store).exists());
}

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