oomtop-cli 0.2.0

oomtop: see the OOM coming. Terminal resource monitor for local AI work.
Documentation
//! `oomtop stale`: what is stale (SPEC §7 "Staleness"), what ended agent sessions left behind, and
//! duplicate instances. Answer first in one sentence; an aligned table only when there is something to act
//! on; one line per item so it still reads well in a screen reader and through `grep`. Ids, scores and weak
//! signals are in `--json`.

use super::{json_pretty, out, Ctx};
use anyhow::Result;
use oomtop_core::provider::SnapshotProvider;
use oomtop_core::redact::redact_snapshot;
use oomtop_core::staleness::{ranked, StalenessConfig};
use oomtop_core::units::format_duration;
use oomtop_core::{Group, Snapshot, SourceStatus};
use serde::Serialize;

/// Frames a replay is advanced through at most (idle times need the observed window).
const MAX_REPLAY_FRAMES: usize = 10_000;

#[derive(Serialize)]
struct StaleRow<'a> {
    id: &'a str,
    label: &'a str,
    kind: &'a str,
    score: f64,
    stale: bool,
    footprint: &'a oomtop_core::Measured<u64>,
    age_s: &'a oomtop_core::Measured<u64>,
    duty_pct: &'a oomtop_core::Measured<f64>,
    idle_rent_gib_h: &'a oomtop_core::Measured<f64>,
    idle_for_s: Option<u64>,
    longest_idle_s: Option<u64>,
    project: Option<&'a str>,
    cohort: Option<&'a str>,
    evidence: &'a [oomtop_core::staleness::StaleEvidence],
}

#[derive(Serialize)]
struct StaleReport<'a> {
    schema_version: u32,
    taken_at_ms: u64,
    thresholds: &'a StalenessConfig,
    /// Groups flagged stale.
    stale_count: usize,
    /// Groups with any evidence, most stale first (at most `--limit`).
    groups: Vec<StaleRow<'a>>,
    cohorts: &'a [oomtop_core::staleness::Cohort],
    duplicates: &'a [oomtop_core::staleness::DuplicateSet],
}

fn row(g: &Group) -> StaleRow<'_> {
    StaleRow {
        id: &g.id,
        label: &g.label,
        kind: g.kind.alias(),
        score: (g.staleness.score * 1000.0).round() / 1000.0,
        stale: g.staleness.stale,
        footprint: &g.totals.footprint,
        age_s: &g.age_s,
        duty_pct: &g.duty_pct,
        idle_rent_gib_h: &g.idle_rent_gib_h,
        idle_for_s: g.idle_for_s,
        longest_idle_s: g.longest_idle_s,
        project: g.project.as_deref(),
        cohort: g.cohort.as_deref(),
        evidence: &g.staleness.evidence,
    }
}

/// The snapshot to rank: one on-demand sample live; with `--replay`, the last frame after playing every
/// frame (idle times grow over the replayed window, as in the TUI).
fn snapshot(ctx: &Ctx) -> Result<Snapshot> {
    let mut e = ctx.engine(true)?;
    let mut s = e.snapshot();
    if ctx.replaying() {
        for _ in 0..MAX_REPLAY_FRAMES {
            if e.replay_done() {
                break;
            }
            s = e.snapshot();
        }
    }
    Ok(s)
}

pub fn run(ctx: &Ctx, json: bool, limit: usize) -> Result<i32> {
    let s = snapshot(ctx)?;
    let cfg = ctx.config().staleness_config();
    if json {
        let s = if ctx.config().privacy.redact_exports {
            redact_snapshot(&s)
        } else {
            s
        };
        let list = ranked(&s);
        let report = StaleReport {
            schema_version: s.schema_version,
            taken_at_ms: s.taken_at_ms,
            thresholds: &cfg,
            stale_count: list.iter().filter(|g| g.staleness.stale).count(),
            groups: list.iter().take(limit).map(|g| row(g)).collect(),
            cohorts: &s.cohorts,
            duplicates: &s.duplicates,
        };
        out(&json_pretty(&report)?);
        return Ok(0);
    }
    out(&render(ctx, &s, limit));
    Ok(0)
}

/// Terminal columns for laying out the table: the tty's width, else `$COLUMNS`, else 100.
fn term_width() -> usize {
    #[cfg(unix)]
    {
        use std::io::IsTerminal;
        if std::io::stdout().is_terminal() {
            let mut ws: libc::winsize = unsafe { std::mem::zeroed() };
            // SAFETY: TIOCGWINSZ fills a winsize for a terminal fd; the struct is zero-initialised.
            if unsafe { libc::ioctl(libc::STDOUT_FILENO, libc::TIOCGWINSZ, &mut ws) } == 0 && ws.ws_col > 0 {
                return ws.ws_col as usize;
            }
        }
    }
    std::env::var("COLUMNS")
        .ok()
        .and_then(|c| c.parse().ok())
        .filter(|&c: &usize| c >= 40)
        .unwrap_or(100)
}

/// Bold / dim only on a terminal and never with `NO_COLOR`; meaning never depends on it.
struct Ink(bool);
impl Ink {
    fn detect() -> Self {
        use std::io::IsTerminal;
        Ink(std::io::stdout().is_terminal()
            && std::env::var_os("NO_COLOR").is_none()
            && std::env::var("TERM").map(|t| t != "dumb").unwrap_or(true))
    }
    fn bold(&self, t: &str) -> String {
        if self.0 {
            format!("\x1b[1m{t}\x1b[0m")
        } else {
            t.to_string()
        }
    }
    fn dim(&self, t: &str) -> String {
        if self.0 {
            format!("\x1b[2m{t}\x1b[0m")
        } else {
            t.to_string()
        }
    }
}

fn clip(t: &str, w: usize) -> String {
    if t.chars().count() <= w {
        return t.to_string();
    }
    let mut out: String = t.chars().take(w.saturating_sub(1)).collect();
    out.push('…');
    out
}

fn pad(t: &str, w: usize) -> String {
    let t = clip(t, w);
    let n = t.chars().count();
    format!("{t}{}", " ".repeat(w.saturating_sub(n)))
}

fn rpad(t: &str, w: usize) -> String {
    let n = t.chars().count();
    format!("{}{t}", " ".repeat(w.saturating_sub(n)))
}

/// A few words per piece of evidence, for the WHY column; the full sentences are in `--json` and the TUI.
fn short_reason(e: &oomtop_core::staleness::StaleEvidence) -> String {
    use oomtop_core::staleness::StaleSignal as S;
    let after = |prefix: &str| {
        e.sentence
            .split(prefix)
            .nth(1)
            .and_then(|r| r.split(" (").next())
            .map(|d| d.trim().to_string())
    };
    match e.signal {
        S::CwdMissing => "its folder was deleted".into(),
        S::ExeDeleted => "binary deleted".into(),
        S::ExeReplaced => "binary updated since it started".into(),
        S::Stopped => "suspended".into(),
        S::Orphaned => match e.sentence.strip_prefix("orphaned: ") {
            Some(r) if !r.starts_with("the agent session or tool") => format!("orphan, {r}"),
            _ => "orphan, its parent is gone".into(),
        },
        S::IdleLong => after("idle for ").map_or("idle".into(), |d| format!("idle {d}")),
        S::TranscriptQuiet => {
            after("not modified for ").map_or("session quiet".into(), |d| format!("session quiet {d}"))
        }
        S::ListeningNoClients => "listening, nobody connected".into(),
    }
}

/// Answer first, then an aligned table only when there is something to act on. Ids, scores and weak
/// signals are for `--json` (and `--limit` still caps the rows).
fn render(ctx: &Ctx, s: &Snapshot, limit: usize) -> String {
    let ink = Ink::detect();
    let width = term_width().clamp(60, 200);
    let list = ranked(s);
    let mut stale: Vec<&&Group> = list.iter().filter(|g| g.staleness.stale).collect();
    // Biggest first: the table answers "what is worth stopping".
    stale.sort_by_key(|g| std::cmp::Reverse(g.totals.footprint.value.unwrap_or(0)));
    // Same name twice ("Codex", "Codex"): say which one by its root pid.
    let name = |g: &Group| {
        let twin = stale.iter().filter(|o| o.label == g.label).count() > 1;
        match (twin, g.root) {
            (true, Some(r)) => format!("{} · {}", g.label, r.pid),
            _ => g.label.clone(),
        }
    };
    let mut o = String::new();

    if stale.is_empty() {
        o.push_str(&ink.bold("Nothing is stale."));
        let weak = list.len();
        if weak > 0 {
            o.push_str(&ink.dim(&format!(
                "  {weak} group{} show{} a weak signal; `oomtop stale --json` lists them.",
                if weak == 1 { "" } else { "s" },
                if weak == 1 { "s" } else { "" },
            )));
        }
        o.push('\n');
    } else {
        let mem: u64 = stale.iter().filter_map(|g| g.totals.footprint.value).sum();
        o.push_str(&ink.bold(&format!(
            "{} stale, holding {}.",
            if stale.len() == 1 {
                "1 thing is".to_string()
            } else {
                format!("{} things are", stale.len())
            },
            ctx.fmt(mem),
        )));
        o.push_str("\n\n");
        // WHAT  MEMORY  ALIVE  WHY
        let (mem_w, age_w) = (9, 6);
        let what_w = stale
            .iter()
            .map(|g| name(g).chars().count())
            .max()
            .unwrap_or(4)
            .clamp(8, 28);
        let why_w = width
            .saturating_sub(2 + what_w + 2 + mem_w + 2 + age_w + 2)
            .max(16);
        o.push_str(&ink.dim(&format!(
            "  {}  {}  {}  {}\n",
            pad("WHAT", what_w),
            rpad("MEMORY", mem_w),
            rpad("ALIVE", age_w),
            "WHY"
        )));
        for g in stale.iter().take(limit) {
            let why: Vec<String> = g.staleness.evidence.iter().map(short_reason).collect();
            o.push_str(&format!(
                "  {}  {}  {}  {}\n",
                pad(&name(g), what_w),
                rpad(&ctx.fmt_opt(g.totals.footprint.value), mem_w),
                rpad(
                    &g.age_s.value.map(format_duration).unwrap_or_else(|| "?".into()),
                    age_w
                ),
                clip(&why.join(" · "), why_w),
            ));
        }
        if stale.len() > limit {
            o.push_str(&ink.dim(&format!("  … {} more (--limit N)\n", stale.len() - limit)));
        }
    }

    if !s.cohorts.is_empty() {
        o.push('\n');
        o.push_str(&ink.bold("Left behind by ended agent sessions"));
        o.push('\n');
        for c in &s.cohorts {
            o.push_str(&format!(
                "  {}  {}  {} process{}\n",
                rpad(&ctx.fmt_opt(c.footprint.value), 9),
                clip(&c.label, width.saturating_sub(30).max(20)),
                c.process_count,
                if c.process_count == 1 { "" } else { "es" },
            ));
        }
    }
    if !s.duplicates.is_empty() {
        o.push('\n');
        o.push_str(&ink.bold("Running more than once in the same project"));
        o.push('\n');
        for d in &s.duplicates {
            let project = d.project.rsplit('/').next().unwrap_or(&d.project);
            o.push_str(&format!(
                "  {}  {} × {} in {}  {}\n",
                rpad(&ctx.fmt_opt(d.footprint.value), 9),
                d.group_ids.len(),
                d.label,
                project,
                ink.dim(&format!("(extras hold {})", ctx.fmt_opt(d.extra_footprint.value))),
            ));
        }
    }

    if !stale.is_empty() || !s.cohorts.is_empty() {
        o.push('\n');
        o.push_str(&ink.dim(
            "  oomtop reclaim --dry-run   what stopping them would free (asks before it stops anything)",
        ));
        o.push('\n');
    }
    let unavailable: Vec<&str> = s
        .source_status
        .iter()
        .filter(|(_, st)| matches!(st, SourceStatus::Unavailable(_)))
        .map(|(k, _)| k.as_str())
        .collect();
    if !unavailable.is_empty() {
        o.push_str(&ink.dim(&format!(
            "  not measured: {} (oomtop doctor)\n",
            unavailable.join(", ")
        )));
    }
    o
}

#[cfg(test)]
mod tests {
    #[test]
    fn columns_clip_and_pad_to_width() {
        assert_eq!(super::pad("abc", 5), "abc  ");
        assert_eq!(super::pad("abcdefgh", 5), "abcd…");
        assert_eq!(super::rpad("3.1G", 6), "  3.1G");
        assert_eq!(super::clip("short", 10), "short");
    }
}