instinct-cli 0.3.9

Shared local memory for coding agents. Save a fix once and find it again in a new session or another connected tool.
//! Team memory: a project bank at `<repo>/.instinct/lessons.jsonl`, read as a second layer after the user's own bank.
//!
//! The file is a plain JSONL journal that git merges with `merge=union`. A union merge keeps both sides' lines but
//! may interleave them, so a hit can land above the lesson it counts and a line can appear twice. Before the fold
//! sees the file it is normalized: unreadable lines are skipped, identical lines collapse, and the rows are sorted
//! (lessons first, then events by time, ties by text). The result depends only on the SET of lines, never on file order.
use super::{parse_json, Discovery, Json};
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::Mutex;

pub(super) const DIR: &str = ".instinct";
pub(super) const FILE: &str = "lessons.jsonl";
const ATTRIBUTES: &str = "lessons.jsonl merge=union\n";
/// Local files the engine keeps beside the bank: its write lock and its index snapshot. Neither is shared.
const IGNORED: [&str; 3] = ["*.lock", "*.idx", "*.idx.tmp*"];

/// The cwd a hook payload reported; the process cwd is used when none was.
static HOOK_CWD: Mutex<Option<String>> = Mutex::new(None);
/// Set while a `--team` bank is written: a shared line carries no model-specific vector.
pub(super) static WRITING_TEAM: AtomicBool = AtomicBool::new(false);
static NOTED: AtomicBool = AtomicBool::new(false);
static SEQ: AtomicU64 = AtomicU64::new(0);

pub(super) fn set_cwd(cwd: Option<&str>) {
    if let (Some(c), Ok(mut slot)) = (cwd.filter(|c| Path::new(c).is_absolute()), HOOK_CWD.lock()) {
        *slot = Some(c.to_string());
    }
}

/// `INSTINCT_TEAM=0` turns the project bank off for reading and for `--team` writes.
pub(super) fn enabled() -> bool {
    std::env::var("INSTINCT_TEAM").map_or(true, |v| v.trim() != "0")
}

fn home() -> Option<PathBuf> {
    std::env::var_os("HOME")
        .filter(|v| !v.is_empty())
        .or_else(|| std::env::var_os("USERPROFILE").filter(|v| !v.is_empty()))
        .map(PathBuf::from)
}

/// Walk up from `start` to the nearest `.instinct/lessons.jsonl`. The walk ends at the git root (a folder holding
/// `.git`) and at the home directory, which is never itself a project.
pub(super) fn find_from(start: &Path, home: Option<&Path>) -> Option<PathBuf> {
    for dir in start.ancestors() {
        if home.is_some_and(|h| h == dir) {
            return None;
        }
        let candidate = dir.join(DIR).join(FILE);
        if candidate.is_file() {
            return Some(candidate);
        }
        if dir.join(".git").exists() {
            return None;
        }
    }
    None
}

/// The project bank for this run, if there is one and it is not the user's own store.
pub(super) fn find(user_store: &Path) -> Option<PathBuf> {
    if !enabled() {
        return None;
    }
    let hooked = HOOK_CWD.lock().ok().and_then(|g| g.clone()).map(PathBuf::from);
    let start = hooked.or_else(|| std::env::current_dir().ok())?;
    let found = find_from(&start, home().as_deref())?;
    let same = |a: &Path, b: &Path| match (a.canonicalize(), b.canonicalize()) {
        (Ok(a), Ok(b)) => a == b,
        _ => a == b,
    };
    if same(&found, user_store) {
        return None;
    }
    Some(found)
}

/// One note per process, on stderr, for rows the fold could not use.
fn note(path: &Path, skipped: usize, first: usize) {
    if skipped > 0 && !NOTED.swap(true, Ordering::Relaxed) {
        eprintln!(
            "instinct: skipped {skipped} unreadable line(s) in {} (first at line {first}); the rest is used",
            path.display()
        );
    }
}

/// The rows of a project bank as one text, in an order that does not depend on the file's order.
pub(super) fn normalize(text: &str, path: &Path) -> String {
    let mut seen: HashSet<&str> = HashSet::new();
    let mut rows: Vec<(u8, u64, &str)> = Vec::new();
    let (mut skipped, mut first) = (0usize, 0usize);
    for (n, raw) in text.lines().enumerate() {
        let line = raw.trim();
        if line.is_empty() || !seen.insert(line) {
            continue;
        }
        let usable = match parse_json(line) {
            Ok(v @ Json::Obj(_)) => {
                let kind = v.get("kind").and_then(Json::as_str).unwrap_or("");
                let machine_missing = kind == "machine_discovery"
                    && v.get("scope_machine").and_then(Json::as_str).unwrap_or("").trim().is_empty();
                (!machine_missing).then(|| {
                    let rank = u8::from(!matches!(kind, "discovery" | "machine_discovery"));
                    (rank, v.get("ts").and_then(Json::as_f64).unwrap_or(0.0) as u64)
                })
            }
            _ => None,
        };
        match usable {
            Some((rank, ts)) => rows.push((rank, ts, line)),
            None => {
                if skipped == 0 {
                    first = n + 1;
                }
                skipped += 1;
            }
        }
    }
    note(path, skipped, first);
    rows.sort();
    let mut out = String::with_capacity(text.len() + 1);
    for (_, _, line) in rows {
        out.push_str(line);
        out.push('\n');
    }
    out
}

/// The project bank folded on its own, rows normalized first.
pub(super) fn load(path: &Path) -> Result<Vec<Discovery>, String> {
    let text = super::journal::read(path)?;
    super::fold_text(&normalize(&text, path), &path.display().to_string(), |_, _, _, _| {})
}

/// `load`, leaving a verified index snapshot next to the file for the next hook (the same one the user's bank
/// gets, so a hook over 2,000 shared lessons does not fold them again). The snapshot is a local cache, ignored by git.
pub(super) fn load_indexed(path: &Path) -> Result<Vec<Discovery>, String> {
    #[cfg(not(target_arch = "wasm32"))]
    let key = super::snapshot::key(path);
    let all = load(path)?;
    #[cfg(not(target_arch = "wasm32"))]
    if let Some(key) = &key {
        super::snapshot::store(path, key, &all);
    }
    Ok(all)
}

/// The project bank's lessons that fit `scope`, from its snapshot when one matches the file. A project bank
/// that cannot be folded is left out with one stderr note; it never stops a hook.
pub(super) fn scoped(path: &Path, scope: &super::eligibility::Scope, now: u64) -> Vec<Discovery> {
    #[cfg(not(target_arch = "wasm32"))]
    if let Some((all, _, _)) = super::snapshot::key(path).and_then(|k| super::snapshot::open(path, &k, scope, now)) {
        return all;
    }
    match load_indexed(path) {
        Ok(all) => all.into_iter().filter(|d| super::eligibility::scope_check(&d.meta, scope, now).is_ok()).collect(),
        Err(e) => {
            eprintln!("instinct: project bank {} not used ({e})", path.display());
            Vec::new()
        }
    }
}

/// True when the project bank's text contains `needle` (a raw scan; a false yes only costs a fold).
pub(super) fn mentions(path: &Path, needle: &str) -> bool {
    std::fs::read_to_string(path).map_or(true, |t| t.contains(needle))
}

/// True when the project bank holds a lesson with this id (a text scan; nothing is folded).
pub(super) fn has_lesson(path: &Path, id: &str) -> bool {
    let Ok(text) = super::journal::read(path) else { return false };
    text.lines().filter(|l| l.contains(id)).any(|l| {
        parse_json(l).is_ok_and(|v| {
            matches!(v.get("kind").and_then(Json::as_str), Some("discovery" | "machine_discovery"))
                && v.get("id").and_then(Json::as_str) == Some(id)
        })
    })
}

/// A key no other teammate's event can share, so a line that arrives twice through git counts once and two
/// real events in the same second both count.
pub(super) fn event_key() -> String {
    #[cfg(not(target_arch = "wasm32"))]
    let salt = {
        let nanos = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.subsec_nanos() as u64)
            .unwrap_or(0);
        (nanos << 20) ^ ((std::process::id() as u64) << 4) ^ SEQ.fetch_add(1, Ordering::Relaxed)
    };
    #[cfg(target_arch = "wasm32")]
    let salt = SEQ.fetch_add(1, Ordering::Relaxed);
    format!("team:{}-{salt:x}", super::now_secs())
}

/// The folder a new project bank belongs in: the git root above `start`, else `start` itself.
fn root_of(start: &Path) -> PathBuf {
    start
        .ancestors()
        .find(|d| d.join(".git").exists())
        .unwrap_or(start)
        .to_path_buf()
}

/// Make sure the bank's folder keeps its lock file out of git.
pub(super) fn ensure_ignore(bank: &Path) {
    if let Some(dir) = bank.parent() {
        let p = dir.join(".gitignore");
        let mut text = std::fs::read_to_string(&p).unwrap_or_default();
        let before = text.len();
        for pat in IGNORED {
            if !text.lines().any(|l| l.trim() == pat) {
                if !text.is_empty() && !text.ends_with('\n') {
                    text.push('\n');
                }
                text.push_str(pat);
                text.push('\n');
            }
        }
        if text.len() != before {
            let _ = std::fs::write(p, text);
        }
    }
}

/// `instinct team init`: the folder, the union-merge rule and an empty bank. Safe to run again.
pub(super) fn init(start: &Path) -> Result<String, String> {
    let root = root_of(start);
    let dir = root.join(DIR);
    std::fs::create_dir_all(&dir).map_err(|e| format!("cannot create {}: {e}", dir.display()))?;
    let write = |p: PathBuf, text: &str| std::fs::write(&p, text).map_err(|e| format!("cannot write {}: {e}", p.display()));
    let attr = dir.join(".gitattributes");
    match std::fs::read_to_string(&attr) {
        Ok(t) if t.lines().any(|l| l.split_whitespace().eq(["lessons.jsonl", "merge=union"])) => {}
        Ok(t) => write(attr, &format!("{}{}{ATTRIBUTES}", t, if t.is_empty() || t.ends_with('\n') { "" } else { "\n" }))?,
        Err(_) => write(attr, ATTRIBUTES)?,
    }
    ensure_ignore(&dir.join(FILE));
    let bank = dir.join(FILE);
    if !bank.exists() {
        write(bank.clone(), "")?;
    }
    Ok(format!(
        "project bank ready: {}\nnext: git add {DIR} && git commit; teammates get it on pull; bank with `instinct bank --team ...`",
        bank.display()
    ))
}

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

    #[test]
    fn rows_do_not_depend_on_file_order_and_repeats_collapse() {
        let d = r#"{"kind":"discovery","id":"in-a","ts":5}"#;
        let h = r#"{"kind":"hit","id":"in-a","ts":9,"outcome_id":"k"}"#;
        let p = Path::new("x");
        let one = normalize(&format!("{d}\n{h}\n"), p);
        assert_eq!(one, normalize(&format!("{h}\n{d}\n{h}\n{d}\n"), p));
        assert!(one.starts_with(d));
    }

    #[test]
    fn walk_stops_at_the_git_root_and_at_home() {
        let base = std::env::temp_dir().join(format!("instinct-team-unit-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&base);
        let deep = base.join("repo").join("a").join("b");
        std::fs::create_dir_all(&deep).unwrap();
        std::fs::create_dir_all(base.join(DIR)).unwrap();
        std::fs::write(base.join(DIR).join(FILE), "").unwrap();
        // a bank above the git root is not this repo's
        std::fs::create_dir_all(base.join("repo").join(".git")).unwrap();
        assert_eq!(find_from(&deep, None), None);
        std::fs::create_dir_all(base.join("repo").join(DIR)).unwrap();
        std::fs::write(base.join("repo").join(DIR).join(FILE), "").unwrap();
        assert_eq!(find_from(&deep, None), Some(base.join("repo").join(DIR).join(FILE)));
        // home itself is never a project
        assert_eq!(find_from(&base, Some(&base)), None);
        let _ = std::fs::remove_dir_all(&base);
    }
}