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 doctor --leftovers [--fix] [--min-age MIN] [--quiet]` (default 15 min): what agents leave behind.
//!   (a) stale wait loops (`doctor --waits`);
//!   (b) orphaned agent leftovers: the caller's own processes, reparented to init or the user's systemd, with no
//!       controlling terminal, outside any systemd `.service` cgroup (services are never touched), whose command
//!       line has a known leftover shape: a headless browser, `tail -f /dev/null`, `sleep`, a poll loop, a cargo
//!       test binary under `target/*/deps`, or a node/bash script run from /tmp or ~/.cache;
//!   (c) git worktrees of the current repo whose branch is merged into origin/main, that are clean, older than
//!       MIN, and that no process has as its working directory (removed with `git worktree remove`, never forced).
//! Each item prints why, the class of command that made it, and the tripwire or habit that would have prevented
//! it: the report is a learning signal first. It is report-only unless asked: `--fix`, or `INSTINCT_CLEANUP=fix`
//! (which the SessionEnd hook honours). `--quiet` prints nothing unless something was found, and to stderr.
//! `INSTINCT_CLEANUP=0` turns the whole thing off. Linux /proc only; elsewhere it says so.
use super::*;

pub fn enabled() -> bool {
    !matches!(std::env::var("INSTINCT_CLEANUP").as_deref(), Ok("0") | Ok("off") | Ok("false") | Ok("no"))
}

/// `INSTINCT_CLEANUP=fix`: SessionEnd stops what it finds instead of only reporting it.
pub fn fix_by_default() -> bool {
    matches!(std::env::var("INSTINCT_CLEANUP").as_deref(), Ok("fix"))
}

pub fn doctor_line() -> String {
    if fix_by_default() {
        "cleanup   fixing (INSTINCT_CLEANUP=fix): SessionEnd stops leftover agent processes\n".into()
    } else if enabled() {
        "cleanup   report-only (SessionEnd lists leftovers and how to avoid them); INSTINCT_CLEANUP=fix to also stop them, =0 to turn off\n".into()
    } else {
        "cleanup   off (INSTINCT_CLEANUP=0)\n".into()
    }
}

/// The leftover shape of a command line, if it has one. `home` is the user's home folder.
pub fn leftover_shape(args: &[String], home: &str) -> Option<&'static str> {
    let exe = args.first()?;
    let name = exe.rsplit('/').next().unwrap_or("");
    let has = |p: &str| args.iter().any(|a| a == p || a.starts_with(&format!("{p}=")));
    let browser = ["chrome", "chromium", "brave", "google-chrome", "headless_shell"].iter().any(|b| name.contains(b));
    if browser && (args.iter().any(|a| a.starts_with("--remote-debugging-port")) || has("--headless")) {
        return Some("headless browser");
    }
    if name == "tail" && args.iter().any(|a| a == "/dev/null") && args.iter().any(|a| a == "-f" || a.starts_with("--follow")) {
        return Some("`tail -f /dev/null`");
    }
    if name == "sleep" {
        return Some("`sleep`");
    }
    if exe.contains("/target/") && exe.contains("/deps/") {
        return Some("cargo test binary");
    }
    if matches!(name, "node" | "bash" | "sh" | "zsh") {
        if let Some(script) = args.iter().skip(1).find(|a| !a.starts_with('-')) {
            let cache = format!("{home}/.cache/");
            if script.starts_with("/tmp/") || (!home.is_empty() && script.starts_with(&cache)) {
                return Some("script run from /tmp or ~/.cache");
            }
        }
        if let Some(ci) = args.iter().position(|a| a == "-c") {
            if let Some(s) = args.get(ci + 1) {
                if s.contains("sleep ") && (s.contains("until ") || s.contains("while ")) {
                    return Some("poll loop");
                }
            }
        }
    }
    None
}

/// True when the process runs inside a systemd `.service` unit. The user manager itself (`user@1000.service`) holds the
/// whole login session, so it does not count: a terminal or agent scope under it is not a service.
#[cfg(test)]
pub fn in_service(cgroup: &str) -> bool {
    cgroup.lines().any(|l| l.rsplit(':').next().unwrap_or("").split('/').any(|c| c.ends_with(".service") && !c.starts_with("user@")))
}

/// The `.service` units named in a cgroup file (the user manager itself excluded).
fn service_units(cgroup: &str) -> Vec<&str> {
    cgroup.lines().flat_map(|l| l.rsplit(':').next().unwrap_or("").split('/')).filter(|c| c.ends_with(".service") && !c.starts_with("user@")).collect()
}

/// True when the process is in a service the caller is NOT part of. When the caller itself runs inside a service (a CI
/// runner's job, a systemd-run unit), orphans left in that same unit are the caller's own leftovers, not another service's.
pub fn in_foreign_service(cgroup: &str, own_cgroup: &str) -> bool {
    let own = service_units(own_cgroup);
    service_units(cgroup).iter().any(|u| !own.contains(u))
}

#[cfg(target_os = "linux")]
fn git(dir: &Path, args: &[&str]) -> Option<(bool, String)> {
    let o = std::process::Command::new("git").arg("-C").arg(dir).args(args).stdin(std::process::Stdio::null()).output().ok()?;
    Some((o.status.success(), String::from_utf8_lossy(&o.stdout).into_owned()))
}

/// (path, branch) of the linked worktrees of the repo at `cwd` that are merged, clean and idle for `min_age` minutes.
#[cfg(target_os = "linux")]
fn merged_worktrees(cwd: &Path, procs: &[waits::linux::Proc], min_age: u64) -> Vec<(PathBuf, String)> {
    let mut out = Vec::new();
    let Some((true, list)) = git(cwd, &["worktree", "list", "--porcelain"]) else { return out };
    let mut first = true;
    let (mut path, mut branch): (Option<PathBuf>, Option<String>) = (None, None);
    let mut entries = Vec::new();
    for l in list.lines().chain(std::iter::once("")) {
        if l.is_empty() {
            if let Some(p) = path.take() {
                entries.push((p, branch.take(), std::mem::take(&mut first)));
            }
            branch = None;
            continue;
        }
        if let Some(p) = l.strip_prefix("worktree ") {
            path = Some(PathBuf::from(p));
        } else if let Some(b) = l.strip_prefix("branch refs/heads/") {
            branch = Some(b.to_string());
        }
    }
    // The first entry is the main worktree: never removed.
    for (i, (p, b, _)) in entries.iter().enumerate() {
        let Some(b) = b else { continue };
        if i == 0 || *p == cwd || cwd.starts_with(p) {
            continue;
        }
        let merged = git(p, &["merge-base", "--is-ancestor", b, "origin/main"]).is_some_and(|(ok, _)| ok);
        let clean = git(p, &["status", "--porcelain"]).is_some_and(|(ok, s)| ok && s.trim().is_empty());
        let old = fs::metadata(p.join(".git")).and_then(|m| m.modified()).ok().and_then(|m| SystemTime::now().duration_since(m).ok()).is_some_and(|d| d.as_secs() / 60 >= min_age);
        let busy = procs.iter().any(|q| Path::new(&q.cwd).starts_with(p));
        if merged && clean && old && !busy {
            out.push((p.clone(), b.clone()));
        }
    }
    out
}

pub fn run(argv: &[String]) -> Result<(), String> {
    const USAGE: &str = "usage: instinct doctor --leftovers [--fix] [--min-age MINUTES] [--quiet]";
    #[cfg(not(target_os = "linux"))]
    {
        let _ = (argv, USAGE);
        println!("not supported here: --leftovers reads Linux /proc");
        Ok(())
    }
    #[cfg(target_os = "linux")]
    {
        let (mut fix, mut quiet, mut min_age) = (fix_by_default() && argv.iter().any(|a| a == "--quiet"), false, 15u64);
        let mut i = 0;
        while i < argv.len() {
            match argv[i].as_str() {
                "--leftovers" => {}
                "--fix" => fix = true,
                "--quiet" => quiet = true,
                "--min-age" => {
                    i += 1;
                    min_age = argv.get(i).and_then(|v| v.parse().ok()).ok_or(USAGE)?;
                }
                _ => return Err(USAGE.into()),
            }
            i += 1;
        }
        if !enabled() {
            if !quiet {
                println!("cleanup is off (INSTINCT_CLEANUP=0)");
            }
            return Ok(());
        }
        let procs = waits::linux::mine();
        let safe = waits::safe_pids(&procs);
        let now = waits::linux::uptime_ticks();
        let home = std::env::var("HOME").unwrap_or_default();
        let mut found = 0;
        let mut stopped = 0;
        let say = |s: String| {
            if quiet {
                eprintln!("{s}");
            } else {
                println!("{s}");
            }
        };
        // (a) stale wait loops, and every pid they cover, so (b) does not list them twice
        let mut covered: Vec<u32> = Vec::new();
        for s in waits::stale_waits(&procs, &safe, min_age) {
            found += 1;
            say(format!("wait loop   pid {}  {} min old  {}", s.pid, s.age_min, s.snippet));
            say(format!("    class: {}", speed::class_of(&s.snippet).unwrap_or_else(|| "shell wait loop (until/while + sleep)".into())));
            say("    prevent: the wait tripwires. Wait on a saved PID or the output file with a deadline, run it in the background, or arm `gh pr merge --auto`.".into());
            for w in &s.why {
                say(format!("    why: {}", w.text()));
            }
            covered.push(s.pid);
            covered.extend(procs.iter().filter(|c| c.ppid == s.pid).map(|c| c.pid));
            if fix {
                waits::stop_tree(&procs, s.pid);
                stopped += 1;
            }
        }
        // (b) orphaned leftovers
        let own_cg = fs::read_to_string("/proc/self/cgroup").unwrap_or_default();
        let systemd_user: Vec<u32> = waits::linux::mine_all().iter().filter(|p| p.args.first().is_some_and(|a| a.ends_with("/systemd") || a == "systemd") && p.args.iter().any(|a| a == "--user")).map(|p| p.pid).collect();
        for p in &procs {
            if safe.contains(&p.pid) || covered.contains(&p.pid) || p.tty != 0 {
                continue;
            }
            if !(p.ppid == 1 || systemd_user.contains(&p.ppid)) {
                continue;
            }
            let age_min = waits::linux::ticks_to_min(now, p.start);
            if age_min < min_age {
                continue;
            }
            let cg = fs::read_to_string(format!("/proc/{}/cgroup", p.pid)).unwrap_or_default();
            if cg.is_empty() || in_foreign_service(&cg, &own_cg) {
                continue;
            }
            let Some(shape) = leftover_shape(&p.args, &home) else { continue };
            found += 1;
            let cmd: String = p.args.join(" ").chars().take(100).collect();
            say(format!("leftover    pid {}  {} min old  {cmd}", p.pid, age_min));
            say(format!("    why: {shape}; parent is init or your systemd, no terminal, not a systemd service"));
            say(format!("    class: {}", speed::class_of(&cmd).unwrap_or_else(|| shape.to_string())));
            say("    prevent: the orphan tripwire (a detached launch: setsid, nohup, or `&` that outlives its caller). Start it with run_in_background and stop it when its job is done.".into());
            if fix {
                waits::stop_tree(&procs, p.pid);
                stopped += 1;
            }
        }
        // (c) merged, clean, idle worktrees
        if let Ok(cwd) = std::env::current_dir() {
            for (path, branch) in merged_worktrees(&cwd, &procs, min_age) {
                found += 1;
                say(format!("worktree    {}  (branch {branch})", path.display()));
                say("    why: the branch is merged into origin/main, the tree is clean, and no process is working in it".into());
                say("    prevent: reuse one slot per builder (slot.sh claim / done) instead of a worktree per task.".into());
                if fix {
                    let ok = git(&cwd, &["worktree", "remove", &path.display().to_string()]).is_some_and(|(ok, _)| ok);
                    println!("    {} worktree {}", if ok { "removed" } else { "could not remove" }, path.display());
                    stopped += usize::from(ok);
                }
            }
        }
        if quiet {
            if found > 0 {
                eprintln!("instinct cleanup: {found} leftover(s) found{}", if fix { format!(", {stopped} stopped or removed") } else { "; `instinct doctor --leftovers --fix` stops them".into() });
            }
        } else {
            if found == 0 {
                println!("no leftovers older than {min_age} min");
            } else if !fix {
                println!("{found} leftover(s). `instinct doctor --leftovers --fix` stops them (your own processes only, never systemd services; worktrees only when merged and clean).");
            }
        }
        Ok(())
    }
}

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

    fn a(s: &str) -> Vec<String> {
        s.split(' ').map(String::from).collect()
    }

    #[test]
    fn shapes() {
        assert_eq!(leftover_shape(&a("/usr/bin/brave --headless --remote-debugging-port=9222"), "/home/u"), Some("headless browser"));
        assert_eq!(leftover_shape(&a("chromium --remote-debugging-port=0"), "/home/u"), Some("headless browser"));
        assert_eq!(leftover_shape(&a("brave --new-window"), "/home/u"), None);
        assert_eq!(leftover_shape(&a("tail -f /dev/null"), "/home/u"), Some("`tail -f /dev/null`"));
        assert_eq!(leftover_shape(&a("tail -f /var/log/x"), "/home/u"), None);
        assert_eq!(leftover_shape(&a("sleep 600"), "/home/u"), Some("`sleep`"));
        assert_eq!(leftover_shape(&a("/w/target/release/deps/foo-1a2b --nocapture"), "/home/u"), Some("cargo test binary"));
        assert_eq!(leftover_shape(&a("node /home/u/.cache/x/run.mjs"), "/home/u"), Some("script run from /tmp or ~/.cache"));
        assert_eq!(leftover_shape(&a("bash /tmp/job.sh"), "/home/u"), Some("script run from /tmp or ~/.cache"));
        assert_eq!(leftover_shape(&a("node /home/u/app/server.js"), "/home/u"), None);
        assert_eq!(leftover_shape(&a("vim notes.txt"), "/home/u"), None);
    }

    #[test]
    fn services_are_recognised_from_the_cgroup() {
        assert!(in_service("0::/system.slice/nginx.service\n"));
        assert!(in_service("0::/user.slice/user-1000.slice/user@1000.service/app.slice/app-foo@autostart.service\n"));
        assert!(!in_service("0::/user.slice/user-1000.slice/user@1000.service/app.slice/ptyxis-spawn-1.scope\n"));
        assert!(!in_service("0::/user.slice/user-1000.slice/session-3.scope\n"));
        let ci = "0::/system.slice/hosted-compute-agent.service\n";
        assert!(in_foreign_service(ci, "0::/user.slice/user-1000.slice/session-3.scope\n"), "another service's process stays exempt");
        assert!(!in_foreign_service(ci, ci), "orphans in the caller's own service are the caller's leftovers");
        assert!(in_foreign_service("0::/system.slice/nginx.service\n", ci));
    }
}