instinct-cli 0.2.0

Local-first RAG memory for AI agents. Give Claude Code, Codex and MCP agents the methods your last agent earned, backed by embedded Helix DB.
// generated by hxc 1.0.0-acgt-compiler from bench/backtest/run.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,io::Write,path::{Path,PathBuf},process::{Command,Stdio},time::Instant};
// hlx:3
fn output(cmd:&mut Command)->String {
    // hlx:4
    let r=cmd.output().expect("start process");
    // hlx:5
    assert!(r.status.success(),"process failed: {}",String::from_utf8_lossy(&r.stderr));
    // hlx:6
    String::from_utf8(r.stdout).expect("UTF8").trim().to_owned()
    // hlx:7
}
// hlx:8
fn read_field(file:&Path,key:&str)->String {
    // hlx:9
    output(Command::new("jq").args(["-er",key]).arg(file))
    // hlx:10
}
// hlx:11
fn ask_claude(dir:&Path,model:&str,prompt:&str)->Result<String,String> {
    // hlx:12
    let mut cmd=Command::new("timeout");
    // hlx:13
    cmd.args(["90","claude","-p","--model",model,"--tools","","--settings","{\"disableAllHooks\":true}","--setting-sources","","--strict-mcp-config","--no-session-persistence"]).current_dir(dir);
    // hlx:14
    let response=cmd.arg(prompt).output().map_err(|e|e.to_string())?;
    // hlx:15
    if !response.status.success(){return Err(format!("Claude process failed {}",response.status))};
    // hlx:16
    String::from_utf8(response.stdout).map(|s|s.trim().to_owned()).map_err(|e|e.to_string())
    // hlx:17
}
// hlx:18
fn ask(dir:&Path,model:&str,prompt:&str,claude:bool)->Result<String,String> {
    // hlx:19
    if claude {
        // hlx:20
        return ask_claude(dir,model,prompt);
        // hlx:21
    }
    // hlx:22
    let mut child=Command::new("timeout").arg("90").args(["codex","exec","--ephemeral","--ignore-user-config","--skip-git-repo-check","-s","read-only","-m",model,"-c","project_doc_max_bytes=0","-c","features.shell_tool=false","--json","-o","response","-"]).current_dir(dir).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().map_err(|e|e.to_string())?;
    // hlx:23
    child.stdin.take().unwrap().write_all(prompt.as_bytes()).map_err(|e|e.to_string())?;
    // hlx:24
    let r=child.wait_with_output().map_err(|e|e.to_string())?;
    // hlx:25
    if !r.status.success(){return Err(format!("model process failed {}",r.status))};
    // hlx:26
    let trace=dir.join("trace.jsonl");
    // hlx:27
    fs::write(&trace,&r.stdout).map_err(|e|e.to_string())?;
    // hlx:28
    let ok=Command::new("jq").args(["-es","all(.[]; (.item.type? // \"\") as $t | ([\"command_execution\",\"mcp_tool_call\",\"web_search\",\"file_change\"] | index($t)) == null)"]).arg(trace).stdout(Stdio::null()).status().map_err(|e|e.to_string())?;
    // hlx:29
    if !ok.success(){return Err("unexpected tool use or malformed trace".into())};
    // hlx:30
    fs::read_to_string(dir.join("response")).map(|s|s.trim().to_owned()).map_err(|e|e.to_string())
    // hlx:31
}
// hlx:32
fn main() {
    // hlx:33
    let args:Vec<_>=env::args().collect();
    // hlx:34
    let arm=args.get(1).map(String::as_str).unwrap_or("demo");
    // hlx:35
    assert!(matches!(arm,"demo"|"base"|"static"|"live"),"use demo, base, static or live");
    // hlx:36
    let model=args.get(2).map(String::as_str).unwrap_or("gpt-6.2-astra");
    // hlx:37
    let everyday=args.iter().skip(3).any(|arg| arg=="everyday");
    // hlx:38
    let first_use=args.iter().skip(3).any(|arg| arg=="first-use");
    // hlx:39
    let claude=args.iter().skip(3).any(|arg| arg=="claude");
    // hlx:40
    let suite=if first_use {"first-use"} else if everyday {"everyday"} else {"backtest"};
    // hlx:41
    let folder=Path::new(env!("CARGO_MANIFEST_DIR")).join("bench").join(suite);
    // hlx:42
    let fixture=folder.join(if first_use {"discoveries.json"} else {"fixtures.json"});
    // hlx:43
    let cases_file=if first_use {folder.join("cases.json")} else {fixture.clone()};
    // hlx:44
    let case_list=if first_use {"."} else {".cases"};
    // hlx:45
    let engine=env::current_exe().unwrap().parent().unwrap().parent().unwrap().join("instinct");
    // hlx:46
    assert!(engine.is_file(),"build the instinct binary in the same Cargo profile first");
    // hlx:47
    let tmp=PathBuf::from(output(Command::new("mktemp").arg("-d")));
    // hlx:48
    let bank=|args:&[String]|output(Command::new(&engine).env_clear().env("INSTINCT_STORE",tmp.join("bank")).args(args));
    // hlx:49
    let n:usize=read_field(&fixture,".bank|length").parse().unwrap();
    // hlx:50
    for i in 0..n {
    // hlx:51
    let mut a=vec!["bank".to_string()];
    // hlx:52
    for field in ["title","when","found","how","reconsider","evidence"] {a.extend([format!("--{field}"),read_field(&fixture,&format!(".bank[{i}].{field}"))]);};
    // hlx:53
    bank(&a);
    // hlx:54
    }
    // hlx:55
    let packet=read_field(&fixture,".bank | map({when,method:.how,observed:.found,reconsider_if:.reconsider,evidence}) | tojson");
    // hlx:56
    let cases:usize=read_field(&cases_file,&format!("{case_list}|length")).parse().unwrap();
    // hlx:57
    if arm!="demo" {println!("case\tarm\tmodel\tcontext_bytes\trecall_ms\tdocs\ttotal_ms\tgrade\tanswer");};
    // hlx:58
    let reverse=args.get(3).map(String::as_str)==Some("reverse");
    // hlx:59
    for position in 0..cases {
    // hlx:60
    let i=if reverse {cases-position-1} else {position};
    // hlx:61
    let field=|key:&str|read_field(&cases_file,&format!("{case_list}[{i}].{key}"));
    // hlx:62
    let (id,question,records,reference,expected)=(field("id"),field("situation"),field("records"),field("reference"),field("answer"));
    // hlx:63
    let dir=tmp.join(&id);
    // hlx:64
    fs::create_dir(&dir).unwrap();
    // hlx:65
    let start=Instant::now();
    // hlx:66
    let context=match arm {"base"=>String::new(),"static"=>packet.clone(),_=>bank(&["decide".into(),"--q".into(),question.clone()])};
    // hlx:67
    let elapsed=start.elapsed().as_millis();
    // hlx:68
    if arm=="demo"{println!("{id}\n{question}\n{context}\n"); continue;};
    // hlx:69
    let prompt=if first_use {format!("Complete this user request using the available material. Follow their output format. If an additional fact could change your answer and you need the available note, reply with exactly READ. Use no tools.\nPrior experience, if relevant: {context}\nRequest: {question}\nMaterial: {records}")} else if everyday {format!("Help a person choose between the listed options. Your only sources are the supplied facts and optional past experience. If you need one more fact, answer only READ to see the available note. Otherwise answer only with the chosen option's ID. No tools.\nPast experience: {context}\nQuestion: {question}\nDetails: {records}")} else {format!("You are adjudicating records. Optional previous experience is fallible. Answer using only the final value (lowercase comma-separated IDs or one number). If you need the project's authoritative contract, return just READ to obtain it. Both reading and answering are allowed. Do not use tools.\nExperience: {context}\nTask: {question}\nRecords: {records}")};
    // hlx:70
    let mut docs=0;
    // hlx:71
    let mut result=ask(&dir,model,&prompt,claude);
    // hlx:72
    if result.as_deref()==Ok("READ"){docs=1;result=ask(&dir,model,&format!("{prompt}\nContract: {reference}\nNow return the final value."),claude);};
    // hlx:73
    let (grade,answer)=match result {Ok(a) if a==expected=>("pass",a),Ok(a)=>("wrong",a),Err(e)=>("infra",e)};
    // hlx:74
    println!("{id}\t{arm}\t{model}\t{}\t{elapsed}\t{docs}\t{}\t{grade}\t{}",context.len(),start.elapsed().as_millis(),answer.replace(['\r','\n','\t']," "));
    // hlx:75
    }
    // hlx:76
    fs::remove_dir_all(tmp).unwrap();
    // hlx:77
}