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


/// A lesson and/or one timing advisory, as one hook reply.
pub fn render_with(lesson: &str, note: Option<&str>, format: &Format) -> String {
    let mut text = if lesson.trim().is_empty() {
        String::new()
    } else {
        format!("Instinct tripwire (advisory, nothing is blocked): a saved lesson fits this action.\n{lesson}")
    };
    if let Some(n) = note {
        if !text.is_empty() {
            text.push('\n');
        }
        text.push_str(n);
    }
    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(),
    }
}

/// Adds the one-time first-run notice to a hook reply. Claude Code JSON gets a top-level `systemMessage`
/// (shown to the user, not the model); the plain-text format gets the sentence as one line.
pub fn with_notice(out: String, format: &Format, notice: &str) -> String {
    match format {
        Format::Json if out.is_empty() => format!("{{\"systemMessage\":\"{}\"}}", escape_json(notice)),
        Format::Json => match out.strip_prefix('{') {
            Some(rest) => format!("{{\"systemMessage\":\"{}\",{rest}", escape_json(notice)),
            None => out,
        },
        Format::Text if out.is_empty() => notice.to_string(),
        Format::Text => format!("{notice}\n{out}"),
        Format::Silent => out,
    }
}

/// 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,
        _ => {}
    }
    // First run: a bank that does not exist yet gets the starter tripwires before this call is answered.
    let explicit = a.opt("store").is_some() || std::env::var_os("INSTINCT_STORE").is_some_and(|v| !v.is_empty());
    let seeded = super::starter::seed_first_run(&path, explicit);
    if event.format == Format::Silent {
        return;
    }
    super::team::set_cwd(event.cwd.as_deref());
    let scope = eligibility::prompt_scope(a.opt("project"), event.cwd.as_deref());
    // Timing: note the start of this call and, for a class that usually runs long in the foreground, one advisory line.
    let note = super::speed::before(&path, &input);
    let timer = meter::start(&path, "guard");
    let sid = event.session.as_deref();
    let seen = sid.map(|s| session::seen(&path, s).lesson_ids()).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
        }),
    };
    {
        let mut methods = recalled.unwrap_or_default();
        methods.retain(|d| !seen.contains(&d.id));
        methods.truncate(1);
        if let Some(s) = sid {
            methods.retain(|d| session::claim_lesson(&path, s, &d.id, session::Source::Guard));
        }
        let (lesson, ids) = render_recall(&methods);
        let out = if lesson.trim().is_empty() && note.is_none() {
            String::new()
        } else {
            render_with(&lesson, note.as_deref(), &event.format)
        };
        if let Some(t) = timer {
            t.finish(if out.is_empty() { 0 } else { ids.len() }, out.len());
        }
        // What the USER sees (the model reads additionalContext, which is left exactly as rendered): in the JSON
        // format one top-level `systemMessage`, accepted by Claude Code and documented for Codex PreToolUse
        // (https://learn.chatgpt.com/docs/hooks). The text format only ever gets the first-run line.
        let mut said: Vec<String> = Vec::new();
        if let (Format::Json, false, Some(d)) = (&event.format, out.is_empty(), methods.first()) {
            let title = d.title.split_whitespace().collect::<Vec<_>>().join(" ");
            said.push(format!("Instinct tripwire: {title} (advisory, nothing was blocked)"));
        }
        if let (Format::Json, Some(n)) = (&event.format, &note) {
            said.push(n.clone());
        }
        if let Some(n) = seeded {
            said.push(super::starter::first_run_notice(n));
        }
        let out = if said.is_empty() { out } else { with_notice(out, &event.format, &said.join("\n")) };
        if !out.is_empty() {
            println!("{out}");
        }
    }
}