use super::*;
#[derive(Clone, Copy, PartialEq, Debug)]
enum State {
On,
Off,
Unreadable,
}
impl State {
fn word(self) -> &'static str {
match self {
State::On => "present",
State::Off => "absent",
State::Unreadable => "unreadable",
}
}
}
struct Item {
id: &'static str,
label: &'static str,
state: State,
via: &'static str,
}
struct Harness {
id: &'static str,
name: &'static str,
dir: PathBuf,
found: bool,
items: Vec<Item>,
}
struct Activity {
last: Option<u64>,
}
struct Bank {
path: Option<PathBuf>,
exists: bool,
lessons: Option<usize>,
error: bool,
writable: bool,
starter_new: Option<usize>,
starter_held: Option<usize>,
explicit: bool,
}
impl Bank {
fn starter_cmd(&self) -> String {
match (&self.path, self.explicit) {
(Some(p), true) => {
let s = p.display().to_string();
let s = if s.contains(char::is_whitespace) { format!("\"{s}\"") } else { s };
format!("instinct starter --apply --store {s}")
}
_ => "instinct starter --apply".to_string(),
}
}
fn has_no_starter(&self) -> bool {
self.exists && self.starter_held == Some(0) && self.starter_new.is_some_and(|n| n > 0)
}
}
enum Cfg<T> {
Missing,
Bad,
Ok(T),
}
fn read_text(p: &Path) -> Cfg<String> {
match fs::read(p) {
Ok(b) => {
let s = String::from_utf8_lossy(&b).into_owned();
Cfg::Ok(s.strip_prefix('\u{feff}').map(str::to_owned).unwrap_or(s))
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Cfg::Missing,
Err(_) => Cfg::Bad,
}
}
fn read_json(p: &Path) -> Cfg<Json> {
match read_text(p) {
Cfg::Ok(t) => match parse_json(&t) {
Ok(j) => Cfg::Ok(j),
Err(_) => Cfg::Bad,
},
Cfg::Missing => Cfg::Missing,
Cfg::Bad => Cfg::Bad,
}
}
fn runs(cmd: &str, sub: &str) -> bool {
cmd.replace("instinct.exe", "instinct").contains(&format!("instinct {sub}"))
}
fn any_string(j: &Json, f: &dyn Fn(&str) -> bool) -> bool {
match j {
Json::Str(s) => f(s),
Json::Arr(a) => a.iter().any(|x| any_string(x, f)),
Json::Obj(o) => o.iter().any(|(_, v)| any_string(v, f)),
_ => false,
}
}
fn has_hook(doc: &Json, sub: &str) -> bool {
doc.get("hooks").is_some_and(|h| any_string(h, &|s| runs(s, sub)))
}
fn mcp_anywhere(j: &Json) -> bool {
match j {
Json::Obj(o) => o.iter().any(|(k, v)| {
(k == "mcpServers" && v.get("instinct").is_some()) || mcp_anywhere(v)
}),
Json::Arr(a) => a.iter().any(mcp_anywhere),
_ => false,
}
}
fn plugin_enabled(doc: &Json, key: &str) -> bool {
matches!(doc.get("enabledPlugins").and_then(|p| p.get(key)), Some(Json::Bool(true)))
}
fn toml_has_mcp(text: &str) -> bool {
text.lines().any(|l| {
let l = l.trim();
["[mcp_servers.instinct]", "[mcp_servers.instinct.", "[mcp_servers.\"instinct\"]", "[mcp_servers.\"instinct\"."]
.iter()
.any(|p| l.starts_with(p))
})
}
fn toml_plugin_on(text: &str, id: &str) -> bool {
let header = format!("[plugins.\"{id}\"]");
let mut inside = false;
let mut found = false;
for l in text.lines().map(str::trim) {
if l.starts_with('[') {
inside = l == header;
found |= inside;
} else if inside && l.replace(' ', "") == "enabled=false" {
return false;
}
}
found
}
fn toml_hook_trusted(text: &str, parts: &[&str]) -> bool {
text.lines().map(str::trim).any(|l| l.starts_with("[hooks.state.") && parts.iter().all(|p| l.contains(p)))
}
fn item(id: &'static str, label: &'static str, state: State, via: &'static str) -> Item {
Item { id, label, state, via }
}
fn from_json(
cfg: &Cfg<Json>,
id: &'static str,
label: &'static str,
via: &'static str,
f: &dyn Fn(&Json) -> bool,
) -> Item {
match cfg {
Cfg::Ok(j) if f(j) => item(id, label, State::On, via),
Cfg::Ok(_) | Cfg::Missing => item(id, label, State::Off, ""),
Cfg::Bad => item(id, label, State::Unreadable, ""),
}
}
fn first_on(id: &'static str, label: &'static str, tries: Vec<Item>) -> Item {
if let Some(i) = tries.iter().find(|i| i.state == State::On) {
return item(id, label, State::On, i.via);
}
if tries.iter().any(|i| i.state == State::Unreadable) {
return item(id, label, State::Unreadable, "");
}
item(id, label, State::Off, "")
}
fn claude_code(home: &Path, cwd: Option<&Path>) -> Harness {
let dir = home.join(".claude");
let found = dir.is_dir();
let mut items = Vec::new();
if found {
let settings = read_json(&dir.join("settings.json"));
let state_file = read_json(&home.join(".claude.json"));
let project: Vec<Json> = cwd
.map(|c| {
["settings.local.json", "settings.json"]
.iter()
.filter_map(|f| match read_json(&c.join(".claude").join(f)) {
Cfg::Ok(j) => Some(j),
_ => None,
})
.collect()
})
.unwrap_or_default();
let proj_hook = |sub: &str| project.iter().any(|j| has_hook(j, sub));
let hook = |sub: &'static str| {
let mut i = from_json(&settings, "hook", "hook", "hook", &|j| has_hook(j, sub));
if i.state == State::Off && proj_hook(sub) {
i = item("hook", "hook", State::On, "project hook");
}
i
};
let plugin = |key: &'static str| from_json(&settings, "plugin", "plugin", "plugin", &|j| plugin_enabled(j, key));
items.push(first_on(
"tripwires",
"tripwires (instinct guard)",
vec![plugin("instinct@koscak-labs"), hook("guard")],
));
items.push(first_on(
"autorecall",
"automatic lookup (instinct prompt)",
vec![plugin("instinct-autorecall@koscak-labs"), hook("prompt")],
));
let direct = from_json(&state_file, "mcp", "mcp", "mcp server", &mcp_anywhere);
let via_plugin = plugin("instinct@koscak-labs");
let via_plugin = if via_plugin.state == State::On { item("mcp", "mcp", State::On, "plugin") } else { via_plugin };
items.push(first_on("mcp", "MCP server", vec![direct, via_plugin]));
}
Harness { id: "claude_code", name: "Claude Code", dir, found, items }
}
fn codex(home: &Path) -> Harness {
let dir = home.join(".codex");
let found = dir.is_dir();
let mut items = Vec::new();
if found {
let hooks = read_json(&dir.join("hooks.json"));
let cfg = read_text(&dir.join("config.toml"));
let plugin = |id: &'static str| match &cfg {
Cfg::Ok(t) if toml_plugin_on(t, id) => item("plugin", "plugin", State::On, "plugin"),
_ => item("plugin", "plugin", State::Off, ""),
};
let tripwires = first_on(
"tripwires",
"tripwires (instinct guard)",
vec![from_json(&hooks, "tripwires", "tripwires", "hook", &|j| has_hook(j, "guard")), plugin("instinct@koscak-labs")],
);
let autorecall = first_on(
"autorecall",
"automatic lookup (instinct prompt)",
vec![from_json(&hooks, "autorecall", "autorecall", "hook", &|j| has_hook(j, "prompt")), plugin("instinct-autorecall@koscak-labs")],
);
let saved = |ev: &str, plugin_id: &str| match &cfg {
Cfg::Ok(t) => toml_hook_trusted(t, &["hooks.json", ev]) || toml_hook_trusted(t, &[plugin_id, ev]),
_ => false,
};
let wants = [(&tripwires, "pre_tool_use", "instinct@koscak-labs"), (&autorecall, "user_prompt_submit", "instinct-autorecall@koscak-labs")];
let installed: Vec<_> = wants.iter().filter(|(i, _, _)| i.state == State::On).collect();
let trust = if installed.is_empty() {
None
} else if installed.iter().all(|(_, ev, id)| saved(ev, id)) {
Some(item("trust", "hooks trusted by Codex", State::On, "config.toml"))
} else {
Some(item("trust", "hooks trusted by Codex", State::Off, ""))
};
items.push(tripwires);
items.push(autorecall);
items.extend(trust);
let mcp = match read_text(&dir.join("config.toml")) {
Cfg::Ok(t) if toml_has_mcp(&t) => item("mcp", "MCP server", State::On, "config.toml"),
Cfg::Ok(_) | Cfg::Missing => item("mcp", "MCP server", State::Off, ""),
Cfg::Bad => item("mcp", "MCP server", State::Unreadable, ""),
};
items.push(mcp);
let skill = if home.join(".agents").join("skills").join("instinct").is_dir() {
item("skill", "skill folder", State::On, "~/.agents/skills")
} else {
item("skill", "skill folder", State::Off, "")
};
items.push(skill);
}
Harness { id: "codex", name: "Codex CLI", dir, found, items }
}
fn gemini(home: &Path) -> Harness {
let dir = home.join(".gemini");
let found = dir.is_dir();
let mut items = Vec::new();
if found {
let s = read_json(&dir.join("settings.json"));
items.push(from_json(&s, "autorecall", "automatic lookup (instinct prompt)", "hook", &|j| has_hook(j, "prompt")));
items.push(from_json(&s, "mcp", "MCP server", "settings.json", &|j| {
j.get("mcpServers").is_some_and(|m| m.get("instinct").is_some())
}));
}
Harness { id: "gemini_cli", name: "Gemini CLI", dir, found, items }
}
fn cursor(home: &Path) -> Harness {
let dir = home.join(".cursor");
let found = dir.is_dir();
let mut items = Vec::new();
if found {
let s = read_json(&dir.join("mcp.json"));
items.push(from_json(&s, "mcp", "MCP server", "mcp.json", &|j| {
j.get("mcpServers").is_some_and(|m| m.get("instinct").is_some())
}));
}
Harness { id: "cursor", name: "Cursor", dir, found, items }
}
fn windsurf(home: &Path) -> Harness {
let dir = home.join(".codeium").join("windsurf");
let found = dir.is_dir();
let mut items = Vec::new();
if found {
let has = |j: &Json| j.get("mcpServers").is_some_and(|m| m.get("instinct").is_some());
let a = from_json(&read_json(&dir.join("mcp_config.json")), "mcp", "MCP server", "mcp_config.json", &has);
let b = from_json(&read_json(&home.join(".config").join("devin").join("mcp_config.json")), "mcp", "MCP server", "mcp_config.json", &has);
items.push(first_on("mcp", "MCP server", vec![a, b]));
}
Harness { id: "windsurf", name: "Windsurf", dir, found, items }
}
fn warp(home: &Path) -> Harness {
let dir = home.join(".warp");
let found = dir.is_dir();
let mut items = Vec::new();
if found {
let s = read_json(&dir.join(".mcp.json"));
items.push(from_json(&s, "mcp", "MCP server", ".mcp.json", &|j| {
j.get("mcpServers").is_some_and(|m| m.get("instinct").is_some())
}));
}
Harness { id: "warp", name: "Warp", dir, found, items }
}
fn folder_writable(bank: &Path) -> bool {
let mut d = bank.parent().map(Path::to_path_buf).unwrap_or_default();
if d.as_os_str().is_empty() {
d = PathBuf::from(".");
}
loop {
if let Ok(m) = fs::metadata(&d) {
return m.is_dir() && !m.permissions().readonly();
}
match d.parent() {
Some(p) if !p.as_os_str().is_empty() => d = p.to_path_buf(),
_ => return false,
}
}
}
fn inspect_bank(path: Option<&Path>, explicit: bool) -> Bank {
let Some(p) = path else {
return Bank { path: None, exists: false, lessons: None, error: false, writable: false, starter_new: None, starter_held: None, explicit };
};
let exists = p.exists();
let mut starter_new = None;
let mut starter_held = None;
let (lessons, error) = if exists {
match load_plain(&p.to_path_buf()) {
Ok(v) => {
let ids: HashSet<String> = v.iter().map(|d| d.id.clone()).collect();
starter_new = super::starter::new_in(&ids).ok();
starter_held = starter_new.and_then(|n| super::starter::total().map(|t| t.saturating_sub(n)));
(Some(v.len()), false)
}
Err(_) => (None, true),
}
} else {
(Some(0), false)
};
Bank { path: Some(p.to_path_buf()), exists, lessons, error, writable: folder_writable(p), starter_new, starter_held, explicit }
}
fn activity(store: &Path) -> (Activity, Activity) {
let (mut prompt, mut guard) = (None::<u64>, None::<u64>);
let bump = |slot: &mut Option<u64>, ts: u64| {
if ts > 0 && slot.map_or(true, |t| ts > t) {
*slot = Some(ts);
}
};
if let Ok(b) = fs::read(meter::meter_path(store)) {
for line in String::from_utf8_lossy(&b).lines() {
let mut f = line.split_whitespace();
let (Some(ts), Some(kind)) = (f.next().and_then(|t| t.parse::<u64>().ok()), f.next()) else { continue };
match kind {
"prompt" => bump(&mut prompt, ts),
"guard" => bump(&mut guard, ts),
_ => {}
}
}
}
for r in session::records(store) {
match r.source {
session::Source::Prompt => bump(&mut prompt, r.ts),
session::Source::Guard => bump(&mut guard, r.ts),
session::Source::Unknown => {}
}
}
(Activity { last: prompt }, Activity { last: guard })
}
fn ago(last: Option<u64>, now: u64) -> String {
let Some(t) = last else { return "never".into() };
let s = now.saturating_sub(t);
let (n, unit) = match s {
0..=59 => return "just now".into(),
60..=3599 => (s / 60, "min"),
3600..=86_399 => (s / 3600, "h"),
_ => (s / 86_400, if s / 86_400 == 1 { "day" } else { "days" }),
};
format!("{n} {unit} ago")
}
struct PathBin {
found: Option<PathBuf>,
same: bool,
others: Vec<(PathBuf, String)>,
online: Option<Option<String>>,
}
fn parse_version(s: &str) -> Option<(u64, u64, u64)> {
let tok = s.split_whitespace().find(|t| t.trim_start_matches('v').starts_with(|c: char| c.is_ascii_digit()))?;
let core = tok.trim_start_matches('v').split(['-', '+']).next()?;
let mut p = core.split('.');
let v = (p.next()?.parse().ok()?, p.next()?.parse().ok()?, p.next()?.parse().ok()?);
if p.next().is_some() {
return None;
}
Some(v)
}
fn capture(mut cmd: std::process::Command, secs: u64) -> Option<String> {
use std::io::Read;
use std::process::Stdio;
let mut child = cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::null()).spawn().ok()?;
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(secs);
let status = loop {
match child.try_wait() {
Ok(Some(s)) => break s,
Ok(None) if std::time::Instant::now() < deadline => std::thread::sleep(std::time::Duration::from_millis(20)),
_ => {
let _ = child.kill();
let _ = child.wait();
return None;
}
}
};
let mut out = String::new();
child.stdout.take()?.take(1 << 16).read_to_string(&mut out).ok()?;
status.success().then_some(out)
}
fn latest_release() -> Option<String> {
let mut c = std::process::Command::new("curl");
c.args(["-fsS", "--max-time", "5", "-H", "Accept: application/vnd.github+json", "https://api.github.com/repos/koscak-labs/instinct/releases/latest"]);
let body = capture(c, 8)?;
let rest = &body[body.find("\"tag_name\"")? + 10..];
let rest = &rest[rest.find('"')? + 1..];
let tag = &rest[..rest.find('"')?];
parse_version(tag).map(|(a, b, c)| format!("{a}.{b}.{c}"))
}
fn other_binaries(me: Option<&Path>) -> Vec<(PathBuf, String)> {
let name = if cfg!(windows) { "instinct.exe" } else { "instinct" };
let mut seen: Vec<PathBuf> = Vec::new();
let mut out = Vec::new();
for dir in std::env::var_os("PATH").map(|p| std::env::split_paths(&p).collect::<Vec<_>>()).unwrap_or_default() {
let c = dir.join(name);
if !c.is_file() {
continue;
}
let real = plain(fs::canonicalize(&c).unwrap_or(c));
if seen.contains(&real) || Some(real.as_path()) == me {
continue;
}
seen.push(real.clone());
let mut cmd = std::process::Command::new(&real);
cmd.arg("--version");
if let Some(v) = capture(cmd, 2).and_then(|o| parse_version(&o)) {
out.push((real, format!("{}.{}.{}", v.0, v.1, v.2)));
}
}
out
}
fn version_notes(pb: &PathBin) -> Vec<String> {
let mine = parse_version(env!("CARGO_PKG_VERSION"));
let mut v = Vec::new();
for (p, ver) in &pb.others {
match parse_version(ver).cmp(&mine) {
std::cmp::Ordering::Less => v.push(format!("another instinct on PATH is older ({ver} at {}): remove it or put the new one first", p.display())),
std::cmp::Ordering::Greater => v.push(format!("another instinct on PATH is newer ({ver} at {}): this {} is out of date; update it or put the new one first", p.display(), env!("CARGO_PKG_VERSION"))),
std::cmp::Ordering::Equal => {}
}
}
if let Some(Some(latest)) = &pb.online {
if parse_version(latest) > mine {
v.push(format!("the latest release is {latest} and this is {}: see https://github.com/koscak-labs/instinct/releases/latest", env!("CARGO_PKG_VERSION")));
}
}
v
}
fn plain(p: PathBuf) -> PathBuf {
let s = p.to_string_lossy();
if let Some(rest) = s.strip_prefix(r"\\?\UNC\") {
return PathBuf::from(format!(r"\\{rest}"));
}
if let Some(rest) = s.strip_prefix(r"\\?\") {
return PathBuf::from(rest);
}
p
}
fn first_on_path(exe: Option<&Path>) -> PathBin {
let name = if cfg!(windows) { "instinct.exe" } else { "instinct" };
let found = std::env::var_os("PATH").and_then(|p| {
std::env::split_paths(&p).map(|d| d.join(name)).find(|c| c.is_file()).map(|c| plain(fs::canonicalize(&c).unwrap_or(c)))
});
let me = exe.map(|e| plain(fs::canonicalize(e).unwrap_or_else(|_| e.to_path_buf())));
let same = found.is_some() && found == me;
PathBin { found, same, others: other_binaries(me.as_deref()), online: None }
}
const CONNECT: &str = "https://github.com/koscak-labs/instinct/blob/main/docs/connect.md";
fn next_steps(
bank: &Bank,
pb: &PathBin,
exe: Option<&Path>,
hs: &[Harness],
prompt: &Activity,
guard: &Activity,
) -> Vec<String> {
let mut v = version_notes(pb);
match (&pb.found, pb.same) {
(None, _) => {
let dir = exe.and_then(Path::parent).map(|d| d.display().to_string()).unwrap_or_else(|| "the folder holding instinct".into());
v.push(format!("add {dir} to your PATH, so hooks and MCP servers can start `instinct`"));
}
(Some(p), false) => v.push(format!("check the version your hooks run: {} --version, and update it if it is older", p.display())),
_ => {}
}
let any = hs.iter().any(|h| h.found);
if !any {
v.push("npx skills add koscak-labs/instinct --skill instinct".into());
}
for h in hs.iter().filter(|h| h.found) {
for i in h.items.iter().filter(|i| i.state != State::On) {
let unread = i.state == State::Unreadable;
let step = match (h.id, i.id) {
(_, _) if unread => format!("{}: fix or remove the unreadable config file in {}, then run `instinct doctor` again", h.name, h.dir.display()),
("claude_code", "tripwires") => "claude plugin marketplace add koscak-labs/instinct && claude plugin install instinct@koscak-labs".into(),
("claude_code", "autorecall") => "claude plugin install instinct-autorecall@koscak-labs".into(),
("claude_code", "mcp") => "claude mcp add --transport stdio --scope local instinct -- instinct mcp".into(),
("codex", "mcp") => "codex mcp add instinct -- instinct mcp".into(),
("codex", "tripwires") => format!("Codex tripwires: codex plugin marketplace add koscak-labs/instinct && codex plugin add instinct@koscak-labs, then instinct codex-trust ({CONNECT}#tripwires)"),
("codex", "trust") => "Codex skips hooks it has not trusted, silently: run `instinct codex-trust` once (or approve them with /hooks inside Codex)".into(),
("codex", "autorecall") => format!("Codex automatic lookup: codex plugin add instinct-autorecall@koscak-labs, then instinct codex-trust ({CONNECT}#codex-cli)"),
("codex", "skill") => "npx skills add koscak-labs/instinct --skill instinct".into(),
("gemini_cli", "mcp") => format!("Gemini CLI MCP: add the mcpServers snippet from {CONNECT}#agents-that-use-mcpservers to ~/.gemini/settings.json"),
("gemini_cli", "autorecall") => format!("Gemini CLI automatic lookup: add the BeforeAgent hook described in {CONNECT}#agents-that-use-mcpservers to ~/.gemini/settings.json"),
("cursor", "mcp") => format!("Cursor MCP: add the mcpServers snippet from {CONNECT}#agents-that-use-mcpservers to ~/.cursor/mcp.json"),
("windsurf", "mcp") => format!("Windsurf MCP: add the mcpServers snippet from {CONNECT}#windsurf-warp-and-crush to ~/.codeium/windsurf/mcp_config.json"),
("warp", "mcp") => format!("Warp MCP: add the mcpServers snippet from {CONNECT}#windsurf-warp-and-crush to ~/.warp/.mcp.json"),
_ => continue,
};
v.push(step);
}
}
if bank.has_no_starter() {
v.push(format!(
"this bank holds none of the starter tripwires, so `instinct guard` stays silent on rm -rf, git push --force and the like: {}",
bank.starter_cmd()
));
}
if bank.path.is_none() {
v.push("set INSTINCT_STORE to a bank file path, or set HOME".into());
} else if bank.error {
v.push("the bank could not be read; run `instinct stats` to see the error".into());
} else if !bank.exists && !hs.iter().any(|h| h.items.iter().any(|i| i.id == "tripwires" && i.state == State::On)) {
v.push(format!("or add the starter tripwires now without hooks: {}", bank.starter_cmd()));
}
let wired = hs.iter().any(|h| h.items.iter().any(|i| i.state == State::On && matches!(i.id, "tripwires" | "autorecall")));
if wired && prompt.last.is_none() && guard.last.is_none() {
v.push("use your agent once, then run `instinct doctor` again: a hook that ran shows up under Activity".into());
}
v
}
fn jstr(s: &str) -> String {
format!("\"{}\"", escape_json(s))
}
fn jopt_num(n: Option<u64>) -> String {
n.map_or("null".into(), |n| n.to_string())
}
fn render_json(
exe: Option<&Path>,
pb: &PathBin,
bank: &Bank,
team: &Option<(PathBuf, Option<usize>)>,
prompt: &Activity,
guard: &Activity,
hs: &[Harness],
steps: &[String],
now: u64,
) -> String {
let act = |a: &Activity| {
format!(
"{{\"last_unix\":{},\"seconds_ago\":{}}}",
jopt_num(a.last),
jopt_num(a.last.map(|t| now.saturating_sub(t)))
)
};
let exe_s = exe.map_or("null".into(), |p| jstr(&p.display().to_string()));
let bank_path = bank.path.as_ref().map_or("null".into(), |p| jstr(&p.display().to_string()));
let lessons = bank.lessons.map_or("null".into(), |n| n.to_string());
let hjson: Vec<String> = hs
.iter()
.map(|h| {
let items: Vec<String> = h
.items
.iter()
.map(|i| {
format!(
"{{\"id\":{},\"state\":{},\"via\":{}}}",
jstr(i.id),
jstr(i.state.word()),
if i.via.is_empty() { "null".into() } else { jstr(i.via) }
)
})
.collect();
format!(
"{{\"id\":{},\"name\":{},\"config_dir\":{},\"found\":{},\"items\":[{}]}}",
jstr(h.id),
jstr(h.name),
jstr(&h.dir.display().to_string()),
h.found,
items.join(",")
)
})
.collect();
let steps_j: Vec<String> = steps.iter().map(|s| jstr(s)).collect();
let team_j = team.as_ref().map_or(String::new(), |(p, n)| {
format!(",\"team\":{{\"path\":{},\"lessons\":{}}}", jstr(&p.display().to_string()), n.map_or("null".into(), |n| n.to_string()))
});
let notes = version_notes(pb);
let version_j = if notes.is_empty() && pb.online.is_none() {
String::new()
} else {
let others: Vec<String> = pb.others.iter().map(|(p, v)| format!("{{\"path\":{},\"version\":{}}}", jstr(&p.display().to_string()), jstr(v))).collect();
let online = match &pb.online {
None => String::new(),
Some(l) => format!(",\"latest_release\":{}", l.as_deref().map_or("null".into(), jstr)),
};
format!(",\"version_check\":{{\"other_binaries\":[{}]{}}}", others.join(","), online)
};
format!(
"{{\"schema\":1,\"binary\":{{\"version\":{},\"path\":{},\"on_path\":{},\"path_binary\":{},\"path_binary_is_this\":{}}}{},\"bank\":{{\"path\":{},\"exists\":{},\"lessons\":{},\"readable\":{},\"folder_writable\":{}{}}}{},\"activity\":{{\"prompt\":{},\"guard\":{}}},\"harnesses\":[{}],\"next_steps\":[{}]}}",
jstr(env!("CARGO_PKG_VERSION")),
exe_s,
pb.found.is_some(),
pb.found.as_ref().map_or("null".into(), |p| jstr(&p.display().to_string())),
if pb.found.is_some() { pb.same.to_string() } else { "null".into() },
version_j,
bank_path,
bank.exists,
lessons,
!bank.error,
bank.writable,
bank.starter_new.filter(|&n| n > 0).map_or(String::new(), |n| format!(
",\"starter_new\":{n},\"starter_none\":{},\"starter_command\":{}",
bank.has_no_starter(),
jstr(&bank.starter_cmd())
)),
team_j,
act(prompt),
act(guard),
hjson.join(","),
steps_j.join(",")
)
}
fn render_text(
exe: Option<&Path>,
pb: &PathBin,
bank: &Bank,
team: &Option<(PathBuf, Option<usize>)>,
prompt: &Activity,
guard: &Activity,
hs: &[Harness],
steps: &[String],
now: u64,
) -> String {
let mut o = String::new();
o.push_str(if pb.online.is_some() {
"instinct doctor (read-only: nothing is written; --online sent one request to api.github.com)\n\n"
} else {
"instinct doctor (read-only: nothing is written, nothing leaves this machine)\n\n"
});
let exe_s = exe.map_or("unknown path".to_string(), |p| p.display().to_string());
let tail = match (&pb.found, pb.same) {
(None, _) => "not found on PATH".to_string(),
(Some(_), true) => "found on PATH".to_string(),
(Some(p), false) => format!("your hooks run {} instead (first on PATH)", p.display()),
};
o.push_str(&format!("binary instinct {} at {exe_s}; {tail}\n", env!("CARGO_PKG_VERSION")));
for note in version_notes(pb) {
o.push_str(&format!("version {note}\n"));
}
match &pb.online {
Some(None) => o.push_str("version online check skipped: no curl, or no answer from GitHub\n"),
Some(Some(v)) if parse_version(v) <= parse_version(env!("CARGO_PKG_VERSION")) => o.push_str(&format!("version latest release is {v}: up to date\n")),
_ => {}
}
match &bank.path {
None => o.push_str("bank no location found (set INSTINCT_STORE or HOME)\n"),
Some(p) => {
let state = if bank.error {
"exists but could not be read".to_string()
} else if !bank.exists {
"does not exist yet".to_string()
} else {
let n = bank.lessons.unwrap_or(0);
format!("{n} lesson{}", if n == 1 { "" } else { "s" })
};
o.push_str(&format!(
"bank {}: {state}; folder {}\n",
p.display(),
if bank.writable { "writable" } else { "not writable" }
));
if bank.has_no_starter() {
o.push_str(&format!(
"starter none of the starter tripwires are in this bank, so the guard is silent on rm -rf $VAR, git push --force and the like: {}\n",
bank.starter_cmd()
));
} else if let Some(n) = bank.starter_new.filter(|&n| n > 0) {
o.push_str(&format!("starter {n} new starter tripwires: {}\n", bank.starter_cmd()));
}
}
}
if let Some((p, n)) = team {
let state = match n {
Some(n) => format!("{n} lesson{}", if *n == 1 { "" } else { "s" }),
None => "exists but could not be read".to_string(),
};
o.push_str(&format!("team {}: {state}; read after your bank, shared through git\n", p.display()));
}
let line = |name: &str, a: &Activity| match a.last {
Some(_) => format!("{name:<10}last ran {}\n", ago(a.last, now)),
None => format!("{name:<10}never ran (no record in the .meter or .sessions file next to the bank)\n"),
};
o.push_str(&line("prompt", prompt));
o.push_str(&line("guard", guard));
o.push_str(&if super::fix::enabled() {
"fixes on: guard rewrites rm -rf $VAR, git push --force and poll loops before they run (INSTINCT_FIX=0 turns it off; instinct fix --dry-run CMD)\n".to_string()
} else {
"fixes off (INSTINCT_FIX=0): guard only warns\n".to_string()
});
if let Some(p) = &bank.path {
o.push_str(&speed::doctor_line(p));
}
for h in hs.iter().filter(|h| h.found) {
o.push_str(&format!("\n{} ({})\n", h.name, h.dir.display()));
for i in &h.items {
let s = match i.state {
State::On if i.via.is_empty() => "on".to_string(),
State::On => format!("on ({})", i.via),
State::Off => "off".to_string(),
State::Unreadable => "unreadable (could not parse the config file)".to_string(),
};
o.push_str(&format!(" {:<36}{s}\n", i.label));
}
}
let missing: Vec<&str> = hs.iter().filter(|h| !h.found).map(|h| h.name).collect();
if !missing.is_empty() {
o.push_str(&format!("\nnot found on this machine: {}\n", missing.join(", ")));
}
if !steps.is_empty() {
o.push_str("\nnext steps\n");
for (n, s) in steps.iter().enumerate() {
o.push_str(&format!(" {}. {s}\n", n + 1));
}
}
o
}
pub fn run(argv: &[String]) -> Result<(), String> {
if argv.iter().any(|a| a == "--waits") {
return super::waits::run(argv);
}
let mut json = false;
let mut online = false;
let mut store: Option<PathBuf> = None;
let mut i = 0;
while i < argv.len() {
match argv[i].as_str() {
"--json" => json = true,
"--online" => online = true,
"--store" => {
i += 1;
store = Some(PathBuf::from(argv.get(i).ok_or("usage: instinct doctor [--json] [--online] [--store PATH]")?));
}
_ => return Err("usage: instinct doctor [--json] [--online] [--store PATH]".into()),
}
i += 1;
}
let now = now_secs();
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);
let exe = std::env::current_exe().ok();
let mut pb = first_on_path(exe.as_deref());
if online {
pb.online = Some(latest_release());
}
let explicit_flag = store.is_some();
let store_path = match store {
Some(p) => Some(p),
None => default_store().ok(),
};
let explicit = explicit_flag || std::env::var_os("INSTINCT_STORE").is_some_and(|v| !v.is_empty());
let bank = inspect_bank(store_path.as_deref(), explicit);
let (prompt, guard) = match &store_path {
Some(p) => activity(p),
None => (Activity { last: None }, Activity { last: None }),
};
let cwd = std::env::current_dir().ok();
let hs = match &home {
Some(h) => vec![claude_code(h, cwd.as_deref()), codex(h), gemini(h), cursor(h), windsurf(h), warp(h)],
None => Vec::new(),
};
let team = store_path.as_deref().and_then(super::team::find).map(|t| {
let n = super::team::load(&t).ok().map(|v| v.len());
(t, n)
});
let steps = next_steps(&bank, &pb, exe.as_deref(), &hs, &prompt, &guard);
let out = if json {
render_json(exe.as_deref(), &pb, &bank, &team, &prompt, &guard, &hs, &steps, now)
} else {
render_text(exe.as_deref(), &pb, &bank, &team, &prompt, &guard, &hs, &steps, now)
};
if json {
println!("{out}");
} else {
print!("{out}");
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ago_reads_plainly() {
assert_eq!(ago(None, 100), "never");
assert_eq!(ago(Some(100), 130), "just now");
assert_eq!(ago(Some(100), 100 + 180), "3 min ago");
assert_eq!(ago(Some(0 + 1), 1 + 7200), "2 h ago");
assert_eq!(ago(Some(1), 1 + 86_400), "1 day ago");
assert_eq!(ago(Some(500), 100), "just now");
}
#[test]
fn hook_commands_are_found_by_substring_and_path() {
assert!(runs("instinct guard", "guard"));
assert!(runs("/home/u/.cargo/bin/instinct guard --format json", "guard"));
assert!(runs("C:\\x\\instinct.exe prompt", "prompt"));
assert!(!runs("instinct recall", "guard"));
}
#[test]
fn toml_scan_matches_the_table_header_only() {
assert!(toml_has_mcp("[mcp_servers.instinct]\ncommand = \"instinct\"\n"));
assert!(toml_has_mcp(" [mcp_servers.instinct.env]\n"));
assert!(!toml_has_mcp("[mcp_servers.other]\n# [mcp_servers.instinct]\n"));
}
}