oomtop-cli 0.2.1

oomtop: see the OOM coming. Terminal resource monitor for local AI work.
Documentation
//! `oomtop stale` and the time/staleness fields of `oomtop json` (SPEC §5 "Time and staleness", §7
//! "Staleness") against the recorded fixtures. Private XDG dirs: nothing touches the real config or state.

use serde_json::Value;
use std::path::PathBuf;
use std::process::{Command, Stdio};

fn root() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../..")
}

fn fixture(rel: &str) -> String {
    root().join(rel).to_string_lossy().into_owned()
}

struct Out {
    code: i32,
    out: String,
    err: String,
}

fn run(fixture_rel: &str, args: &[&str]) -> Out {
    let dir = tempfile::tempdir().unwrap();
    let mut c = Command::new(env!("CARGO_BIN_EXE_oomtop"));
    c.env("XDG_CONFIG_HOME", dir.path().join("config"))
        .env("XDG_STATE_HOME", dir.path().join("state"))
        .env("TERM", "dumb")
        .stdin(Stdio::null())
        .args(["--replay", &fixture(fixture_rel), "--offline"])
        .args(args);
    for (k, _) in std::env::vars() {
        if k.starts_with("OOMTOP_") {
            c.env_remove(k);
        }
    }
    let o = c.output().unwrap();
    Out {
        code: o.status.code().unwrap_or(-1),
        out: String::from_utf8_lossy(&o.stdout).into_owned(),
        err: String::from_utf8_lossy(&o.stderr).into_owned(),
    }
}

const MAC: &str = "fixtures/macos/m5-air-agents.json";
const LINUX: &str = "fixtures/linux/nvidia-oom-trend.json";

#[test]
fn stale_plain_answers_first_and_lists_evidence() {
    let r = run(MAC, &["stale"]);
    assert_eq!(r.code, 0, "{}{}", r.out, r.err);
    let first = r.out.lines().next().unwrap_or_default();
    assert!(
        first.ends_with(").") || first.ends_with('.'),
        "answer first, one sentence: {first:?}"
    );
    assert!(
        first.contains(" stale, holding ") || first.starts_with("Nothing is stale."),
        "{first:?}"
    );
    // stale rows sit under a WHAT / MEMORY / ALIVE / WHY header, one line each, ids kept out of the text
    let lines: Vec<&str> = r.out.lines().collect();
    let ranked = match lines.iter().position(|l| l.trim_start().starts_with("WHAT")) {
        Some(h) => {
            assert!(lines[h].contains("MEMORY") && lines[h].contains("ALIVE") && lines[h].contains("WHY"));
            lines[h + 1..].iter().take_while(|l| !l.trim().is_empty()).count()
        }
        None => 0,
    };
    assert!(!r.out.contains("agent:builtin:"), "group ids belong in --json");
    assert!(ranked <= 10, "default --limit is 10");
    // plain: no escape sequences, no box drawing
    assert!(!r.out.contains('\u{1b}'), "no ANSI escapes");
    assert!(!r.out.contains('│') && !r.out.contains('─'));
    // deterministic: the same fixture gives the same answer
    assert_eq!(run(MAC, &["stale"]).out, r.out);
}

#[test]
fn stale_json_is_ranked_and_bounded() {
    let r = run(MAC, &["stale", "--json", "--limit", "3"]);
    assert_eq!(r.code, 0, "{}", r.err);
    let v: Value = serde_json::from_str(&r.out).unwrap();
    assert_eq!(v["schema_version"], 1);
    assert_eq!(v["thresholds"]["idle_s"], 14_400);
    assert_eq!(v["thresholds"]["stale_score"], 0.5);
    let groups = v["groups"].as_array().unwrap();
    assert!(groups.len() <= 3);
    let scores: Vec<(bool, f64)> = groups
        .iter()
        .map(|g| (g["stale"].as_bool().unwrap(), g["score"].as_f64().unwrap()))
        .collect();
    for w in scores.windows(2) {
        assert!(w[0] >= w[1], "stale first, then by score: {scores:?}");
    }
    for g in groups {
        let ev = g["evidence"].as_array().unwrap();
        assert!(!ev.is_empty(), "only groups with evidence are listed");
        for e in ev {
            assert!(e["signal"].is_string() && e["sentence"].is_string());
            let w = e["weight"].as_f64().unwrap();
            assert!((0.0..=1.0).contains(&w));
        }
        assert!(g["age_s"]["source"].is_string());
    }
    assert!(v["cohorts"].is_array() && v["duplicates"].is_array());
}

#[test]
fn json_carries_time_fields_additively() {
    for fx in [MAC, LINUX] {
        let r = run(fx, &["json"]);
        assert_eq!(r.code, 0, "{fx}: {}", r.err);
        let v: Value = serde_json::from_str(&r.out).unwrap();
        assert_eq!(
            v["schema_version"], 1,
            "additive: the schema version does not change"
        );
        let procs = v["processes"].as_array().unwrap();
        let with_cpu = procs
            .iter()
            .filter(|p| p["cpu_time_s"]["value"].is_number())
            .count();
        assert!(with_cpu > 0, "{fx}: CPU time decoded");
        for p in procs {
            // every process has an age (start times are known in both fixtures) with provenance
            assert!(p["age_s"]["source"].is_string(), "{fx}: {p}");
            assert!(p["duty_pct"].is_object());
            // idle rent is never exact: an estimate, or unavailable with its reason
            let q = &p["idle_rent_gib_h"]["quality"];
            assert!(q == "estimate" || q["unavailable"].is_string(), "{fx}: {q}");
        }
        let groups = v["groups"].as_array().unwrap();
        assert!(groups
            .iter()
            .all(|g| g["age_s"].is_object() && g["duty_pct"].is_object()));
        // a group's age is its root's (or oldest member's) age
        assert!(groups.iter().any(|g| g["age_s"]["source"]
            .as_str()
            .unwrap_or("")
            .starts_with("root process")));
    }
}

#[test]
fn stale_limit_zero_still_answers() {
    let r = run(LINUX, &["stale", "--limit", "0"]);
    assert_eq!(r.code, 0, "{}", r.err);
    assert!(!r.out.is_empty());
    assert!(!r.out.lines().any(|l| l.starts_with("1. ")));
}