instinct-cli 0.3.7

Shared local memory for coding agents. Save a fix once and find it again in a new session or another connected tool.
//! The savings meter: counts, never text. One line per lookup in `<store>.meter` (append-only, mode 600):
//! `unix_ts path lessons bytes_delivered bytes_whole_bank microseconds`. It is not part of the checksummed journal;
//! deleting it loses only the meter. `INSTINCT_METER=0` turns it off. A failed write never fails a lookup.
use super::*;
use std::cell::Cell;
use std::path::Path;
use std::time::Instant;

/// Stop appending past this size (about 80k lookups), so the file can never grow without bound.
const CAP: u64 = 4 << 20;
/// Bytes per token used for every estimate; printed wherever a token number is.
const BYTES_PER_TOKEN: u64 = 4;

thread_local! {
    static ARMED: Cell<bool> = const { Cell::new(false) };
    /// (bytes a memory file would add for the eligible set, microseconds spent computing that)
    static WHOLE: Cell<(u64, u64)> = const { Cell::new((0, 0)) };
}

pub fn enabled() -> bool {
    !matches!(
        std::env::var("INSTINCT_METER").as_deref(),
        Ok("0") | Ok("off") | Ok("false") | Ok("no")
    )
}

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

/// Called by the ranker with every lesson eligible in the lookup's scope; a no-op unless a lookup is being metered.
pub fn note_eligible(all: &[Discovery]) {
    if !ARMED.with(Cell::get) {
        return;
    }
    let t = Instant::now();
    let mut bytes = 0u64;
    for d in all {
        bytes += render_len(d) as u64;
    }
    bytes += 2 * all.len().saturating_sub(1) as u64;
    WHOLE.with(|w| w.set((bytes, t.elapsed().as_micros() as u64)));
}

pub struct Timer {
    store: PathBuf,
    kind: &'static str,
    start: Instant,
}

impl Drop for Timer {
    fn drop(&mut self) {
        ARMED.with(|a| a.set(false));
    }
}

/// Begins timing a lookup; `None` when the meter is off.
pub fn start(store: &Path, kind: &'static str) -> Option<Timer> {
    if !enabled() {
        return None;
    }
    ARMED.with(|a| a.set(true));
    WHOLE.with(|w| w.set((0, 0)));
    Some(Timer { store: store.to_path_buf(), kind, start: Instant::now() })
}

impl Timer {
    /// Records the lookup: lessons delivered and bytes handed to the agent. Errors are swallowed.
    pub fn finish(self, lessons: usize, bytes: usize) {
        let (whole, spent) = WHOLE.with(Cell::get);
        let us = (self.start.elapsed().as_micros() as u64).saturating_sub(spent);
        let line = format!("{} {} {lessons} {bytes} {whole} {us}\n", now_secs(), self.kind);
        let _ = write_line(&meter_path(&self.store), &line);
    }
}

fn write_line(path: &Path, line: &str) -> std::io::Result<()> {
    let mut o = journal::private_options();
    o.append(true).create(true);
    let mut f = o.open(path)?;
    if f.metadata()?.len() > CAP {
        return Ok(());
    }
    f.write_all(line.as_bytes())
}

/// recall/prompt: scoped recall, metered. Output is byte-identical to `op_recall_scoped`.
pub fn recall_text(
    path: &PathBuf,
    kind: &'static str,
    q: &str,
    k: usize,
    scope: &eligibility::Scope,
) -> Result<String, String> {
    let t = start(path, kind);
    let (text, ids) = op_recall_data(path, q, k, scope)?;
    if let Some(t) = t {
        t.finish(ids.len(), text.len());
    }
    Ok(text)
}

// ------------------------------------------------------------------ reading

#[derive(Default, Debug, PartialEq)]
pub struct Totals {
    pub lookups: u64,
    pub found: u64,
    pub empty: u64,
    pub delivered: u64,
    pub whole: u64,
    pub kept_out: u64,
    pub median_us: u64,
    pub p95_us: u64,
}

pub fn parse_since(s: &str) -> Result<Option<u64>, String> {
    if s == "all" {
        return Ok(None);
    }
    s.strip_suffix('d')
        .and_then(|n| n.parse::<u64>().ok())
        .filter(|n| *n > 0)
        .map(|n| Some(n * 86_400))
        .ok_or_else(|| "--since takes 7d, 30d, all, or N days like 14d".to_string())
}

/// Missing file, unreadable file, and malformed lines all read as "nothing recorded".
pub fn read(store: &Path, window: Option<u64>, now: u64) -> Totals {
    let text = match fs::read(meter_path(store)) {
        Ok(b) => String::from_utf8_lossy(&b).into_owned(),
        Err(_) => return Totals::default(),
    };
    let floor = window.map(|w| now.saturating_sub(w)).unwrap_or(0);
    let mut t = Totals::default();
    let mut times = Vec::new();
    let mut guard_bytes = 0u64;
    for line in text.lines() {
        let f: Vec<&str> = line.split(' ').collect();
        if f.len() != 6 {
            continue;
        }
        let n: Vec<Option<u64>> = [0, 2, 3, 4, 5].iter().map(|&i| f[i].parse().ok()).collect();
        let [Some(ts), Some(lessons), Some(bytes), Some(whole), Some(us)] = n[..] else { continue };
        if ts < floor || !matches!(f[1], "recall" | "decide" | "prompt" | "guard" | "mcp") {
            continue;
        }
        t.lookups += 1;
        if lessons > 0 { t.found += 1 } else { t.empty += 1 }
        t.delivered += bytes;
        // A memory file costs once per prompt, not once per tool call, so a tripwire check never counts
        // as keeping the whole bank out. What a tripwire adds is a real cost and is subtracted below.
        if f[1] == "guard" {
            guard_bytes += bytes;
        } else {
            t.whole += whole;
            t.kept_out += whole.saturating_sub(bytes);
        }
        times.push(us);
    }
    t.kept_out = t.kept_out.saturating_sub(guard_bytes);
    times.sort_unstable();
    if !times.is_empty() {
        t.median_us = times[times.len() / 2];
        t.p95_us = times[(times.len() * 95).div_ceil(100) - 1];
    }
    t
}

fn commas(n: u64) -> String {
    let s = n.to_string();
    let mut out = String::new();
    for (i, c) in s.chars().enumerate() {
        if i > 0 && (s.len() - i) % 3 == 0 {
            out.push(',');
        }
        out.push(c);
    }
    out
}

fn short(n: u64) -> String {
    match n {
        0..=9_999 => commas(n),
        10_000..=999_999 => format!("{:.1}k", n as f64 / 1e3),
        1_000_000..=999_999_999 => format!("{:.1}M", n as f64 / 1e6),
        _ => format!("{:.1}G", n as f64 / 1e9),
    }
}

fn ms(us: u64) -> String {
    if us > 0 && us < 100 {
        format!("{:.2} ms", us as f64 / 1000.0)
    } else {
        format!("{:.1} ms", us as f64 / 1000.0)
    }
}

fn window_label(since: &str) -> String {
    match since {
        "all" => "all recorded time".into(),
        d => format!("the last {} days", d.trim_end_matches('d')),
    }
}

pub struct Bank {
    pub hits: u32,
    pub misses: u32,
    pub proven: usize,
}

pub fn block(t: &Totals, bank: &Bank, since: &str) -> String {
    if t.lookups == 0 {
        return format!(
            "no metered lookups in {} (the meter starts counting at the first recall; INSTINCT_METER=0 turns it off) · {} hits / {} misses recorded · {} lessons proven (2+ hits, strength 0.6 or more)",
            window_label(since), bank.hits, bank.misses, bank.proven
        );
    }
    format!(
        "Savings, {}:\n  lookups served       {} ({} found a lesson, {} found nothing)\n  kept out of prompts  {} bytes versus pasting the whole bank each time, about {} tokens (estimate, about {BYTES_PER_TOKEN} bytes per token)\n  lookup time          {} median, {} p95\n  hits / misses        {} / {} recorded on the bank\n  lessons proven       {} (2+ hits, strength 0.6 or more)",
        window_label(since),
        commas(t.lookups),
        commas(t.found),
        commas(t.empty),
        commas(t.kept_out),
        short(t.kept_out / BYTES_PER_TOKEN),
        ms(t.median_us),
        ms(t.p95_us),
        bank.hits,
        bank.misses,
        bank.proven
    )
}

pub fn share(t: &Totals, bank: &Bank, since: &str) -> String {
    if t.lookups == 0 {
        return format!("Instinct has no metered lookups in {} yet.", window_label(since));
    }
    format!(
        "Instinct kept about {} tokens out of my agents' prompts in {} (estimate against pasting the whole bank, about {BYTES_PER_TOKEN} bytes per token): {} lookups, {} median, {} proven {}.",
        short(t.kept_out / BYTES_PER_TOKEN),
        window_label(since),
        commas(t.lookups),
        ms(t.median_us),
        bank.proven,
        if bank.proven == 1 { "lesson" } else { "lessons" }
    )
}

pub fn json(t: &Totals, bank: &Bank, since: &str) -> String {
    format!(
        "{{\"since\":\"{}\",\"lookups\":{},\"found\":{},\"empty\":{},\"bytes_delivered\":{},\"bytes_whole_bank\":{},\"bytes_kept_out\":{},\"tokens_kept_out_estimate\":{},\"bytes_per_token\":{BYTES_PER_TOKEN},\"median_us\":{},\"p95_us\":{},\"hits\":{},\"misses\":{},\"proven\":{}}}",
        escape_json(since), t.lookups, t.found, t.empty, t.delivered, t.whole, t.kept_out,
        t.kept_out / BYTES_PER_TOKEN, t.median_us, t.p95_us, bank.hits, bank.misses, bank.proven
    )
}

#[cfg(test)]
mod tests {
    use super::*;

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

    #[test]
    fn accounts_counts_and_percentiles() {
        let s = dir("acct");
        let now = now_secs();
        let body = format!(
            "{now} recall 2 100 1000 50\n{now} prompt 0 0 1000 10\n{now} guard 1 40 400 30\n{now} mcp 1 10 1000 20\n"
        );
        fs::write(meter_path(&s), body).unwrap();
        let t = read(&s, None, now);
        assert_eq!((t.lookups, t.found, t.empty), (4, 3, 1));
        // The guard line is a tripwire check: its 400-byte bank is not "kept out", and its 40 delivered
        // bytes count against the savings. Whole = 3 x 1000; kept out = 900 + 1000 + 990 - 40.
        assert_eq!((t.delivered, t.whole, t.kept_out), (150, 3000, 2850));
        assert_eq!((t.median_us, t.p95_us), (30, 50));
    }

    #[test]
    fn window_filters_old_lines() {
        let s = dir("win");
        let now = 10_000_000;
        let body = format!("{} recall 1 1 9 5\n{} recall 1 1 9 5\n{} recall 1 1 9 5\n", now - 40 * 86400, now - 3 * 86400, now);
        fs::write(meter_path(&s), body).unwrap();
        assert_eq!(read(&s, Some(7 * 86400), now).lookups, 2);
        assert_eq!(read(&s, Some(30 * 86400), now).lookups, 2);
        assert_eq!(read(&s, None, now).lookups, 3);
        assert_eq!(parse_since("7d"), Ok(Some(604_800)));
        assert_eq!(parse_since("all"), Ok(None));
        assert!(parse_since("week").is_err());
    }

    #[test]
    fn missing_and_corrupt_files_read_as_empty_or_skip_bad_lines() {
        let s = dir("bad");
        assert_eq!(read(&s, None, 100), Totals::default());
        fs::write(meter_path(&s), b"\xff\xfe garbage\n1 recall x 1 1 1\n1 nope 1 1 1 1\n\n5 recall 1 2 3 4\n1 recall 1 2\n").unwrap();
        let t = read(&s, None, 100);
        assert_eq!((t.lookups, t.delivered, t.whole), (1, 2, 3));
    }

    #[test]
    fn the_meter_file_holds_counts_only_and_is_private() {
        let s = dir("shape");
        fs::write(&s, "").unwrap();
        write_line(&meter_path(&s), "1 recall 1 2 3 4\n").unwrap();
        let text = fs::read_to_string(meter_path(&s)).unwrap();
        assert!(text.split_whitespace().all(|w| w == "recall" || w.chars().all(|c| c.is_ascii_digit())));
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            assert_eq!(fs::metadata(meter_path(&s)).unwrap().permissions().mode() & 0o777, 0o600);
        }
    }

    #[test]
    fn a_failed_write_is_silent() {
        let t = Timer { store: PathBuf::from("/nonexistent-dir/x/bank"), kind: "recall", start: Instant::now() };
        t.finish(1, 1); // must not panic
    }

    #[test]
    fn formats_are_plain() {
        assert_eq!(commas(1234567), "1,234,567");
        assert_eq!(short(1_200_000), "1.2M");
        assert_eq!(ms(300), "0.3 ms");
        let t = Totals { lookups: 2431, found: 2000, empty: 431, kept_out: 4_800_000, median_us: 300, p95_us: 900, ..Default::default() };
        let b = Bank { hits: 5, misses: 1, proven: 41 };
        let line = share(&t, &b, "7d");
        assert!(line.contains("1.2M tokens") && line.contains("estimate") && line.contains("2,431 lookups") && line.contains("41 proven"), "{line}");
        assert!(json(&t, &b, "7d").contains("\"tokens_kept_out_estimate\":1200000"));
    }
}