instinct-cli 0.3.0

Local memory for AI coding agents: an MCP server and CLI that gives Claude Code, Codex, Cursor and any MCP client the one lesson that fits. Lessons that keep failing go quiet.
// generated by hxc 1.0.0-acgt-compiler from src/helix_db.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
include!("../runtime/helix-db.rs");
// hlx:3
use std::{
    fs::{self, File},
    io::{Read, Seek, SeekFrom},
    path::Path,
};
// hlx:4
use super::journal::private_options;
// hlx:6
pub fn is_native(path: &Path) -> bool {
    // hlx:7
    path.extension().is_some_and(|ext| ext == "hxdb")
    // hlx:8
}
// hlx:10
fn access_lock(path: &Path, write: bool) -> Result<File, String> {
    // hlx:11
    let mut name = path.as_os_str().to_owned();
    // hlx:12
    name.push(".io.lock");
    // hlx:13
    let file = if !write && Path::new(&name).exists() {
        File::open(name)
    } else {
        private_options()
            .create(true)
            .truncate(false)
            .read(true)
            .write(true)
            .open(name)
    }
    .map_err(|e| e.to_string())?;
    // hlx:14
    if write {
        // hlx:15
        file.lock().map_err(|e| e.to_string())?;
        // hlx:16
    } else {
        // hlx:17
        file.lock_shared().map_err(|e| e.to_string())?;
        // hlx:18
    }
    // hlx:19
    Ok(file)
    // hlx:20
}
// hlx:22
fn key(offset: u64) -> String {
    // hlx:23
    format!("event:{offset:016x}")
    // hlx:24
}
// hlx:27
fn decode(records: &str) -> Result<String, String> {
    // hlx:28
    let mut events = String::with_capacity(records.len());
    // hlx:29
    let mut offset = 0u64;
    // hlx:30
    for line in records.split_inclusive('\n') {
        // hlx:31
        let error = || format!("invalid Helix DB event at byte {offset}; restore a verified copy");
        // hlx:32
        let row = line.strip_suffix('\n').ok_or_else(error)?;
        // hlx:33
        let (stored_key, rest) = row.split_once("\tV\t").ok_or_else(error)?;
        // hlx:34
        let (sum, escaped) = rest.split_once(':').ok_or_else(error)?;
        // hlx:35
        let event = db_unesc(escaped);
        // hlx:36
        if stored_key != key(offset)
            || sum != format!("{:016x}", db_fnv(&event))
            || db_esc(&event) != escaped
            || event.contains('\n')
        {
            // hlx:37
            return Err(error());
            // hlx:38
        }
        // hlx:39
        events.push_str(&event);
        // hlx:40
        events.push('\n');
        // hlx:41
        offset += line.len() as u64;
        // hlx:42
    }
    // hlx:43
    Ok(events)
    // hlx:44
}
// hlx:46
pub fn read(path: &Path) -> Result<String, String> {
    // hlx:47
    if !path.try_exists().map_err(|e| e.to_string())? {
        // hlx:48
        return Ok(String::new());
        // hlx:49
    }
    // hlx:50
    let _lock = access_lock(path, false)?;
    // hlx:51
    let records =
        fs::read_to_string(path).map_err(|e| format!("cannot read {}: {e}", path.display()))?;
    // hlx:52
    decode(&records)
    // hlx:53
}
// hlx:56
fn put(file: &mut File, path: &Path, event: &str) -> Result<(), String> {
    // hlx:57
    let offset = file.seek(SeekFrom::End(0)).map_err(|e| e.to_string())?;
    // hlx:58
    let id = key(offset);
    // hlx:59
    db_putv(
        path.to_str().ok_or("Helix DB requires a UTF-8 path")?,
        &id,
        event,
    );
    // hlx:60
    let expected = format!("{id}\tV\t{:016x}:{}\n", db_fnv(event), db_esc(event));
    // hlx:61
    let mut actual = String::new();
    // hlx:62
    file.read_to_string(&mut actual)
        .map_err(|e| e.to_string())?;
    // hlx:63
    if expected != actual {
        // hlx:64
        return Err(format!(
            "Helix DB write verification failed at byte {offset}"
        ));
        // hlx:65
    }
    // hlx:66
    Ok(())
    // hlx:67
}
// hlx:69
pub fn append(path: &Path, event: &str) -> Result<(), String> {
    // hlx:70
    if let Some(dir) = path.parent() {
        // hlx:71
        fs::create_dir_all(dir).map_err(|e| e.to_string())?;
        // hlx:72
    }
    // hlx:73
    let _lock = access_lock(path, true)?;
    // hlx:74
    let mut file = private_options()
        .read(true)
        .write(true)
        .create(true)
        .truncate(false)
        .open(path)
        .map_err(|e| e.to_string())?;
    // hlx:75
    if file.metadata().map_err(|e| e.to_string())?.len() > 0 {
        // hlx:76
        file.seek(SeekFrom::End(-1)).map_err(|e| e.to_string())?;
        // hlx:77
        let mut last = [0u8];
        // hlx:78
        file.read_exact(&mut last).map_err(|e| e.to_string())?;
        // hlx:79
        if last != [b'\n'] {
            // hlx:80
            return Err("incomplete final Helix DB record; restore a verified copy".into());
            // hlx:81
        }
        // hlx:82
    }
    // hlx:83
    put(&mut file, path, event)?;
    // hlx:84
    file.sync_data().map_err(|e| e.to_string())
    // hlx:85
}
// hlx:88
pub fn import(path: &Path, events: &str) -> Result<usize, String> {
    // hlx:89
    if !is_native(path) {
        // hlx:90
        return Err("migration destination must end in .hxdb".into());
        // hlx:91
    }
    // hlx:92
    if let Some(dir) = path.parent() {
        // hlx:93
        fs::create_dir_all(dir).map_err(|e| e.to_string())?;
        // hlx:94
    }
    // hlx:95
    let _lock = access_lock(path, true)?;
    // hlx:96
    if path.try_exists().map_err(|e| e.to_string())? {
        // hlx:97
        return Err("migration destination already exists".into());
        // hlx:98
    }
    // hlx:99
    let mut staging_name = path.as_os_str().to_owned();
    // hlx:100
    let nonce = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_err(|e| e.to_string())?
        .as_nanos();
    // hlx:101
    staging_name.push(format!(".import-{}-{nonce}", std::process::id()));
    // hlx:102
    let staging = std::path::PathBuf::from(staging_name);
    // hlx:103
    let mut file = private_options()
        .read(true)
        .write(true)
        .create_new(true)
        .open(&staging)
        .map_err(|e| e.to_string())?;
    // hlx:104
    let result = (
        || -> Result<usize, String> {
            // hlx:105
            let mut normalized = String::new();
            // hlx:106
            let mut count = 0;
            // hlx:107
            for event in events.lines().filter(|s| !s.trim().is_empty()) {
                // hlx:108
                if super::parse_json(event)?
                    .get("kind")
                    .and_then(super::Json::as_str)
                    .is_none()
                {
                    // hlx:109
                    return Err("expected a bank event with a string kind".into());
                    // hlx:110
                }
                // hlx:111
                put(&mut file, &staging, event)?;
                // hlx:112
                normalized.push_str(event);
                // hlx:113
                normalized.push('\n');
                // hlx:114
                count += 1;
                // hlx:115
            }
            // hlx:116
            file.sync_all().map_err(|e| e.to_string())?;
            // hlx:117
            let stored = fs::read_to_string(&staging).map_err(|e| e.to_string())?;
            // hlx:118
            if decode(&stored)? != normalized {
                // hlx:119
                return Err("Helix DB import replay differs from source".into());
                // hlx:120
            }
            // hlx:121
            fs::hard_link(&staging, path)
                .map_err(|e| format!("cannot publish new Helix DB: {e}"))?;
            // hlx:122
            Ok(count)
            // hlx:123
        }
        // hlx:124
    )();
    // hlx:125
    drop(file);
    // hlx:126
    let _ = fs::remove_file(staging);
    // hlx:127
    result
    // hlx:128
}
// hlx:132
pub fn cue_similarity(query: &[String], cue: &str) -> f64 {
    // hlx:133
    let words = super::tokens(cue);
    // hlx:134
    if query.len() < 2 || query.len() != words.len() {
        // hlx:135
        return 0.0;
        // hlx:136
    }
    // hlx:137
    for (a, b) in query.iter().zip(&words) {
        // hlx:138
        if a != b
            && (a.chars().count().min(b.chars().count()) < 4
                || a.chars().next() != b.chars().next()
                || a.chars().count().abs_diff(b.chars().count()) > 1
                || db_sim(&db_trigrams(a), &db_trigrams(b)) < 0.35)
        {
            // hlx:139
            return 0.0;
            // hlx:140
        }
        // hlx:141
    }
    // hlx:142
    db_sim(
        &db_trigrams(&query.join(" ")),
        &db_trigrams(&words.join(" ")),
    )
    // hlx:143
}