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.
//! `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`)
//! 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)
}

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(())
}

// ---------------------------------------------------------------- command tags for `instinct guard`

/// A lesson that matches on the command rather than on prose.
pub fn has_cmd(d: &Discovery) -> bool {
    d.tags.split(';').any(|t| t.trim().to_lowercase().starts_with("cmd:"))
}

/// The lesson's `cmd:` matchers, trimmed and sorted; empty for a prose lesson.
pub fn cmd_specs(d: &Discovery) -> Vec<String> {
    let mut v: Vec<String> = d.tags.split(';').map(str::trim).filter(|t| t.to_lowercase().starts_with("cmd:")).map(str::to_owned).collect();
    v.sort();
    v
}

/// The command as lower-cased whole words: quotes dropped, `; | & ( )` as separators, `>` and `>>` apart.
pub fn words(command: &str) -> Vec<String> {
    let mut s = String::with_capacity(command.len() + 8);
    let mut chars = command.chars().peekable();
    while let Some(c) = chars.next() {
        match c {
            '"' | '\'' | '`' => {}
            ';' | '|' | '&' | '(' | ')' => s.push(' '),
            '>' => {
                if chars.peek() == Some(&'>') {
                    chars.next();
                    s.push_str(" >> ");
                } else {
                    s.push_str(" > ");
                }
            }
            c => s.push(c),
        }
    }
    s.split_whitespace().map(str::to_owned).collect()
}

/// Flags and paths compare exactly (`-D` is not `-d`); a token of letters only (a keyword such as `where` or
/// `flushall`) ignores case, and so does `*text` unless it starts with `-`.
fn token_hits(tok: &str, word: &str) -> bool {
    match tok.strip_prefix('*') {
        Some("") => word == "*",
        Some(sub) => word.contains(sub) || (!sub.starts_with('-') && word.to_lowercase().contains(&sub.to_lowercase())),
        None => word == tok || (tok.chars().all(|c| c.is_ascii_alphabetic()) && word.eq_ignore_ascii_case(tok)),
    }
}

/// Number of positive tokens when the spec matches the words, else None.
pub fn spec_matches(spec: &str, words: &[String]) -> Option<usize> {
    let mut at = 0;
    let mut positive = 0;
    for tok in spec.split_whitespace() {
        if let Some(neg) = tok.strip_prefix('!') {
            if words.iter().any(|w| token_hits(neg, w)) {
                return None;
            }
            continue;
        }
        let found = words.iter().skip(at).position(|w| token_hits(&tok, w))?;
        at += found + 1;
        positive += 1;
    }
    (positive > 0).then_some(positive)
}

/// 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 = words(command);
    let now = now_secs();
    let all = load_scoped(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;
        }
        for t in d.tags.split(';') {
            let t = t.trim();
            let Some(spec) = t.get(..4).filter(|p| p.eq_ignore_ascii_case("cmd:")).map(|_| &t[4..]) else {
                continue;
            };
            if let Some(n) = spec_matches(spec, &w) {
                if best.is_none_or(|(_, b)| n > b) {
                    best = Some((i, n));
                }
            }
        }
    }
    best.map(|(i, _)| all[i].clone())
}

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

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

    #[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);
        }
    }
}