instinct-cli 0.3.6

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.
//! `instinct starter [--apply] [--json] [--store PATH]`: the community tripwire pack (`community/tripwires.json`).
//!
//! A new bank is empty, so `instinct guard` has nothing to say. The pack is lessons for classic agent
//! disasters, each with its safe alternative. A dry run lists it; `--apply` banks it as `source: community`.
//! Idempotent: a lesson already in the bank (same id) is skipped, so a rerun banks 0.
//!
//! Command tags. A tag of the form `cmd:<tokens>` makes `instinct guard` match the lesson on the command
//! itself, because short commands (`rm`, `dd`, `-rf`) are never prose anchors. Words are the command split on
//! whitespace and `; | & ( )`, with quotes removed, and `>` and `>>` as words of their own.
//!   word    must appear as a whole word (`--force` does not match `--force-with-lease`), in order; flags and paths
//!           are case-sensitive (`-D` is not `-d`), a keyword of letters only (`where`, `flushall`) is not
//!   *text   a word containing `text` (`*$` is any word with a variable in it)
//!   !word   or `!*text`: the command must NOT contain it (`delete from !where`)
//!   =pat    a whole word, any case. `a|b` lists alternatives, `?` is one path segment (`=/home/?` is `/home/leduc`
//!           but not `/home/leduc/src`), `^` lets the word be cut short (`=-r^ecurse` is `-r`, `-rec`, `-recurse`)
//! Text that a reading command only prints is not a command: segments of grep, rg, echo, printf, man, cat, less, head,
//! tail, wc, ls, `git log` and `git grep` are dropped (their own `>` redirects stay), unless piped into a shell or a SQL client.
//! Several `cmd:` tags on one lesson are alternatives; the one with the most positive tokens wins.
//! Prose recall ignores `cmd:` lessons in `guard`, and `cmd:` tags are inert everywhere else.
//! Sibling access goes through `super::` because the playground compiles main.rs as a submodule.
use super::*;

const PACK: &str = include_str!("../community/tripwires.json");

pub const STARTER_HELP: &str = "usage: instinct starter [--apply] [--json] [--store PATH]\n\
The community tripwire pack: lessons for classic agent disasters, each with the safe alternative.\n\
  rm -rf on an unset variable, git push --force, git reset --hard, git clean -fdx, pkill -f, chmod -R 777,\n\
  dd of=/dev/..., DROP TABLE, DELETE without WHERE, terraform destroy, kubectl delete, curl | sh ...\n\
`instinct guard` (the pre-tool hook) shows the one that fits before the agent runs the command. It never blocks.\n\
  --apply       bank the lessons that are not in the bank yet, as source: community (default: dry run)\n\
  --store PATH  bank file to read and write (default: INSTINCT_STORE or the usual bank)\n\
  --json        print the pack, what is new and what is already banked as JSON\n\
Idempotent: lessons already in the bank are skipped, so a second --apply banks 0.";

struct Lesson {
    pack_id: String,
    title: String,
    when: String,
    found: String,
    how: String,
    evidence: String,
    reconsider: String,
    tags: String,
}

fn pack() -> Result<Vec<Lesson>, String> {
    let root = parse_json(PACK).map_err(|e| format!("community/tripwires.json: {e}"))?;
    let Json::Arr(items) = root else {
        return Err("community/tripwires.json: expected an array".into());
    };
    let mut out = Vec::new();
    for (i, it) in items.iter().enumerate() {
        let f = |k: &str| it.get(k).and_then(Json::as_str).unwrap_or("").to_string();
        let l = Lesson {
            pack_id: f("id"),
            title: f("title"),
            when: f("when"),
            found: f("found"),
            how: f("how"),
            evidence: f("evidence"),
            reconsider: f("reconsider"),
            tags: f("tags"),
        };
        if [&l.pack_id, &l.title, &l.when, &l.found, &l.how, &l.evidence, &l.tags].iter().any(|s| s.trim().is_empty()) {
            return Err(format!("community/tripwires.json: lesson {i} is missing a field"));
        }
        out.push(l);
    }
    Ok(out)
}

fn bank_in(l: &Lesson) -> BankIn {
    BankIn {
        title: l.title.clone(),
        when: l.when.clone(),
        found: l.found.clone(),
        how: l.how.clone(),
        evidence: l.evidence.clone(),
        reconsider: l.reconsider.clone(),
        tags: l.tags.clone(),
        project: String::new(),
        persona: String::new(),
        applicability_harness: String::new(),
        applicability_version: String::new(),
        applicability_machine: None,
    }
}

/// The id the lesson has once banked: unscoped, so the same on every machine.
fn bank_id(l: &Lesson) -> Result<String, String> {
    bank_discovery(bank_in(l), &eligibility::Scope::default()).map(|d| d.id)
}

/// How many lessons of the pack a bank does not hold yet, given the ids of the lessons it holds.
pub fn new_in(present: &HashSet<String>) -> Result<usize, String> {
    let mut n = 0;
    for l in &pack()? {
        if !present.contains(&bank_id(l)?) {
            n += 1;
        }
    }
    Ok(n)
}

pub fn run(argv: &[String]) -> Result<(), String> {
    let (mut apply, mut json, mut store) = (false, false, None);
    let mut it = argv.iter();
    while let Some(a) = it.next() {
        match a.as_str() {
            "--apply" => apply = true,
            "--json" => json = true,
            "--store" => store = Some(PathBuf::from(it.next().ok_or("--store needs a path")?)),
            "--help" | "-h" => {
                println!("{STARTER_HELP}");
                return Ok(());
            }
            other => return Err(format!("starter: unknown argument {other}\n\n{STARTER_HELP}")),
        }
    }
    let explicit = store.is_some() || std::env::var_os("INSTINCT_STORE").is_some_and(|v| !v.is_empty());
    let path = match store {
        Some(p) => Some(p),
        None => default_store().ok(),
    };
    if apply && path.is_none() {
        return Err("no home directory found: --apply needs a bank; set INSTINCT_STORE".into());
    }
    let lessons = pack()?;
    let mut present: HashSet<String> = HashSet::new();
    if let Some(p) = path.as_ref().filter(|p| p.is_file()) {
        present = load(p)?.into_iter().map(|d| d.id).collect();
    }
    let mut ids = Vec::new();
    for l in &lessons {
        ids.push(bank_id(l)?);
    }
    let new: Vec<usize> = (0..lessons.len()).filter(|&i| !present.contains(&ids[i])).collect();
    let mut banked = 0;
    if apply {
        let p = path.as_ref().expect("apply has a store");
        if !explicit {
            ensure_default_dir(p)?;
        }
        for &i in &new {
            let msg = op_bank_in(p, bank_in(&lessons[i]), "community", &eligibility::Scope::default())?;
            if msg.starts_with("banked") {
                banked += 1;
            }
        }
    }
    if json {
        let row = |i: usize| {
            let l = &lessons[i];
            format!(
                "{{\"id\":\"{}\",\"bank_id\":\"{}\",\"title\":\"{}\",\"banked\":{}}}",
                escape_json(&l.pack_id),
                escape_json(&ids[i]),
                escape_json(&l.title),
                !new.contains(&i)
            )
        };
        let all: Vec<String> = (0..lessons.len()).map(row).collect();
        println!(
            "{{\"source\":\"community\",\"pack\":{},\"new\":{},\"already_banked\":{},\"applied\":{apply},\"banked_now\":{banked},\"lessons\":[{}]}}",
            lessons.len(),
            new.len() - if apply { banked } else { 0 } + if apply { 0 } else { 0 },
            lessons.len() - new.len() + banked,
            all.join(",")
        );
        return Ok(());
    }
    println!(
        "community tripwire pack: {} lessons, {} not in your bank yet, {} already there",
        lessons.len(),
        new.len(),
        lessons.len() - new.len()
    );
    for (i, l) in lessons.iter().enumerate() {
        let mark = if apply && new.contains(&i) {
            "banked "
        } else if present.contains(&ids[i]) {
            "present"
        } else {
            "new    "
        };
        println!("  {mark}  {:<26} {}", l.pack_id, l.title);
    }
    if apply {
        println!("banked {banked} as source: community. `instinct guard` now warns before these commands.");
    } else {
        println!("Dry run. `instinct starter --apply` banks the {} new lessons.", new.len());
    }
    Ok(())
}

// ---------------------------------------------------------------- first run

/// What the user is told, once, on the call that created their bank.
pub fn first_run_notice(count: usize) -> String {
    format!(
        "Instinct created your bank with {count} starter tripwires. They warn before risky commands such as rm -rf on an empty variable and never block anything. Set INSTINCT_STARTER=0 to start empty."
    )
}

/// `INSTINCT_STARTER=0` (or `off` / `false`) keeps a new bank empty.
fn seeding_off() -> bool {
    std::env::var("INSTINCT_STARTER")
        .map(|v| matches!(v.trim().to_ascii_lowercase().as_str(), "0" | "off" | "false"))
        .unwrap_or(false)
}

/// Called by the `prompt` and `guard` hooks only. When the resolved bank file does not exist yet, banks exactly
/// what `instinct starter --apply` banks (same ids, state `community`, source `community`) and returns how many
/// lessons it banked. Returns `None` when nothing was seeded: opted out, the bank already exists, or any error
/// (hooks must never fail, so every error is swallowed). A missing folder for an explicit store is not created.
/// A `<store>.seed.lock` serialises two first calls: the second waits, sees the bank, and seeds nothing.
pub fn seed_first_run(path: &PathBuf, explicit: bool) -> Option<usize> {
    if seeding_off() || path.exists() {
        return None;
    }
    let seeded = std::panic::catch_unwind(|| seed_locked(path, explicit)).ok()?;
    seeded.ok().flatten()
}

fn seed_locked(path: &PathBuf, explicit: bool) -> Result<Option<usize>, String> {
    if explicit {
        if path.parent().is_some_and(|d| !d.as_os_str().is_empty() && !d.is_dir()) {
            return Ok(None);
        }
    } else {
        ensure_default_dir(path)?;
    }
    let mut lock_path = path.as_os_str().to_owned();
    lock_path.push(".seed.lock");
    let lock_path = PathBuf::from(lock_path);
    let lock = journal::private_options()
        .create(true)
        .truncate(false)
        .read(true)
        .write(true)
        .open(&lock_path)
        .map_err(|e| e.to_string())?;
    lock.lock().map_err(|e| e.to_string())?;
    let mut banked = 0;
    // Re-check under the lock: the call that held it first has already created the bank.
    if !path.exists() {
        for l in &pack()? {
            if let Ok(m) = op_bank_in(path, bank_in(l), "community", &eligibility::Scope::default()) {
                if m.starts_with("banked") {
                    banked += 1;
                }
            }
        }
    }
    drop(lock);
    let _ = std::fs::remove_file(&lock_path);
    Ok((banked > 0).then_some(banked))
}

// ---------------------------------------------------------------- command tags for `instinct guard`
// The matcher itself is authored in src/tripwire.hlx; this file only reads a lesson's tags and picks.

/// A lesson that matches on the command rather than on prose.
pub fn has_cmd(d: &Discovery) -> bool {
    tripwire::has_cmd(&d.tags)
}

/// The lesson's `cmd:` matchers, trimmed and sorted; empty for a prose lesson.
pub fn cmd_specs(d: &Discovery) -> Vec<String> {
    tripwire::cmd_specs(&d.tags)
}

/// The `cmd:` matchers a banked lesson is judged by. A lesson banked from the starter pack uses the pack's
/// current tags, so a matcher fix reaches banks made by an older version (the lesson id does not change).
fn current_tags(d: &Discovery) -> &str {
    static PACK_TAGS: std::sync::OnceLock<HashMap<String, String>> = std::sync::OnceLock::new();
    if d.meta.source != "community" {
        return &d.tags;
    }
    let tags = PACK_TAGS.get_or_init(|| {
        let mut m = HashMap::new();
        for l in pack().unwrap_or_default() {
            if let Ok(id) = bank_id(&l) {
                m.insert(id, l.tags);
            }
        }
        m
    });
    tags.get(&d.id).map_or(d.tags.as_str(), |t| t.as_str())
}

/// The best deliverable `cmd:` lesson for a `tool_bash <command>` situation, or None.
pub fn guard_pick(
    path: &PathBuf,
    situation: &str,
    scope: &eligibility::Scope,
    seen: &[String],
) -> Option<Discovery> {
    let command = situation.strip_prefix("tool_bash ")?;
    let w = tripwire::command_words(command);
    let now = now_secs();
    let all = load_scoped_for_cmd(path, scope, now).ok()?;
    let quiet = quiet_ids(path);
    let mut best: Option<(usize, usize)> = None;
    for (i, d) in all.iter().enumerate() {
        if seen.contains(&d.id)
            || eligibility::eligible(&d.meta, scope, now, None, d.hits, quiet.contains(&d.id)).is_err()
            || eligibility::quiet(d.hits, d.misses)
        {
            continue;
        }
        if let Some(n) = tripwire::best_match(current_tags(d), &w) {
            if best.is_none_or(|(_, b)| n > b) {
                best = Some((i, n));
            }
        }
    }
    best.map(|(i, _)| all[i].clone())
}

// ---------------------------------------------------------------- for `instinct scan`

/// The pack as (title, tags) pairs, for matching past commands against the tripwires. Empty if the pack is unreadable.
pub(crate) fn pack_matchers() -> Vec<(String, String)> {
    pack().map(|p| p.into_iter().map(|l| (l.title, l.tags)).collect()).unwrap_or_default()
}

/// (pack size, how many of its lessons the bank at the default location already holds); `None` when there is no
/// bank file to read. Reads only: no snapshot, no folder, no write.
pub(crate) fn banked_in_default() -> Option<(usize, usize)> {
    let lessons = pack().ok()?;
    let path = default_store().ok().filter(|p| p.is_file())?;
    let present: HashSet<String> = load_plain(&path).ok()?.into_iter().map(|d| d.id).collect();
    let n = lessons.iter().filter(|l| bank_id(l).is_ok_and(|id| present.contains(&id))).count();
    Some((lessons.len(), n))
}

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

    fn m(spec: &str, cmd: &str) -> bool {
        tripwire::spec_matches(spec, &tripwire::words(cmd)).is_some()
    }

    #[test]
    fn a_pack_lesson_banked_with_older_tags_is_judged_by_the_current_ones() {
        let l = pack().unwrap().into_iter().find(|l| l.pack_id == "mkfs-wipefs").unwrap();
        let mut d = bank_discovery(bank_in(&l), &eligibility::Scope::default()).unwrap();
        d.meta.source = "community".into();
        d.tags = "tool_bash;cmd:wipefs".into();
        assert_eq!(current_tags(&d), l.tags);
        assert!(tripwire::best_match(current_tags(&d), &tripwire::command_words("wipefs /dev/sdb")).is_none());
        assert!(tripwire::best_match(current_tags(&d), &tripwire::command_words("wipefs -a /dev/sdb")).is_some());
        // a lesson of the user's own, even with the same id, keeps its own tags
        d.meta.source = "banked".into();
        assert_eq!(current_tags(&d), "tool_bash;cmd:wipefs");
    }

    #[test]
    fn whole_words_in_order() {
        assert!(m("git push --force", "git push --force origin main"));
        assert!(m("git push --force", "cd x && git push origin main --force"));
        assert!(!m("git push --force", "git push --force-with-lease"));
        assert!(!m("git push --force", "git --force push"));
    }

    #[test]
    fn contains_and_negation() {
        assert!(m("rm -rf *$", "rm -rf \"$BUILD\"/*"));
        assert!(!m("rm -rf *$", "rm -rf ./target"));
        assert!(!m("rm -rf *$ !*:?", "rm -rf \"${BUILD:?}\"/*"));
        assert!(m("delete from !where", "psql -c \"DELETE FROM users\""));
        assert!(!m("delete from !where", "psql -c \"DELETE FROM users WHERE id = 1\""));
    }

    #[test]
    fn redirects_are_words() {
        assert!(m("> *.bashrc", "echo 'export A=1' >~/.bashrc"));
        assert!(!m("> *.bashrc", "echo 'export A=1' >> ~/.bashrc"));
    }

    #[test]
    fn the_pack_parses_and_every_cmd_spec_has_a_positive_token() {
        let lessons = pack().unwrap();
        assert!(lessons.len() >= 25);
        for l in lessons {
            assert!(l.tags.split(';').any(|t| t.trim().starts_with("cmd:")), "{}", l.pack_id);
        }
    }
}