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.
// generated by hxc 1.0.0-acgt-compiler from bench/storage.hlx -- do not edit by hand

#[cfg(windows)]
#[allow(dead_code)]
const SYS_CURL: &str = "C:\\Windows\\System32\\curl.exe";
#[cfg(not(windows))]
#[allow(dead_code)]
const SYS_CURL: &str = "curl";
#[allow(dead_code)]
fn _helix_allowed(var: &str, what: &str) -> bool {
    let ok = std::env::var(var).map(|v| v == "1").unwrap_or(false);
    if !ok {
        eprintln!("helix: BLOCKED {} -- permission denied (set {}=1 to allow; `hxc run` allows by default, a `hxc build`/`export-rust` binary does not)", what, var);
    }
    ok
}
#[cfg(windows)]
#[allow(dead_code)]
fn _nw_exec(mut c: std::process::Command) -> std::process::Command {
    if !_helix_allowed("HELIX_ALLOW_RUN", "process execution") {
        std::process::exit(13);
    }
    use std::os::windows::process::CommandExt;
    c.creation_flags(0x08000000);
    c
}
#[cfg(not(windows))]
#[allow(dead_code)]
fn _nw_exec(c: std::process::Command) -> std::process::Command {
    if !_helix_allowed("HELIX_ALLOW_RUN", "process execution") {
        std::process::exit(13);
    }
    c
}
#[cfg(windows)]
#[allow(dead_code)]
fn _nw_net(mut c: std::process::Command) -> std::process::Command {
    if !_helix_allowed("HELIX_ALLOW_NET", "network access") {
        std::process::exit(13);
    }
    use std::os::windows::process::CommandExt;
    c.creation_flags(0x08000000);
    c
}
#[cfg(not(windows))]
#[allow(dead_code)]
fn _nw_net(c: std::process::Command) -> std::process::Command {
    if !_helix_allowed("HELIX_ALLOW_NET", "network access") {
        std::process::exit(13);
    }
    c
}

// hlx:2
use std::{
    env,
    fs::{self, File},
    io::{self, BufRead, BufReader, BufWriter, Write},
    path::Path,
    process::{Command, Stdio},
    time::{Instant, SystemTime, UNIX_EPOCH},
};
// hlx:3
fn resident(engine: &Path, store: &Path, count: usize, format: &str) -> io::Result<()> {
    // hlx:4
    let mut cmd = Command::new(engine);
    // hlx:5
    for (key, _) in env::vars_os().filter(|(k, _)| k.to_string_lossy().starts_with("INSTINCT_")) {
        // hlx:6
        cmd.env_remove(key);
        // hlx:7
    }
    // hlx:8
    let mut child = cmd
        .arg("mcp")
        .env("INSTINCT_STORE", store)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .spawn()?;
    // hlx:9
    let mut input = child.stdin.take().unwrap();
    // hlx:10
    let mut output = BufReader::new(child.stdout.take().unwrap());
    // hlx:11
    let mut samples = Vec::new();
    // hlx:12
    for trial in 0..33 {
        // hlx:13
        let id = 1 + (trial * 271) % (count - 1);
        // hlx:14
        let message = r#"{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"instinct_recall","arguments":{"project":"studio","q":"groupKEY itemKEY","k":1}}}"#.replace("KEY",&id.to_string());
        // hlx:15
        let now = Instant::now();
        // hlx:16
        writeln!(input, "{message}")?;
        // hlx:17
        input.flush()?;
        // hlx:18
        let mut reply = String::new();
        // hlx:19
        output.read_line(&mut reply)?;
        // hlx:20
        let elapsed = now.elapsed().as_secs_f64() * 1000.0;
        // hlx:21
        if !reply.contains(&format!("[fixture-{id}]")) || !reply.contains(r#""isError":false"#) {
            // hlx:22
            return Err(io::Error::other("resident MCP returned the wrong fixture"));
            // hlx:23
        }
        // hlx:24
        if trial >= 2 {
            // hlx:25
            samples.push(elapsed);
            // hlx:26
        }
        // hlx:27
    }
    // hlx:28
    drop(input);
    // hlx:29
    if !child.wait()?.success() {
        // hlx:30
        return Err(io::Error::other("MCP failed"));
        // hlx:31
    }
    // hlx:32
    samples.sort_by(f64::total_cmp);
    // hlx:33
    println!(
        "resident-mcp,{format},{count},{},{:.2},{:.2}",
        store.metadata()?.len(),
        samples[15],
        samples[29]
    );
    // hlx:34
    Ok(())
    // hlx:35
}
// hlx:37
fn write_cached_vectors(path: &Path, count: usize) -> io::Result<()> {
    // hlx:38
    let mut sidecar = BufWriter::new(File::create(path.with_extension("hxdb.when.bin"))?);
    // hlx:39
    let vector = 0.25f32.to_le_bytes().repeat(768);
    // hlx:40
    for i in 0..count {
        // hlx:41
        let id = format!("fixture-{i}");
        // hlx:42
        sidecar.write_all(&(id.len() as u16).to_le_bytes())?;
        // hlx:43
        sidecar.write_all(id.as_bytes())?;
        // hlx:44
        sidecar.write_all(&768u16.to_le_bytes())?;
        // hlx:45
        sidecar.write_all(&vector)?;
        // hlx:46
    }
    // hlx:47
    sidecar.flush()
    // hlx:48
}
// hlx:49
fn measure(engine: &Path, store: &Path, count: usize, offline_vectors: bool) -> io::Result<()> {
    // hlx:50
    let mut writer = BufWriter::new(File::create(store)?);
    // hlx:51
    for i in 0..count {
        // hlx:52
        let cue = if i == 0 {
            "approved headline".to_owned()
        } else {
            format!("delivery packing group{i} item{i}")
        };
        // hlx:53
        writeln!(
            writer,
            r#"{{"kind":"discovery","id":"fixture-{i}","title":"Task {i}","when":"{cue}","found":"The requested edit worked","how":"Use the accepted revision","evidence":"Checked the output","source":"banked","state":"candidate","scope_project":"studio"}}"#
        )?;
        // hlx:54
    }
    // hlx:55
    writer.flush()?;
    // hlx:56
    drop(writer);
    // hlx:57
    let native = store.with_extension("hxdb");
    // hlx:58
    let migration = Command::new(engine)
        .arg("migrate")
        .arg("--store")
        .arg(store)
        .arg("--to")
        .arg(&native)
        .output()?;
    // hlx:59
    if !migration.status.success() {
        // hlx:60
        return Err(io::Error::other(
            String::from_utf8_lossy(&migration.stderr).to_string(),
        ));
        // hlx:61
    }
    // hlx:62
    let paths = [store, native.as_path()];
    // hlx:63
    if offline_vectors {
        // hlx:64
        resident(engine, &native, count, "helix-db-no-sidecar")?;
        // hlx:65
        write_cached_vectors(&native, count)?;
        // hlx:66
        return resident(engine, &native, count, "helix-db-with-sidecar");
        // hlx:67
    }
    // hlx:68
    let mut samples = [Vec::new(), Vec::new()];
    // hlx:69
    for trial in 0..33 {
        // hlx:70
        for step in 0..2 {
            // hlx:71
            let arm = (trial + step) % 2;
            // hlx:72
            let mut cmd = Command::new(engine);
            // hlx:73
            for (key, _) in
                env::vars_os().filter(|(k, _)| k.to_string_lossy().starts_with("INSTINCT_"))
            {
                // hlx:74
                cmd.env_remove(key);
                // hlx:75
            }
            // hlx:76
            cmd.env("INSTINCT_STORE", paths[arm]).args([
                "decide",
                "--project",
                "studio",
                "--q",
                "Keep the approved headline",
            ]);
            // hlx:77
            let start = Instant::now();
            // hlx:78
            let output = cmd.output()?;
            // hlx:79
            let elapsed = start.elapsed().as_secs_f64() * 1000.0;
            // hlx:80
            let reply = String::from_utf8_lossy(&output.stdout);
            // hlx:81
            if !output.status.success()
                || !reply.contains(r#""id":"fixture-0""#)
                || reply.matches(r#""id":"#).count() != 1
            {
                // hlx:82
                return Err(io::Error::other("unexpected fixture result"));
                // hlx:83
            }
            // hlx:84
            if trial >= 2 {
                // hlx:85
                samples[arm].push(elapsed);
                // hlx:86
            }
            // hlx:87
        }
        // hlx:88
    }
    // hlx:89
    for (arm, times) in samples.iter_mut().enumerate() {
        // hlx:90
        times.sort_by(f64::total_cmp);
        // hlx:91
        println!(
            "cold-cli,{},{},{},{:.2},{:.2}",
            ["jsonl", "helix-db"][arm],
            count,
            paths[arm].metadata()?.len(),
            times[15],
            times[29]
        );
        // hlx:92
        resident(engine, paths[arm], count, ["jsonl", "helix-db"][arm])?;
        // hlx:93
    }
    // hlx:94
    Ok(())
    // hlx:95
}
// hlx:96
fn main() -> io::Result<()> {
    // hlx:97
    let offline_vectors = match env::args_os().nth(2) {
        None => false,
        Some(arg) if arg == "--offline-vectors" => true,
        _ => return Err(io::Error::other("expected optional --offline-vectors")),
    };
    // hlx:98
    let engine = env::args_os()
        .nth(1)
        .ok_or_else(|| io::Error::other("supply the path to the release instinct executable"))?;
    // hlx:99
    let stamp = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_nanos();
    // hlx:100
    let scratch = env::temp_dir().join(format!("instinct-storage-{}-{stamp}", std::process::id()));
    // hlx:101
    fs::create_dir(&scratch)?;
    // hlx:102
    println!("mode,format,lessons,bytes,p50_ms,p95_ms");
    // hlx:103
    let result = [100, 1000, 10000].into_iter().try_for_each(|n| {
        measure(
            Path::new(&engine),
            &scratch.join(format!("bank-{n}.jsonl")),
            n,
            offline_vectors,
        )
    });
    // hlx:104
    fs::remove_dir_all(&scratch)?;
    // hlx:105
    result
    // hlx:106
}