instinct-cli 0.3.8

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,
    /// The whole payload, for rewriting `tool_input`.
    pub payload: Json,
    pub tool: String,
    /// Codex payloads carry `turn_id`; Codex accepts a rewrite only with auto-approval, so it gets a warning.
    pub codex: bool,
    pub cwd: Option<String>,
    pub format: Format,
    pub session: Option<String>,
    /// The Bash command itself, for the retry tripwire.
    pub bash: 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 {
        tool: name.to_string(),
        codex: event.get("turn_id").is_some(),
        payload: event.clone(),
        // 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),
        bash: (name == "Bash").then(|| target.to_string()),
    })
}




/// JSON text of a value (numbers that are whole print without a fraction).
fn to_json(v: &Json) -> String {
    match v {
        Json::Null => "null".into(),
        Json::Bool(b) => b.to_string(),
        Json::Num(n) if n.fract() == 0.0 && n.abs() < 1e15 => format!("{}", *n as i64),
        Json::Num(n) => n.to_string(),
        Json::Str(s) => format!("\"{}\"", escape_json(s)),
        Json::Arr(a) => format!("[{}]", a.iter().map(to_json).collect::<Vec<_>>().join(",")),
        Json::Obj(o) => format!(
            "{{{}}}",
            o.iter().map(|(k, v)| format!("\"{}\":{}", escape_json(k), to_json(v))).collect::<Vec<_>>().join(",")
        ),
    }
}

/// Sets `key` on an object, replacing the value or appending the field.
fn set_field(obj: &mut Json, key: &str, val: Json) {
    if let Json::Obj(fields) = obj {
        match fields.iter_mut().find(|(k, _)| k == key) {
            Some(f) => f.1 = val,
            None => fields.push((key.to_string(), val)),
        }
    }
}

/// A rewrite for this call: the whole replacement `tool_input`, the notes for the model and the payload with the
/// change applied (for the timing bookkeeping).
struct Fixed {
    tool_input: Option<Json>,
    payload: Json,
    notes: Vec<String>,
}

/// The `fix:` step. Claude Code gets `updatedInput`; Codex only accepts a rewrite together with auto-approval, so
/// there it stays a warning that names the safe form. `None` when nothing applies or fixes are off.
fn fix_step(path: &PathBuf, scope: &eligibility::Scope, event: &Event, store_input: &str) -> Option<Fixed> {
    if !fix::enabled() || event.format != Format::Json || event.tool != "Bash" {
        return None;
    }
    let args = event.payload.get("tool_input")?;
    let cmd = args.get("command").and_then(Json::as_str)?;
    let rewritten = fix::rewrite(cmd, &|_| true);
    let slow = speed::bg_fix_enabled() && speed::slow_foreground(path, store_input);
    if rewritten.is_none() && !slow {
        return None;
    }
    let on = super::starter::fix_rules_on(path, scope);
    let rewritten = rewritten.and_then(|_| fix::rewrite(cmd, &|r| on.contains(r)));
    let background = slow && on.contains("bg-slow") && !event.codex;
    if rewritten.is_none() && !background {
        return None;
    }
    let mut tool_input = args.clone();
    let mut notes = Vec::new();
    if let Some((new, fired)) = &rewritten {
        let lesson = super::starter::fix_lesson(fired[0].rule);
        if event.codex {
            notes.push(format!(
                "Instinct would rewrite: {} -> {} (lesson {lesson}). Codex accepts a rewrite only with auto-approval, so this is a warning: run the safe form.",
                cmd.split_whitespace().collect::<Vec<_>>().join(" "),
                new.split_whitespace().collect::<Vec<_>>().join(" ")
            ));
        } else {
            set_field(&mut tool_input, "command", Json::Str(new.clone()));
            notes.push(fix::note(cmd, new, fired, &lesson));
        }
    }
    if background {
        set_field(&mut tool_input, "run_in_background", Json::Bool(true));
        notes.push(format!(
            "Instinct ran this call in the background: its class usually takes over {} s in the foreground here (lesson {}). You will be told when it finishes.",
            speed::SLOW_SECS,
            super::starter::fix_lesson("bg-slow")
        ));
    }
    if tool_input == *args {
        return Some(Fixed { tool_input: None, payload: event.payload.clone(), notes });
    }
    let mut payload = event.payload.clone();
    set_field(&mut payload, "tool_input", tool_input.clone());
    Some(Fixed { tool_input: Some(tool_input), payload, notes })
}

/// `retry` is the retry tripwire line (`INSTINCT_RETRY=1`); it stands alone or leads the lesson. `note` (the fix and
/// timing notes) follows the lesson.
fn render_fixed(lesson: &str, retry: Option<&str>, note: Option<&str>, format: &Format, updated: Option<&Json>) -> String {
    let mut text = if lesson.trim().is_empty() {
        retry.unwrap_or("").to_string()
    } else {
        let head = retry.map(|n| format!("{n}\n")).unwrap_or_default();
        format!("{head}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 => {
            let upd = updated.map(|u| format!("\"updatedInput\":{},", to_json(u))).unwrap_or_default();
            format!(
                "{{\"hookSpecificOutput\":{{\"hookEventName\":\"PreToolUse\",{upd}\"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());
    // Fix: a safe rewrite of the command, applied before it runs (Claude Code `updatedInput`); see fix.rs.
    let fixed = fix_step(&path, &scope, &event, &input);
    let timing_input = fixed.as_ref().map(|f| to_json(&f.payload));
    let timing_note = super::speed::before(&path, timing_input.as_deref().unwrap_or(&input));
    let note = match (&fixed, timing_note) {
        (Some(f), t) => {
            let mut n = f.notes.clone();
            n.extend(t);
            Some(n.join("\n"))
        }
        (None, t) => t,
    };
    let updated = fixed.as_ref().and_then(|f| f.tool_input.as_ref());
    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 retry = match (event.bash.as_deref(), sid) {
            (Some(c), Some(s)) => super::gates::retry_warning(&path, s, c, event.cwd.as_deref()),
            _ => None,
        };
        let out = if lesson.trim().is_empty() && retry.is_none() && note.is_none() {
            String::new()
        } else {
            render_fixed(&lesson, retry, note.as_deref(), &event.format, updated)
        };
        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}");
        }
    }
}