instinct-cli 0.3.9

Shared local memory for coding agents. Save a fix once and find it again in a new session or another connected tool.
//! `instinct doctor --waits [--min-age MIN] [--fix]`: finds background wait loops that will never end or whose
//! result is already in, and with `--fix` stops them. A shell `-c` script qualifies when it holds a loop
//! (`until`/`while`/`for`) that polls with `sleep`, `tail --pid` or `pgrep`, is older than MIN minutes
//! (default 10), and at least one of these holds:
//!   1. a file it tests with `[ -s F ]` / `-e` / `-f` already exists;
//!   2. a process it awaits (`tail --pid=N`, `kill -0 N`, `/proc/N`) is gone;
//!   3. it runs `pgrep -f PATTERN` and PATTERN occurs in its own command line, so it matches itself.
//! Only processes of the caller's UID, never anything outside the loop's own shell and its children. Linux
//! `/proc` only; no new crates.
use super::*;

#[derive(Debug, PartialEq)]
pub enum Why {
    FileExists(String),
    ProcessGone(u32),
    MatchesItself(String),
}

impl Why {
    pub fn text(&self) -> String {
        match self {
            Why::FileExists(f) => format!("the file it waits for already exists: {f}"),
            Why::ProcessGone(p) => format!("the process it waits for (pid {p}) is gone"),
            Why::MatchesItself(p) => format!("`pgrep -f {p}` matches this loop's own command line, so it never ends"),
        }
    }
}

fn clean(tok: &str) -> &str {
    tok.trim_matches(|c| matches!(c, '"' | '\'' | ';' | '(' | ')' | '{' | '}' | '`'))
}

fn is_loop_with_poll(script: &str) -> bool {
    let words: Vec<&str> = script.split(|c: char| c.is_whitespace() || c == ';').map(clean).collect();
    let looped = words.iter().any(|w| matches!(*w, "until" | "while" | "for"));
    let polls = script.contains("sleep ") || script.contains("tail --pid") || script.contains("pgrep");
    looped && polls
}

/// Reasons this script's loop is stale. `exists` and `alive` are the machine's answers, passed in so the
/// logic is testable without processes.
pub fn analyze(script: &str, cwd: &str, exists: &dyn Fn(&str) -> bool, alive: &dyn Fn(u32) -> bool) -> Vec<Why> {
    let mut out = Vec::new();
    if !is_loop_with_poll(script) {
        return out;
    }
    let toks: Vec<&str> = script.split_whitespace().map(clean).collect();
    for (i, t) in toks.iter().enumerate() {
        let next = toks.get(i + 1).copied().unwrap_or("");
        match *t {
            "-s" | "-e" | "-f" if i > 0 && matches!(toks[i - 1], "[" | "[[" | "test" | "!") && !next.is_empty() => {
                let p = if next.starts_with('/') { next.to_string() } else { format!("{cwd}/{next}") };
                if !next.contains('$') && exists(&p) {
                    out.push(Why::FileExists(next.to_string()));
                }
            }
            "kill" if next == "-0" => {
                if let Some(p) = toks.get(i + 2).and_then(|v| v.parse::<u32>().ok()) {
                    if !alive(p) {
                        out.push(Why::ProcessGone(p));
                    }
                }
            }
            "pgrep" => {
                // `pgrep -f PATTERN`: the pattern is the first non-flag word after the flags.
                let mut j = i + 1;
                let mut full = false;
                while let Some(w) = toks.get(j) {
                    if w.starts_with('-') {
                        full |= w.contains('f') && !w.starts_with("--");
                        j += 1;
                    } else {
                        break;
                    }
                }
                if let (true, Some(pat)) = (full, toks.get(j)) {
                    // `[x]yz` is the classic trick to avoid matching oneself.
                    if !pat.is_empty() && !pat.contains('[') && !pat.contains('$') && script.matches(pat).count() >= 1 {
                        out.push(Why::MatchesItself(pat.to_string()));
                    }
                }
            }
            _ => {
                let pid = t.strip_prefix("--pid=").or_else(|| if *t == "--pid" { Some(next) } else { None });
                if let Some(p) = pid.and_then(|v| v.parse::<u32>().ok()) {
                    if !alive(p) {
                        out.push(Why::ProcessGone(p));
                    }
                }
                if let Some(p) = t.strip_prefix("/proc/").and_then(|r| r.split('/').next()).and_then(|v| v.parse::<u32>().ok()) {
                    if !alive(p) {
                        out.push(Why::ProcessGone(p));
                    }
                }
            }
        }
    }
    out
}

#[cfg(target_os = "linux")]
pub(crate) mod linux {
    use super::*;
    use std::os::unix::fs::MetadataExt;

    pub struct Proc {
        pub pid: u32,
        pub ppid: u32,
        pub start: u64,
        pub tty: i64,
        pub args: Vec<String>,
        pub cwd: String,
    }

    fn stat(pid: u32) -> Option<(u32, u64, i64)> {
        let s = fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
        // comm may hold spaces and parens: fields start after the last ')'.
        let rest = &s[s.rfind(')')? + 2..];
        let f: Vec<&str> = rest.split(' ').collect();
        Some((f.get(1)?.parse().ok()?, f.get(19)?.parse().ok()?, f.get(4)?.parse().ok()?))
    }

    pub fn uptime_ticks() -> u64 {
        fs::read_to_string("/proc/uptime").ok().and_then(|s| s.split(' ').next().and_then(|v| v.parse::<f64>().ok())).map(|s| (s * 100.0) as u64).unwrap_or(0)
    }

    pub fn ticks_to_min(now: u64, start: u64) -> u64 {
        now.saturating_sub(start) / 100 / 60
    }

    pub fn alive(pid: u32) -> bool {
        Path::new(&format!("/proc/{pid}")).exists()
    }

    /// Test seam: `INSTINCT_LEFTOVERS_SCOPE_PIDS=1,2,3` limits every scan, and so every `--fix`, to those pids and
    /// their children. Nothing outside the scope is listed or touched.
    fn scope() -> Option<Vec<u32>> {
        let v = std::env::var("INSTINCT_LEFTOVERS_SCOPE_PIDS").ok()?;
        Some(v.split(',').filter_map(|p| p.trim().parse().ok()).collect())
    }

    /// Every process of this user, ignoring the test scope (needed to recognise the user's systemd as a parent).
    pub fn mine() -> Vec<Proc> {
        let mut v = mine_all();
        if let Some(s) = scope() {
            v.retain(|p| s.contains(&p.pid) || s.contains(&p.ppid));
        }
        v
    }

    pub fn mine_all() -> Vec<Proc> {
        let me = fs::metadata("/proc/self").map(|m| m.uid()).unwrap_or(u32::MAX);
        let mut v = Vec::new();
        let Ok(rd) = fs::read_dir("/proc") else { return v };
        for e in rd.flatten() {
            let Some(pid) = e.file_name().to_str().and_then(|n| n.parse::<u32>().ok()) else { continue };
            if fs::metadata(e.path()).map(|m| m.uid()).ok() != Some(me) {
                continue;
            }
            let Some((ppid, start, tty)) = stat(pid) else { continue };
            let Ok(raw) = fs::read(e.path().join("cmdline")) else { continue };
            let args: Vec<String> = raw.split(|b| *b == 0).filter(|a| !a.is_empty()).map(|a| String::from_utf8_lossy(a).into_owned()).collect();
            let cwd = fs::read_link(e.path().join("cwd")).map(|p| p.display().to_string()).unwrap_or_default();
            v.push(Proc { pid, ppid, start, tty, args, cwd });
        }
        v
    }
}


/// A stale wait loop: its shell, its age, a snippet of its script and why it qualifies.
#[cfg(target_os = "linux")]
pub struct Stale {
    pub pid: u32,
    pub age_min: u64,
    pub snippet: String,
    pub why: Vec<Why>,
}

/// pids that must never be touched: this process and its ancestors.
#[cfg(target_os = "linux")]
pub fn safe_pids(procs: &[linux::Proc]) -> Vec<u32> {
    let own = std::process::id();
    let mut safe = vec![own];
    let mut cur = own;
    while let Some(p) = procs.iter().find(|p| p.pid == cur) {
        if p.ppid <= 1 || safe.contains(&p.ppid) {
            break;
        }
        safe.push(p.ppid);
        cur = p.ppid;
    }
    safe
}

#[cfg(target_os = "linux")]
pub fn stale_waits(procs: &[linux::Proc], safe: &[u32], min_age: u64) -> Vec<Stale> {
    let now = linux::uptime_ticks();
    let mut out = Vec::new();
    for p in procs {
        let shell = p.args.first().map(|a| a.rsplit('/').next().unwrap_or("")).unwrap_or("");
        if safe.contains(&p.pid) || !matches!(shell, "bash" | "sh" | "zsh" | "dash") {
            continue;
        }
        let Some(ci) = p.args.iter().position(|a| a == "-c") else { continue };
        let Some(script) = p.args.get(ci + 1) else { continue };
        let age_min = linux::ticks_to_min(now, p.start);
        if age_min < min_age {
            continue;
        }
        let exists = |f: &str| Path::new(f).exists() && fs::metadata(f).map(|m| m.len() > 0 || f.ends_with('/')).unwrap_or(false);
        let why = analyze(script, &p.cwd, &exists, &linux::alive);
        if why.is_empty() {
            continue;
        }
        let snippet: String = script.split_whitespace().collect::<Vec<_>>().join(" ").chars().take(100).collect();
        out.push(Stale { pid: p.pid, age_min, snippet, why });
    }
    out
}

/// Stops `pid` and its direct children with SIGTERM; prints one line each.
#[cfg(target_os = "linux")]
pub fn stop_tree(procs: &[linux::Proc], pid: u32) {
    let mut targets: Vec<u32> = procs.iter().filter(|c| c.ppid == pid).map(|c| c.pid).collect();
    targets.push(pid);
    for t in targets {
        let ok = std::process::Command::new("kill").arg(t.to_string()).stderr(std::process::Stdio::null()).status().map(|s| s.success()).unwrap_or(false);
        println!("    {} pid {t}", if ok { "stopped" } else { "could not stop" });
    }
}

pub fn run(argv: &[String]) -> Result<(), String> {
    const USAGE: &str = "usage: instinct doctor --waits [--min-age MINUTES] [--fix]";
    #[cfg(not(target_os = "linux"))]
    {
        let _ = (argv, USAGE);
        println!("not supported here: --waits reads Linux /proc");
        Ok(())
    }
    #[cfg(target_os = "linux")]
    {
        let mut fix = false;
        let mut min_age: u64 = 10;
        let mut i = 0;
        while i < argv.len() {
            match argv[i].as_str() {
                "--waits" => {}
                "--fix" => fix = 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;
        }
        let procs = linux::mine();
        let safe = safe_pids(&procs);
        let mut found = 0;
        for s in stale_waits(&procs, &safe, min_age) {
            found += 1;
            println!("pid {}  {} min old  {}", s.pid, s.age_min, s.snippet);
            for w in &s.why {
                println!("    why: {}", w.text());
            }
            if fix {
                stop_tree(&procs, s.pid);
            }
        }
        if found == 0 {
            println!("no stale wait loops older than {min_age} min");
        } else if !fix {
            println!("{found} stale wait loop(s). `instinct doctor --waits --fix` stops them (your user's processes only, each loop's own shell and children).");
        }
        Ok(())
    }
}

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

    #[test]
    fn finds_the_three_shapes_and_leaves_live_waits_alone() {
        let yes = |_: &str| true;
        let no = |_: &str| false;
        let alive = |p: u32| p == 7;
        let a = analyze("until [ -s /t/out.txt ]; do sleep 2; done", "/", &yes, &alive);
        assert_eq!(a, vec![Why::FileExists("/t/out.txt".into())]);
        assert!(analyze("until [ -s /t/out.txt ]; do sleep 2; done", "/", &no, &alive).is_empty());
        assert_eq!(analyze("tail --pid=99 -f /dev/null; echo", "/", &no, &alive), vec![]); // no loop keyword
        assert_eq!(analyze("while tail --pid=99 -f /dev/null; do sleep 1; done", "/", &no, &alive), vec![Why::ProcessGone(99)]);
        assert!(analyze("while tail --pid=7 -f /dev/null; do sleep 1; done", "/", &no, &alive).is_empty());
        let s = analyze("until ! pgrep -f \"xyz-sleeper\"; do sleep 1; done", "/", &no, &alive);
        assert_eq!(s, vec![Why::MatchesItself("xyz-sleeper".into())]);
        assert!(analyze("until ! pgrep -f \"[x]yz-sleeper\"; do sleep 1; done", "/", &no, &alive).is_empty());
    }
}