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 codex-trust`: Codex CLI runs a hook only after it is trusted (a hash saved in `config.toml`), and
//! skips an untrusted one without a word. This asks Codex itself, over its documented app-server protocol
//! (`hooks/list`, then `config/batchWrite`), which `instinct guard` / `instinct prompt` hooks are untrusted and
//! saves their trust, then lists again to confirm. It trusts only hooks whose command is `instinct guard|prompt`.
//! `--check` lists and changes nothing. std only; honours CODEX_HOME because Codex does.
use super::*;
use std::process::{Child, Command, Stdio};
use std::sync::mpsc;

const WAIT: Duration = Duration::from_secs(20);

struct Hook {
    key: String,
    event: String,
    command: String,
    hash: String,
    trusted: bool,
}

struct Server {
    child: Child,
    stdin: process::ChildStdin,
    lines: mpsc::Receiver<String>,
    next: u32,
}

impl Server {
    fn start() -> Result<Server, String> {
        let mut child = Command::new("codex")
            .arg("app-server")
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::null())
            .spawn()
            .map_err(|e| format!("could not start `codex app-server`: {e}. Is Codex CLI installed and on PATH?"))?;
        let stdin = child.stdin.take().ok_or("no stdin")?;
        let out = child.stdout.take().ok_or("no stdout")?;
        let (tx, rx) = mpsc::channel();
        std::thread::spawn(move || {
            for line in std::io::BufReader::new(out).lines().map_while(Result::ok) {
                if tx.send(line).is_err() {
                    break;
                }
            }
        });
        let mut s = Server { child, stdin, lines: rx, next: 1 };
        s.call("initialize", "{\"clientInfo\":{\"name\":\"instinct\",\"version\":\"0\"}}")?;
        s.send("{\"method\":\"initialized\"}")?;
        Ok(s)
    }

    fn send(&mut self, line: &str) -> Result<(), String> {
        writeln!(self.stdin, "{line}").and_then(|_| self.stdin.flush()).map_err(|e| format!("codex app-server closed: {e}"))
    }

    /// One request, and the `result` of the response with the same id (notifications are skipped).
    fn call(&mut self, method: &str, params: &str) -> Result<Json, String> {
        let id = self.next;
        self.next += 1;
        self.send(&format!("{{\"id\":{id},\"method\":\"{method}\",\"params\":{params}}}"))?;
        let end = std::time::Instant::now() + WAIT;
        loop {
            let left = end.saturating_duration_since(std::time::Instant::now());
            let line = self.lines.recv_timeout(left).map_err(|_| format!("codex app-server did not answer {method}"))?;
            let Ok(j) = parse_json(&line) else { continue };
            if j.get("id").and_then(Json::as_f64) != Some(id as f64) {
                continue;
            }
            if let Some(e) = j.get("error") {
                let msg = e.get("message").and_then(Json::as_str).unwrap_or("error");
                return Err(format!("codex {method}: {msg}"));
            }
            return j.get("result").cloned().ok_or_else(|| format!("codex {method}: no result"));
        }
    }
}

impl Drop for Server {
    fn drop(&mut self) {
        let _ = self.child.kill();
        let _ = self.child.wait();
    }
}

/// True for `instinct guard`, `instinct prompt`, `/path/to/instinct guard --flag`.
fn is_ours(command: &str) -> bool {
    let mut w = command.split_whitespace();
    let exe = w.next().unwrap_or("").rsplit(['/', '\\']).next().unwrap_or("");
    matches!(exe, "instinct" | "instinct.exe") && matches!(w.next(), Some("guard" | "prompt"))
}

fn list(s: &mut Server) -> Result<Vec<Hook>, String> {
    let cwd = std::env::current_dir().map(|p| p.display().to_string()).unwrap_or_else(|_| ".".into());
    let r = s.call("hooks/list", &format!("{{\"cwds\":[\"{}\"]}}", escape_json(&cwd)))?;
    let mut out = Vec::new();
    let Some(Json::Arr(entries)) = r.get("data") else { return Ok(out) };
    for e in entries {
        let Some(Json::Arr(hooks)) = e.get("hooks") else { continue };
        for h in hooks {
            let text = |k: &str| h.get(k).and_then(Json::as_str).unwrap_or("").to_string();
            let command = text("command");
            if !is_ours(&command) || out.iter().any(|x: &Hook| x.key == text("key")) {
                continue;
            }
            // A plugin hook reports "<hook hash>/<plugin hash>"; the saved trust is the first part.
            let hash = text("currentHash");
            let hash = hash.split('/').next().unwrap_or("").to_string();
            out.push(Hook { key: text("key"), event: text("eventName"), command, hash, trusted: text("trustStatus") == "trusted" });
        }
    }
    Ok(out)
}

pub fn run(argv: &[String]) -> Result<(), String> {
    let check = match argv {
        [] => false,
        [f] if f == "--check" => true,
        _ => return Err("usage: instinct codex-trust [--check]".into()),
    };
    let mut s = Server::start()?;
    let hooks = list(&mut s)?;
    if hooks.is_empty() {
        println!("Codex lists no `instinct guard` or `instinct prompt` hook. Install the plugin first: codex plugin marketplace add koscak-labs/instinct && codex plugin add instinct@koscak-labs");
        return Ok(());
    }
    let pending: Vec<&Hook> = hooks.iter().filter(|h| !h.trusted).collect();
    if check || pending.is_empty() {
        for h in &hooks {
            println!("{}  {}  ({})", if h.trusted { "trusted  " } else { "untrusted" }, h.command, h.event);
        }
        if !pending.is_empty() {
            println!("Codex skips untrusted hooks without a message. Run `instinct codex-trust` to trust them.");
        }
        return Ok(());
    }
    let value = pending
        .iter()
        .map(|h| format!("\"{}\":{{\"trusted_hash\":\"{}\"}}", escape_json(&h.key), escape_json(&h.hash)))
        .collect::<Vec<_>>()
        .join(",");
    s.call("config/batchWrite", &format!("{{\"edits\":[{{\"keyPath\":\"hooks.state\",\"value\":{{{value}}},\"mergeStrategy\":\"upsert\"}}]}}"))?;
    let after = list(&mut s)?;
    let mut bad = 0;
    for h in &after {
        println!("{}  {}  ({})", if h.trusted { "trusted  " } else { "untrusted" }, h.command, h.event);
        bad += usize::from(!h.trusted);
    }
    if bad > 0 {
        return Err(format!("{bad} hook(s) are still untrusted: approve them once with /hooks inside Codex"));
    }
    println!("Saved to Codex's config.toml. A hook edited later needs this again.");
    Ok(())
}

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

    #[test]
    fn only_instinct_guard_and_prompt_are_trusted() {
        assert!(is_ours("instinct guard"));
        assert!(is_ours("/home/a/.cargo/bin/instinct prompt --project x"));
        assert!(!is_ours("instinct mcp"));
        assert!(!is_ours("rm -rf / # instinct guard"));
        assert!(!is_ours("my-instinct guard"));
    }
}