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 cursor|vscode|gemini|windsurf [--user] [--dry-run]`: one command per harness.
//!
//! Each target is an `mcpServers` (or, for VS Code, `servers`) entry named `instinct` that runs `instinct mcp`, merged into
//! the harness's JSON config without touching any other server or key. Before a file is changed, the old bytes are copied
//! to `<file>.bak-instinct`; a second run changes nothing. `--dry-run` prints the same report and writes nothing.
//! A config that is not plain JSON (comments, trailing commas) is left alone with a message, never rewritten.
//! The config shapes come from docs/connect.md. Sibling access goes through `super::` because the playground compiles
//! main.rs as a submodule.
use super::*;

const USAGE: &str = "usage: instinct connect cursor|vscode|gemini|windsurf [--user] [--dry-run]\n  cursor    project .cursor/mcp.json (--user: ~/.cursor/mcp.json)\n  vscode    project .vscode/mcp.json (\"servers\" key)\n  gemini    `gemini extensions install` when the gemini CLI exists, else ~/.gemini/settings.json\n  windsurf  ~/.codeium/windsurf/mcp_config.json";
const GEMINI_EXT: &str = "https://github.com/koscak-labs/instinct";

/// The server entry. VS Code's file also wants `"type": "stdio"`.
fn entry(vscode: bool) -> Vec<(String, Json)> {
    let mut v = Vec::new();
    if vscode {
        v.push(("type".to_string(), Json::Str("stdio".into())));
    }
    v.push(("command".to_string(), Json::Str("instinct".into())));
    v.push(("args".to_string(), Json::Arr(vec![Json::Str("mcp".into())])));
    v
}

/// Pretty JSON, two spaces, arrays of scalars on one line. Integers print without a fraction.
fn ser(j: &Json, depth: usize, out: &mut String) {
    let pad = |n: usize| "  ".repeat(n);
    match j {
        Json::Null => out.push_str("null"),
        Json::Bool(b) => out.push_str(if *b { "true" } else { "false" }),
        Json::Num(n) if n.fract() == 0.0 && n.abs() < 1e15 => out.push_str(&format!("{}", *n as i64)),
        Json::Num(n) => out.push_str(&format!("{n}")),
        Json::Str(s) => out.push_str(&format!("\"{}\"", escape_json(s))),
        Json::Arr(items) if items.is_empty() => out.push_str("[]"),
        Json::Arr(items) if items.iter().all(|i| !matches!(i, Json::Arr(_) | Json::Obj(_))) => {
            out.push('[');
            for (n, i) in items.iter().enumerate() {
                if n > 0 {
                    out.push_str(", ");
                }
                ser(i, depth, out);
            }
            out.push(']');
        }
        Json::Arr(items) => {
            out.push_str("[\n");
            for (n, i) in items.iter().enumerate() {
                out.push_str(&pad(depth + 1));
                ser(i, depth + 1, out);
                out.push_str(if n + 1 < items.len() { ",\n" } else { "\n" });
            }
            out.push_str(&pad(depth));
            out.push(']');
        }
        Json::Obj(fields) if fields.is_empty() => out.push_str("{}"),
        Json::Obj(fields) => {
            out.push_str("{\n");
            for (n, (k, v)) in fields.iter().enumerate() {
                out.push_str(&format!("{}\"{}\": ", pad(depth + 1), escape_json(k)));
                ser(v, depth + 1, out);
                out.push_str(if n + 1 < fields.len() { ",\n" } else { "\n" });
            }
            out.push_str(&pad(depth));
            out.push('}');
        }
    }
}

/// One-line form of a value, for the "- old / + new" report.
fn compact(j: &Json) -> String {
    match j {
        Json::Arr(items) => format!("[{}]", items.iter().map(compact).collect::<Vec<_>>().join(", ")),
        Json::Obj(fields) => format!(
            "{{{}}}",
            fields.iter().map(|(k, v)| format!("\"{}\": {}", escape_json(k), compact(v))).collect::<Vec<_>>().join(", ")
        ),
        scalar => {
            let mut s = String::new();
            ser(scalar, 0, &mut s);
            s
        }
    }
}

/// Where the old bytes go: `<file>.bak-instinct`, then `-2`, `-3`... so an earlier backup is never overwritten.
fn backup_path(path: &Path) -> PathBuf {
    let base = format!("{}.bak-instinct", path.display());
    let mut p = PathBuf::from(&base);
    let mut n = 2;
    while p.exists() {
        p = PathBuf::from(format!("{base}-{n}"));
        n += 1;
    }
    p
}

/// Merge the `instinct` server into `path` under `key` and say exactly what happened.
fn merge_file(name: &str, path: &Path, key: &str, vscode: bool, dry: bool) -> Result<String, String> {
    let want = entry(vscode);
    let (mut doc, existed, old_bytes) = match fs::read_to_string(path) {
        Ok(t) if t.trim().is_empty() => (Json::Obj(Vec::new()), true, t),
        Ok(t) => match parse_json(&t) {
            Ok(j @ Json::Obj(_)) => (j, true, t),
            Ok(_) => return Err(format!("{}: the top level is not a JSON object; left untouched. Add the entry by hand (docs/connect.md)", path.display())),
            Err(e) => return Err(format!("{}: not plain JSON ({e}); left untouched. Add the entry by hand (docs/connect.md)", path.display())),
        },
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => (Json::Obj(Vec::new()), false, String::new()),
        Err(e) => return Err(format!("{}: {e}", path.display())),
    };
    let Json::Obj(top) = &mut doc else { unreachable!() };
    if !top.iter().any(|(k, _)| k == key) {
        top.push((key.to_string(), Json::Obj(Vec::new())));
    }
    let servers = match top.iter_mut().find(|(k, _)| k == key) {
        Some((_, Json::Obj(s))) => s,
        _ => return Err(format!("{}: \"{key}\" is not an object; left untouched", path.display())),
    };
    let before: Option<String> = servers.iter().find(|(k, _)| k == "instinct").map(|(_, v)| compact(v));
    match servers.iter_mut().find(|(k, _)| k == "instinct") {
        None => servers.push(("instinct".to_string(), Json::Obj(want.clone()))),
        Some((_, Json::Obj(have))) => {
            // Our fields are set in place; anything else the user added (env, timeout) stays.
            for (k, v) in &want {
                match have.iter_mut().find(|(hk, _)| hk == k) {
                    Some((_, hv)) => *hv = v.clone(),
                    None => have.push((k.clone(), v.clone())),
                }
            }
        }
        Some((_, other)) => *other = Json::Obj(want.clone()),
    }
    let after = compact(servers.iter().find(|(k, _)| k == "instinct").map(|(_, v)| v).unwrap());
    if before.as_deref() == Some(after.as_str()) {
        return Ok(format!("{name}: already connected, no change: {}\n  entry {after}\n", path.display()));
    }
    let mut text = String::new();
    ser(&doc, 0, &mut text);
    text.push('\n');
    let mut report = String::new();
    let verb = if dry { "would " } else { "" };
    let bak = (existed && !old_bytes.trim().is_empty()).then(|| backup_path(path));
    match (&before, existed) {
        (_, false) => report.push_str(&format!("{name}: {verb}create {}\n", path.display())),
        (None, true) => report.push_str(&format!("{name}: {verb}add the instinct server to {}\n", path.display())),
        (Some(_), true) => report.push_str(&format!("{name}: {verb}update the instinct server in {}\n", path.display())),
    }
    if let Some(b) = &before {
        report.push_str(&format!("  - {b}\n"));
    }
    report.push_str(&format!("  + {after}\n"));
    if let Some(b) = &bak {
        report.push_str(&format!("  {verb}back up the old file to {}\n", b.display()));
    }
    if dry {
        return Ok(report);
    }
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent).map_err(|e| format!("{}: {e}", parent.display()))?;
    }
    if let Some(b) = &bak {
        fs::write(b, &old_bytes).map_err(|e| format!("{}: {e}", b.display()))?;
    }
    let tmp = PathBuf::from(format!("{}.instinct-tmp", path.display()));
    fs::write(&tmp, text).map_err(|e| format!("{}: {e}", tmp.display()))?;
    fs::rename(&tmp, path).map_err(|e| {
        let _ = fs::remove_file(&tmp);
        format!("{}: {e}", path.display())
    })?;
    Ok(report)
}

/// Run `cmd` with no stdin for at most `secs` seconds. Err(None): it cannot start (not installed). Err(Some(msg)): it failed.
/// Two reader threads send each stream when it closes, so the wait is a channel timeout, not a poll.
fn run_cli(mut cmd: std::process::Command, secs: u64) -> Result<String, Option<String>> {
    use std::io::Read;
    use std::process::Stdio;
    let mut child = match cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn() {
        Ok(c) => c,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Err(None),
        Err(e) => return Err(Some(e.to_string())),
    };
    let (tx, rx) = std::sync::mpsc::channel::<(bool, String)>();
    if let Some(o) = child.stdout.take() {
        let tx = tx.clone();
        std::thread::spawn(move || {
            let mut s = String::new();
            let _ = o.take(1 << 16).read_to_string(&mut s);
            let _ = tx.send((true, s));
        });
    }
    if let Some(e) = child.stderr.take() {
        let tx = tx.clone();
        std::thread::spawn(move || {
            let mut s = String::new();
            let _ = e.take(1 << 16).read_to_string(&mut s);
            let _ = tx.send((false, s));
        });
    }
    drop(tx);
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(secs);
    let (mut out, mut err) = (String::new(), String::new());
    for _ in 0..2 {
        match rx.recv_timeout(deadline.saturating_duration_since(std::time::Instant::now())) {
            Ok((true, s)) => out = s,
            Ok((false, s)) => err = s,
            Err(_) => {
                let _ = child.kill();
                let _ = child.wait();
                return Err(Some(format!("timed out after {secs} s")));
            }
        }
    }
    match child.wait() {
        Ok(s) if s.success() => Ok(out),
        Ok(_) => Err(Some(if err.trim().is_empty() { out.trim().to_string() } else { err.trim().to_string() })),
        Err(e) => Err(Some(e.to_string())),
    }
}

fn gemini(home: &Path, dry: bool) -> Result<String, String> {
    let mut list = std::process::Command::new("gemini");
    list.args(["extensions", "list"]);
    match run_cli(list, 30) {
        Err(None) => merge_file("gemini", &home.join(".gemini").join("settings.json"), "mcpServers", false, dry)
            .map(|r| format!("{r}  (the gemini CLI was not found on PATH, so the settings file was used)\n")),
        Err(Some(e)) => Err(format!("gemini: `gemini extensions list` failed: {e}")),
        Ok(listing) if listing.lines().any(|l| l.contains("instinct")) => Ok("gemini: already connected, no change: the instinct extension is installed\n".into()),
        Ok(_) if dry => Ok(format!("gemini: would run: gemini extensions install {GEMINI_EXT}\n")),
        Ok(_) => {
            let mut install = std::process::Command::new("gemini");
            install.args(["extensions", "install", GEMINI_EXT]);
            match run_cli(install, 180) {
                Ok(_) => Ok(format!("gemini: ran: gemini extensions install {GEMINI_EXT}\n")),
                Err(e) => Err(format!("gemini: `gemini extensions install {GEMINI_EXT}` failed: {}", e.unwrap_or_default())),
            }
        }
    }
}

pub fn run(argv: &[String]) -> Result<(), String> {
    let (mut target, mut user, mut dry) = (None::<&str>, false, false);
    for a in argv {
        match a.as_str() {
            "--user" => user = true,
            "--dry-run" => dry = true,
            s if s.starts_with('-') => return Err(USAGE.into()),
            s if target.is_none() => target = Some(s),
            _ => return Err(USAGE.into()),
        }
    }
    let Some(target) = target else { return Err(USAGE.into()) };
    if user && target != "cursor" {
        return Err(format!(
            "`instinct connect {target}` has no --user form: {}",
            match target {
                "gemini" | "windsurf" => "its config already lives in your home folder",
                "vscode" => "VS Code keeps the user-level MCP list inside its own settings (see docs/connect.md)",
                _ => "unknown harness",
            }
        ));
    }
    let home = || {
        std::env::var_os("HOME")
            .filter(|v| !v.is_empty())
            .or_else(|| std::env::var_os("USERPROFILE").filter(|v| !v.is_empty()))
            .map(PathBuf::from)
            .ok_or_else(|| "cannot find your home folder (set HOME)".to_string())
    };
    let cwd = || std::env::current_dir().map_err(|e| e.to_string());
    let report = match target {
        "cursor" => {
            let base = if user { home()? } else { cwd()? };
            merge_file("cursor", &base.join(".cursor").join("mcp.json"), "mcpServers", false, dry)?
        }
        "vscode" => merge_file("vscode", &cwd()?.join(".vscode").join("mcp.json"), "servers", true, dry)?,
        "gemini" => gemini(&home()?, dry)?,
        "windsurf" => merge_file("windsurf", &home()?.join(".codeium").join("windsurf").join("mcp_config.json"), "mcpServers", false, dry)?,
        _ => return Err(USAGE.into()),
    };
    print!("{report}");
    if dry {
        println!("dry run: nothing was written");
    }
    Ok(())
}