use super::table::{clip, pad, rpad, term_width, Ink};
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;
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,
stale_count: usize,
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,
}
}
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)
}
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(),
}
}
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();
stale.sort_by_key(|g| std::cmp::Reverse(g.totals.footprint.value.unwrap_or(0)));
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");
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
}