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/recall_index.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::{
    collections::HashMap,
    path::{Path, PathBuf},
};
// hlx:3
use super::{eligibility::Scope, Discovery};
// hlx:4
#[derive(Debug, PartialEq, Eq)]
// hlx:5
struct Stamp {
    // hlx:6
    length: u64,
    // hlx:7
    device: u64,
    // hlx:8
    inode: u64,
    // hlx:9
    change: (i64, i64),
    // hlx:10
}
// hlx:11
#[cfg(unix)]
// hlx:12
fn stamp(path: &Path) -> Result<Option<Stamp>, String> {
    // hlx:13
    use std::os::unix::fs::MetadataExt;
    // hlx:14
    match std::fs::metadata(path) {
        // hlx:15
        Ok(m) => Ok(Some(Stamp {
            length: m.len(),
            device: m.dev(),
            inode: m.ino(),
            change: (m.ctime(), m.ctime_nsec()),
        })),
        // hlx:16
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
        // hlx:17
        Err(e) => Err(e.to_string()),
        // hlx:18
    }
    // hlx:19
}
// hlx:20
#[cfg(not(unix))]
// hlx:21
fn stamp(_: &Path) -> Result<Option<Stamp>, String> {
    // hlx:22
    Ok(None)
    // hlx:23
}
// hlx:24
pub(super) struct Index {
    // hlx:25
    stamp: Stamp,
    // hlx:26
    scope: [String; 5],
    // hlx:27
    since: u64,
    // hlx:28
    valid_until: u64,
    // hlx:29
    entries: Vec<Discovery>,
    // hlx:30
    lengths: Vec<usize>,
    // hlx:31
    avg: f32,
    // hlx:32
    postings: HashMap<String, Vec<(usize, usize)>>,
    // hlx:33
}
// hlx:34
fn build(stamp: Stamp, scope: [String; 5], entries: Vec<Discovery>, since: u64) -> Index {
    // hlx:35
    let mut lengths = Vec::with_capacity(entries.len());
    // hlx:36
    let mut postings: HashMap<String, Vec<(usize, usize)>> = HashMap::new();
    // hlx:37
    let mut valid_until = u64::MAX;
    // hlx:38
    for (id, d) in entries.iter().enumerate() {
        // hlx:39
        if d.meta.valid_until != 0 {
            // hlx:40
            valid_until = valid_until.min(d.meta.valid_until);
            // hlx:41
        }
        // hlx:42
        let words = super::tokens(&d.lex_text());
        // hlx:43
        lengths.push(words.len());
        // hlx:44
        let mut counts = HashMap::new();
        // hlx:45
        for word in words {
            // hlx:46
            *counts.entry(word).or_insert(0usize) += 1;
            // hlx:47
        }
        // hlx:48
        for (word, tf) in counts {
            // hlx:49
            postings.entry(word).or_default().push((id, tf));
            // hlx:50
        }
        // hlx:51
    }
    // hlx:52
    let avg = (lengths.iter().sum::<usize>() as f32 / entries.len().max(1) as f32).max(1.0);
    // hlx:53
    Index {
        stamp,
        scope,
        since,
        valid_until,
        entries,
        lengths,
        avg,
        postings,
    }
    // hlx:54
}
// hlx:55
fn scores(index: &Index, query: &str) -> Vec<f32> {
    // hlx:56
    let mut result = vec![0.0; index.entries.len()];
    // hlx:57
    let mut terms = super::tokens(query);
    // hlx:58
    terms.sort();
    // hlx:59
    terms.dedup();
    // hlx:60
    for term in terms {
        // hlx:61
        if let Some(list) = index.postings.get(&term) {
            // hlx:62
            let n = index.entries.len() as f32;
            // hlx:63
            let df = list.len() as f32;
            // hlx:64
            let idf = ((n - df + 0.5) / (df + 0.5) + 1.0).ln();
            // hlx:65
            for &(id, count) in list {
                // hlx:66
                let tf = count as f32;
                // hlx:67
                result[id] += idf * tf * 2.2
                    / (tf + 1.2 * (0.25 + 0.75 * index.lengths[id] as f32 / index.avg));
                // hlx:68
            }
            // hlx:69
        }
        // hlx:70
    }
    // hlx:71
    result
    // hlx:72
}
// hlx:73
pub(super) fn recall(
    cache: &mut Option<Index>,
    path: &PathBuf,
    query: &str,
    k: usize,
    scope: &Scope,
) -> Result<Vec<Discovery>, String> {
    // hlx:74
    if !cfg!(unix) || !super::helix_db::is_native(path) {
        // hlx:75
        return super::recall_methods(path, query, k, scope);
        // hlx:76
    }
    // hlx:77
    let Some(before) = stamp(path)? else {
        *cache = None;
        return Ok(Vec::new());
    };
    // hlx:78
    let context = [
        &scope.project,
        &scope.persona,
        &scope.harness,
        &scope.version,
        &scope.machine,
    ]
    .map(|s| s.to_owned());
    // hlx:79
    let now = super::now_secs();
    // hlx:80
    if !cache.as_ref().is_some_and(|i| {
        i.stamp == before && i.scope == context && now >= i.since && now <= i.valid_until
    }) {
        // hlx:81
        *cache = None;
        // hlx:82
        let entries = super::load_scoped(path, scope, now)?;
        // hlx:83
        if stamp(path)?.as_ref() != Some(&before) {
            // hlx:84
            return super::recall_methods(path, query, k, scope);
            // hlx:85
        }
        // hlx:86
        *cache = Some(build(before, context, entries, now));
        // hlx:87
    }
    // hlx:88
    let index = cache.as_ref().unwrap();
    // hlx:89
    super::rank_methods(path, query, k, scope, &index.entries, |action| {
        scores(index, action)
    })
    // hlx:90
}