instinct-cli 0.3.10

Shared local memory for coding agents. Save a fix once and find it again in a new session or another connected tool.
//! `instinct connect codex [--trust]`: writes the Instinct hooks into Codex CLI's `hooks.json`
//! (`$CODEX_HOME`, else `~/.codex`): `instinct guard` before shell commands, `instinct prompt` on each prompt.
//! Codex skips a hook it has not trusted, silently. Without `--trust` this prints the exact trust step; with
//! `--trust` it records trust only for the hooks in the file it just wrote, never for any other hook.
//! Use `--trust` when the user asked you to set Instinct up.
use super::*;

const GUARD: &str = "instinct guard";
const PROMPT: &str = "instinct prompt";

fn codex_home() -> Result<PathBuf, String> {
    if let Some(h) = std::env::var_os("CODEX_HOME").filter(|v| !v.is_empty()) {
        return Ok(PathBuf::from(h));
    }
    let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")).ok_or("no HOME")?;
    Ok(PathBuf::from(home).join(".codex"))
}

fn to_json(j: &Json) -> String {
    match j {
        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(",")
        ),
    }
}

fn has_command(group_list: &Json, cmd: &str) -> bool {
    let Json::Arr(groups) = group_list else { return false };
    groups.iter().any(|g| {
        matches!(g.get("hooks"), Some(Json::Arr(hs)) if hs.iter().any(|h| h.get("command").and_then(Json::as_str) == Some(cmd)))
    })
}

fn group(matcher: Option<&str>, cmd: &str, timeout: u32) -> Json {
    let mut f = Vec::new();
    if let Some(m) = matcher {
        f.push(("matcher".to_string(), Json::Str(m.into())));
    }
    let hook = Json::Obj(vec![
        ("type".into(), Json::Str("command".into())),
        ("command".into(), Json::Str(cmd.into())),
        ("timeout".into(), Json::Num(timeout as f64)),
    ]);
    f.push(("hooks".into(), Json::Arr(vec![hook])));
    Json::Obj(f)
}

/// The hooks.json text with both Instinct hooks present, and whether anything was added.
fn merged(existing: &str) -> Result<(String, bool), String> {
    let mut root = if existing.trim().is_empty() { Json::Obj(vec![]) } else { parse_json(existing).map_err(|e| format!("hooks.json is not valid JSON ({e}); fix or move it first"))? };
    let Json::Obj(top) = &mut root else { return Err("hooks.json is not a JSON object".into()) };
    if !top.iter().any(|(k, _)| k == "hooks") {
        top.push(("hooks".into(), Json::Obj(vec![])));
    }
    let Some((_, Json::Obj(events))) = top.iter_mut().find(|(k, _)| k == "hooks") else { return Err("`hooks` in hooks.json is not an object".into()) };
    let mut changed = false;
    for (event, matcher, cmd, timeout) in [("PreToolUse", Some("Bash"), GUARD, 10u32), ("UserPromptSubmit", None, PROMPT, 10)] {
        if !events.iter().any(|(k, _)| k == event) {
            events.push((event.into(), Json::Arr(vec![])));
        }
        let Some((_, Json::Arr(list))) = events.iter_mut().find(|(k, _)| k == event) else { return Err(format!("`hooks.{event}` is not an array")) };
        if !has_command(&Json::Arr(list.clone()), cmd) {
            list.push(group(matcher, cmd, timeout));
            changed = true;
        }
    }
    Ok((to_json(&root), changed))
}

/// Adds both hooks to `file` (backing up an existing one as `<name>.bak-instinct`). Returns whether it changed.
fn write_hooks(file: &Path) -> Result<bool, String> {
    let existing = match fs::read_to_string(file) {
        Ok(t) => t,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
        Err(e) => return Err(format!("cannot read {}: {e}", file.display())),
    };
    let (text, changed) = merged(&existing)?;
    if !changed {
        println!("{} already has both Instinct hooks", file.display());
        return Ok(false);
    }
    if let Some(dir) = file.parent() {
        fs::create_dir_all(dir).map_err(|e| format!("cannot create {}: {e}", dir.display()))?;
    }
    if !existing.trim().is_empty() {
        let bak = file.with_extension("json.bak-instinct");
        fs::write(&bak, &existing).map_err(|e| format!("cannot back up to {}: {e}", bak.display()))?;
        println!("backed up the old file to {}", bak.display());
    }
    fs::write(file, format!("{text}\n")).map_err(|e| format!("cannot write {}: {e}", file.display()))?;
    println!("wrote `{GUARD}` (PreToolUse, matcher Bash) and `{PROMPT}` (UserPromptSubmit) to {}", file.display());
    Ok(true)
}

/// Runs `claude <args>` and prints what it did; false when it could not run or failed.
fn claude_step(args: &[&str]) -> bool {
    println!("$ claude {}", args.join(" "));
    match std::process::Command::new("claude").args(args).stdin(std::process::Stdio::null()).output() {
        Ok(o) => {
            for l in String::from_utf8_lossy(&o.stdout).lines().chain(String::from_utf8_lossy(&o.stderr).lines()).filter(|l| !l.trim().is_empty()).take(6) {
                println!("    {l}");
            }
            o.status.success()
        }
        Err(e) => {
            println!("    could not run claude: {e}");
            false
        }
    }
}

fn claude(rest: &[String]) -> Result<(), String> {
    const USAGE: &str = "usage: instinct connect claude [--user]";
    if rest.iter().any(|a| a != "--user") {
        return Err(USAGE.into());
    }
    let scope = if rest.is_empty() { "local" } else { "user" };
    let have_cli = std::process::Command::new("claude").arg("--version").stdin(std::process::Stdio::null()).output().is_ok();
    if have_cli {
        println!("scope: {scope} ({})", if scope == "local" { "this project only, not shared" } else { "every project for this user" });
        let mut ok = true;
        // A marketplace that is already added reports an error; the installs below are what matter.
        claude_step(&["plugin", "marketplace", "add", "koscak-labs/instinct", "--scope", scope]);
        for p in ["instinct@koscak-labs", "instinct-autorecall@koscak-labs"] {
            ok &= claude_step(&["plugin", "install", p, "--scope", scope]);
        }
        if !ok {
            return Err("a claude command failed (see above); nothing else was changed".into());
        }
        println!("installed the Instinct plugin (tripwires, skill, MCP) and the autorecall plugin at {scope} scope. Start a new Claude Code session to load them.");
        return Ok(());
    }
    let file = if scope == "local" {
        std::env::current_dir().map_err(|e| e.to_string())?.join(".claude").join("settings.local.json")
    } else {
        PathBuf::from(std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")).ok_or("no HOME")?).join(".claude").join("settings.json")
    };
    println!("the claude CLI is not on PATH, so the hooks go into the settings file instead");
    write_hooks(&file)?;
    println!("for MCP recall, run: claude mcp add --transport stdio --scope {scope} instinct -- instinct mcp");
    Ok(())
}

pub fn run(argv: &[String]) -> Result<(), String> {
    const USAGE: &str = "usage: instinct connect codex [--trust] | instinct connect claude [--user] | instinct connect cursor|vscode|gemini|windsurf [--user] [--dry-run]";
    let (target, rest) = argv.split_first().ok_or(USAGE)?;
    if matches!(target.as_str(), "cursor" | "vscode" | "gemini" | "windsurf") {
        return super::connect_mcp::run(argv);
    }
    if target == "claude" {
        return claude(rest);
    }
    if target != "codex" || rest.iter().any(|a| a != "--trust") {
        return Err(USAGE.into());
    }
    let trust = !rest.is_empty();
    let file = codex_home()?.join("hooks.json");
    write_hooks(&file)?;
    if trust {
        println!("--trust: recording trust only for the hooks in {} that run `{GUARD}` or `{PROMPT}`; no other hook is touched", file.display());
        codex_trust::trust(false, Some(&format!("{}:", file.display())))
    } else {
        println!("Codex skips a hook it has not trusted, with no message. Trust these once: `instinct codex-trust` (or `instinct connect codex --trust`, if the user asked you to set Instinct up), or approve them with /hooks inside Codex.");
        Ok(())
    }
}

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

    #[test]
    fn adds_both_hooks_once_and_keeps_other_hooks() {
        let (a, changed) = merged("").unwrap();
        assert!(changed && a.contains("\"matcher\":\"Bash\"") && a.contains("instinct prompt"));
        let (b, changed) = merged(&a).unwrap();
        assert!(!changed);
        assert_eq!(a, b);
        let other = "{\"hooks\":{\"PreToolUse\":[{\"matcher\":\"Bash\",\"hooks\":[{\"type\":\"command\",\"command\":\"mine\"}]}]}}";
        let (c, changed) = merged(other).unwrap();
        assert!(changed && c.contains("\"command\":\"mine\"") && c.contains("instinct guard"));
        assert!(merged("[1]").is_err());
    }
}