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 guard`: a pre-tool tripwire. Reads a harness PreToolUse-style payload on stdin, builds the
//! situation from the tool name plus its command or path, runs the same scoped recall as `instinct prompt`
//! (k=1), and prints the lesson as context. Advisory only: it never blocks, never exits non-zero, and is
//! silent on no match, bad input, or an unset store.
use super::*;

/// Context text above this is truncated; Claude Code caps hook context at 10,000 characters.
const MAX_CONTEXT: usize = 8000;

#[derive(Debug, PartialEq)]
pub enum Format {
    /// `{"hookSpecificOutput":{"hookEventName":"PreToolUse","additionalContext":...}}` (Claude Code, Codex).
    Json,
    /// Plain lesson text on stdout.
    Text,
    /// Print nothing.
    Silent,
}

pub struct Event {
    pub situation: String,
    pub cwd: Option<String>,
    pub format: Format,
    pub session: Option<String>,
}

fn first_str<'a>(v: &'a Json, keys: &[&str]) -> Option<&'a str> {
    keys.iter()
        .filter_map(|k| v.get(k).and_then(Json::as_str))
        .find(|s| !s.trim().is_empty())
}

/// Understands Claude Code and Codex PreToolUse (`tool_name`, `tool_input`), Gemini CLI BeforeTool
/// (same field names) and Copilot CLI camelCase preToolUse (`toolName`, `toolArgs`, possibly a JSON string).
pub fn parse(input: &str) -> Option<Event> {
    let event = parse_json(input).ok()?;
    let name = first_str(&event, &["tool_name", "toolName"])?;
    let args = event.get("tool_input").or_else(|| event.get("toolArgs"));
    let reparsed;
    let args = match args {
        Some(Json::Str(raw)) => {
            reparsed = parse_json(raw)
                .unwrap_or_else(|_| Json::Obj(vec![("command".into(), Json::Str(raw.clone()))]));
            Some(&reparsed)
        }
        other => other,
    };
    let target = args
        .and_then(|a| {
            first_str(
                a,
                &["command", "cmd", "file_path", "filePath", "path", "pattern", "url", "query"],
            )
        })
        .unwrap_or("");
    if target.is_empty() {
        return None;
    }
    let hook = first_str(&event, &["hook_event_name"]).unwrap_or("");
    let format = if hook == "BeforeTool" || event.get("toolName").is_some() {
        // No documented way to add context from these hooks without denying the call.
        Format::Silent
    } else {
        Format::Json
    };
    Some(Event {
        // The tool name becomes one `tool_<name>` word: lesson text never contains it by accident, so
        // it only counts toward a match when a lesson is tagged with it (for example `tool_bash pkill`).
        situation: format!("tool_{} {target}", name.to_lowercase()),
        cwd: event.get("cwd").and_then(Json::as_str).map(str::to_owned),
        format,
        session: first_str(&event, &["session_id", "sessionId"]).and_then(session::clean),
    })
}

pub fn render(lesson: &str, format: &Format) -> String {
    let mut text = format!(
        "Instinct tripwire (advisory, nothing is blocked): a saved lesson fits this action.\n{lesson}"
    );
    if text.len() > MAX_CONTEXT {
        let mut end = MAX_CONTEXT;
        while !text.is_char_boundary(end) {
            end -= 1;
        }
        text.truncate(end);
    }
    match format {
        Format::Json => format!(
            "{{\"hookSpecificOutput\":{{\"hookEventName\":\"PreToolUse\",\"additionalContext\":\"{}\"}}}}",
            escape_json(&text)
        ),
        Format::Text => text,
        Format::Silent => String::new(),
    }
}

/// Never returns an error: every failure is silence with exit 0.
pub fn run(a: &Args) {
    // Drain the payload before anything can return early, so the harness never writes into a closed pipe.
    let mut input = String::new();
    if std::io::stdin().take(1 << 20).read_to_string(&mut input).is_err() {
        return;
    }
    let Ok(path) = store_path(a) else { return };
    let Some(mut event) = parse(&input) else { return };
    match a.opt("format") {
        Some("text") => event.format = Format::Text,
        Some("json") => event.format = Format::Json,
        _ => {}
    }
    if event.format == Format::Silent {
        return;
    }
    let scope = eligibility::prompt_scope(a.opt("project"), event.cwd.as_deref());
    let timer = meter::start(&path, "guard");
    let sid = event.session.as_deref();
    let seen = sid.map(|s| session::delivered_ids(&path, s)).unwrap_or_default();
    // A lesson with a `cmd:` tag is matched on the command itself (whole words, in order) and never by prose.
    let recalled = match super::starter::guard_pick(&path, &event.situation, &scope, &seen) {
        Some(d) => Ok(vec![d]),
        None => recall_methods(&path, &event.situation, 41 + seen.len().min(10), &scope).map(|mut m| {
            m.retain(|d| !super::starter::has_cmd(d));
            m
        }),
    };
    if let Ok(mut methods) = recalled {
        methods.retain(|d| !seen.contains(&d.id));
        methods.truncate(1);
        // The explore arm: withhold a stable share by hash of session and lesson, and record it as held.
        if let (Some(s), Some(d)) = (sid, methods.first()) {
            if session::withheld(s, &d.id, session::explore_share()) {
                session::record_held(&path, s, std::slice::from_ref(&d.id), session::Source::Guard);
                methods.clear();
            }
        }
        let (lesson, ids) = render_recall(&methods);
        let out = if lesson.trim().is_empty() { String::new() } else { render(&lesson, &event.format) };
        if let Some(t) = timer {
            t.finish(if out.is_empty() { 0 } else { ids.len() }, out.len());
        }
        if let (Some(s), false) = (sid, out.is_empty()) {
            session::record_delivered(&path, s, &ids, session::Source::Guard);
        }
        if !out.is_empty() {
            println!("{out}");
        }
    }
}