mod report;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::{Duration, Instant, SystemTime};
pub use report::{document, render_human, render_json};
use serde::Deserialize;
use crate::delete::{Guard, Outcome, Removal};
use crate::error::Result;
use crate::size::measure_fully;
pub const SCHEMA_VERSION: u32 = 1;
const STATE_FILE_NAME: &str = "state.json";
const STATE_FILE_MAX_BYTES: u64 = 64 * 1024;
const SCRATCH_DIR_NAME: &str = "tmp";
pub const DEFAULT_MIN_AGE: Duration = Duration::from_secs(14 * 24 * 60 * 60);
#[derive(Debug, Deserialize)]
struct State {
#[serde(rename = "sessionId")]
session_id: Option<String>,
#[serde(rename = "lastTerminalAt")]
last_terminal_at: Option<String>,
}
#[expect(
clippy::struct_excessive_bools,
reason = "these mirror command-line flags, which are bools by nature"
)]
#[derive(Debug, Clone)]
pub struct ClaudePruneOptions {
pub roots: Vec<PathBuf>,
pub min_age: Duration,
pub remove: bool,
pub dry_run: bool,
pub force: bool,
pub one_file_system: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Unproven {
NoStateFile,
Unparsable,
NotFinished,
BadTimestamp,
}
impl Unproven {
#[must_use]
pub const fn code(self) -> &'static str {
match self {
Self::NoStateFile => "no_state_file",
Self::Unparsable => "unparsable",
Self::NotFinished => "not_finished",
Self::BadTimestamp => "bad_timestamp",
}
}
}
impl std::fmt::Display for Unproven {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str(match self {
Self::NoStateFile => "no readable state.json",
Self::Unparsable => "state.json is not valid JSON",
Self::NotFinished => "has not finished — state.json records no lastTerminalAt",
Self::BadTimestamp => "lastTerminalAt is not a timestamp voom recognises",
})
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum JobState {
Unproven(Unproven),
Live {
session_id: String,
},
TooRecent {
age: Duration,
},
Eligible {
age: Duration,
},
}
#[derive(Debug, Clone)]
pub struct Job {
pub path: PathBuf,
pub state: JobState,
pub bytes: Option<u64>,
pub outcome: Option<Outcome>,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Totals {
pub found: usize,
pub removed: usize,
pub refused: usize,
pub kept: usize,
pub bytes: u64,
pub eligible: usize,
pub eligible_bytes: u64,
}
#[derive(Debug)]
pub struct ClaudePruneResult {
pub roots: Vec<PathBuf>,
pub jobs: Vec<Job>,
pub remove: bool,
pub dry_run: bool,
pub elapsed: Duration,
}
impl ClaudePruneResult {
#[must_use]
pub fn totals(&self) -> Totals {
let mut totals = Totals {
found: self.jobs.len(),
..Totals::default()
};
for job in &self.jobs {
if matches!(job.state, JobState::Eligible { .. }) {
totals.eligible += 1;
totals.eligible_bytes += job.bytes.unwrap_or(0);
}
match (&job.state, &job.outcome) {
(JobState::Eligible { .. }, Some(Outcome::Removed | Outcome::Detached | Outcome::WouldRemove)) => {
totals.removed += 1;
totals.bytes += job.bytes.unwrap_or(0);
}
(JobState::Eligible { .. }, Some(Outcome::Refused(_))) => totals.refused += 1,
_ => totals.kept += 1,
}
}
totals
}
#[must_use]
pub fn exit_code(&self) -> i32 {
let failed = self
.jobs
.iter()
.any(|job| matches!(job.outcome, Some(Outcome::Failed(_) | Outcome::PartiallyRemoved { .. })));
if failed {
crate::report::exit::REMOVAL_FAILED
} else {
crate::report::exit::SUCCESS
}
}
}
#[must_use]
pub fn default_root() -> Vec<PathBuf> {
dirs::home_dir().map_or_else(Vec::new, |home| vec![home.join(".claude/jobs")])
}
pub fn prune(options: &ClaudePruneOptions) -> Result<ClaudePruneResult> {
let started = Instant::now();
let mut roots = Vec::new();
let mut candidates = Vec::new();
for root in &options.roots {
let Ok(canonical) = root.canonicalize() else {
continue;
};
candidates.extend(immediate_subdirectories(&canonical));
roots.push(canonical);
}
let guard = Guard::new(&roots, options.one_file_system)?;
let removal = Removal {
dry_run: options.dry_run,
force: options.force,
};
let now = SystemTime::now();
let mut jobs: Vec<Job> = candidates
.into_iter()
.map(|path| {
let state = state_of(&path, options.min_age, now);
let scratch = path.join(SCRATCH_DIR_NAME);
let measured =
(matches!(state, JobState::Eligible { .. }) && scratch.is_dir()).then(|| measure_fully(&scratch).bytes);
let outcome = measured
.filter(|_| options.remove)
.map(|bytes| guard.remove(&scratch, bytes, removal));
let bytes = measured;
Job {
path,
state,
bytes,
outcome,
}
})
.collect();
jobs.sort_by(|left, right| left.path.cmp(&right.path));
Ok(ClaudePruneResult {
roots,
jobs,
remove: options.remove,
dry_run: options.dry_run,
elapsed: started.elapsed(),
})
}
fn immediate_subdirectories(root: &Path) -> Vec<PathBuf> {
let Ok(entries) = std::fs::read_dir(root) else {
return Vec::new();
};
entries
.flatten()
.filter(|entry| entry.file_type().is_ok_and(|file_type| file_type.is_dir()))
.map(|entry| entry.path())
.collect()
}
fn state_of(job_dir: &Path, min_age: Duration, now: SystemTime) -> JobState {
let state = match read_state(job_dir) {
Ok(state) => state,
Err(reason) => return JobState::Unproven(reason),
};
let Some(last_terminal_at) = state.last_terminal_at.as_deref() else {
return JobState::Unproven(Unproven::NotFinished);
};
let Some(last_terminal_at) = parse_utc_timestamp(last_terminal_at) else {
return JobState::Unproven(Unproven::BadTimestamp);
};
if let Some(session_id) = state.session_id.as_deref()
&& is_resumed(session_id)
{
return JobState::Live {
session_id: session_id.to_owned(),
};
}
let age = now.duration_since(last_terminal_at).unwrap_or_default();
if age < min_age {
JobState::TooRecent { age }
} else {
JobState::Eligible { age }
}
}
fn read_state(job_dir: &Path) -> std::result::Result<State, Unproven> {
let contents = crate::io::read_capped_text(&job_dir.join(STATE_FILE_NAME), STATE_FILE_MAX_BYTES)
.ok_or(Unproven::NoStateFile)?;
serde_json::from_str(&contents).map_err(|_| Unproven::Unparsable)
}
fn is_resumed(session_id: &str) -> bool {
let Ok(output) = Command::new("ps").args(["-A", "-o", "command="]).output() else {
return false;
};
String::from_utf8_lossy(&output.stdout)
.lines()
.any(|line| line.contains(session_id))
}
fn parse_utc_timestamp(text: &str) -> Option<SystemTime> {
let text = text.strip_suffix('Z')?;
let (date, time) = text.split_once('T')?;
let mut date_parts = date.split('-');
let year: i64 = date_parts.next()?.parse().ok()?;
let month: u32 = date_parts.next()?.parse().ok()?;
let day: u32 = date_parts.next()?.parse().ok()?;
if date_parts.next().is_some() {
return None;
}
let (hms, fraction) = time.split_once('.').unwrap_or((time, "0"));
let mut time_parts = hms.split(':');
let hour: u64 = time_parts.next()?.parse().ok()?;
let minute: u64 = time_parts.next()?.parse().ok()?;
let second: u64 = time_parts.next()?.parse().ok()?;
if time_parts.next().is_some() {
return None;
}
if hour > 23 || minute > 59 || second > 60 {
return None;
}
let millis: u64 = format!("{fraction:0<3}").get(..3)?.parse().ok()?;
let days = days_from_civil(year, month, day)?;
let time_of_day = hour
.checked_mul(3600)?
.checked_add(minute.checked_mul(60)?)?
.checked_add(second)?;
let seconds = days.checked_mul(86400)?.checked_add(time_of_day.cast_signed())?;
if seconds < 0 {
return None;
}
Some(SystemTime::UNIX_EPOCH + Duration::from_secs(seconds.cast_unsigned()) + Duration::from_millis(millis))
}
fn days_from_civil(year: i64, month: u32, day: u32) -> Option<i64> {
if !(1..=12).contains(&month) || !(1..=31).contains(&day) {
return None;
}
let year = if month <= 2 { year - 1 } else { year };
let era = if year >= 0 { year } else { year - 399 } / 400;
let year_of_era = year - era * 400;
let month_index = i64::from(if month > 2 { month - 3 } else { month + 9 });
let day_of_year = (153 * month_index + 2) / 5 + i64::from(day) - 1;
let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year;
Some(era * 146_097 + day_of_era - 719_468)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::testing::tree;
fn options(root: &Path) -> ClaudePruneOptions {
ClaudePruneOptions {
roots: vec![root.to_path_buf()],
min_age: DEFAULT_MIN_AGE,
remove: true,
dry_run: false,
force: false,
one_file_system: true,
}
}
fn write_state(job_dir: &Path, session_id: &str, last_terminal_at: &str) {
std::fs::write(
job_dir.join("state.json"),
format!(r#"{{"sessionId": "{session_id}", "lastTerminalAt": "{last_terminal_at}"}}"#),
)
.unwrap();
}
#[test]
fn should_convert_a_known_calendar_date() {
assert_eq!(days_from_civil(1970, 1, 1), Some(0));
assert_eq!(days_from_civil(2026, 9, 10), Some(20706));
}
#[test]
fn should_parse_the_exact_shape_claude_code_writes() {
let parsed = parse_utc_timestamp("2026-09-10T05:13:43.668Z").expect("a valid timestamp");
let expected = SystemTime::UNIX_EPOCH
+ Duration::from_secs(20706 * 86400 + 5 * 3600 + 13 * 60 + 43)
+ Duration::from_millis(668);
assert_eq!(parsed, expected);
}
#[test]
fn should_reject_a_shape_it_does_not_recognise() {
assert_eq!(parse_utc_timestamp("2026-09-10 05:13:43"), None, "no `T`, no `Z`");
assert_eq!(parse_utc_timestamp("not a date"), None);
}
#[cfg(unix)]
#[test]
fn should_never_remove_a_job_a_running_process_still_names() {
let fixture = tree(&["jobs/old-but-live/tmp/scratch.bin"]);
let root = fixture.path().join("jobs");
let real_session = std::env::current_exe().unwrap().display().to_string();
write_state(&root.join("old-but-live"), &real_session, "2000-01-01T00:00:00.000Z");
let result = prune(&options(&root)).expect("the root resolves");
let job = &result.jobs[0];
assert!(matches!(&job.state, JobState::Live { .. }), "{:?}", job.state);
assert!(job.outcome.is_none(), "nothing is even attempted against a live job");
assert!(root.join("old-but-live/tmp").exists());
}
#[test]
fn should_keep_a_job_more_recent_than_the_minimum_age() {
let fixture = tree(&["jobs/fresh/tmp/scratch.bin"]);
let root = fixture.path().join("jobs");
let now = humantime_like_now();
write_state(&root.join("fresh"), "session-nobody-is-running", &now);
let result = prune(&options(&root)).expect("the root resolves");
assert!(matches!(&result.jobs[0].state, JobState::TooRecent { .. }));
assert!(root.join("fresh/tmp").exists());
}
#[test]
fn should_remove_an_old_unresumed_jobs_scratch_when_remove_is_given() {
let fixture = tree(&["jobs/ancient/tmp/scratch.bin", "jobs/ancient/timeline.jsonl"]);
let root = fixture.path().join("jobs");
write_state(
&root.join("ancient"),
"session-nobody-is-running",
"2000-01-01T00:00:00.000Z",
);
let result = prune(&options(&root)).expect("the root resolves");
let job = &result.jobs[0];
assert!(matches!(&job.state, JobState::Eligible { .. }));
assert_eq!(job.outcome, Some(Outcome::Removed));
assert!(!root.join("ancient/tmp").exists(), "the scratch is gone");
assert!(
root.join("ancient/timeline.jsonl").exists(),
"the job's own record survives"
);
}
#[test]
fn should_report_only_without_the_remove_flag() {
let fixture = tree(&["jobs/ancient/tmp/scratch.bin"]);
let root = fixture.path().join("jobs");
write_state(
&root.join("ancient"),
"session-nobody-is-running",
"2000-01-01T00:00:00.000Z",
);
let mut report_only = options(&root);
report_only.remove = false;
let result = prune(&report_only).expect("the root resolves");
let job = &result.jobs[0];
assert!(matches!(&job.state, JobState::Eligible { .. }));
assert!(job.outcome.is_none(), "nothing is attempted without --remove");
assert!(root.join("ancient/tmp").exists());
}
#[test]
fn should_leave_an_unparsable_job_unproven() {
let fixture = tree(&["jobs/broken/state.json"]);
let root = fixture.path().join("jobs");
std::fs::write(root.join("broken/state.json"), "not json").unwrap();
let result = prune(&options(&root)).expect("the root resolves");
assert_eq!(result.jobs[0].state, JobState::Unproven(Unproven::Unparsable));
}
#[test]
fn should_say_a_job_without_a_state_file_has_none() {
let fixture = tree(&["jobs/bare/tmp/scratch.bin"]);
let root = fixture.path().join("jobs");
let result = prune(&options(&root)).expect("the root resolves");
assert_eq!(result.jobs[0].state, JobState::Unproven(Unproven::NoStateFile));
}
#[test]
fn should_say_a_job_that_never_finished_has_not_finished() {
let fixture = tree(&["jobs/blocked/tmp/scratch.bin"]);
let root = fixture.path().join("jobs");
std::fs::write(
root.join("blocked/state.json"),
r#"{"state": "blocked", "sessionId": "s", "needs": "confirm?"}"#,
)
.unwrap();
let result = prune(&options(&root)).expect("the root resolves");
assert_eq!(result.jobs[0].state, JobState::Unproven(Unproven::NotFinished));
assert!(root.join("blocked/tmp").exists());
}
#[test]
fn should_say_a_timestamp_it_cannot_read_is_unreadable() {
let fixture = tree(&["jobs/odd/tmp/scratch.bin"]);
let root = fixture.path().join("jobs");
write_state(&root.join("odd"), "s", "last Tuesday");
let result = prune(&options(&root)).expect("the root resolves");
assert_eq!(result.jobs[0].state, JobState::Unproven(Unproven::BadTimestamp));
}
#[test]
fn should_size_an_eligible_jobs_scratch_without_remove() {
let fixture = tree(&["jobs/ancient/tmp/scratch.bin"]);
let root = fixture.path().join("jobs");
std::fs::write(root.join("ancient/tmp/scratch.bin"), vec![1u8; 100_000]).unwrap();
write_state(
&root.join("ancient"),
"session-nobody-is-running",
"2000-01-01T00:00:00.000Z",
);
let mut report_only = options(&root);
report_only.remove = false;
let result = prune(&report_only).expect("the root resolves");
assert!(
result.jobs[0].bytes.is_some_and(|bytes| bytes >= 100_000),
"{:?}",
result.jobs[0].bytes
);
assert!(result.jobs[0].outcome.is_none());
assert!(root.join("ancient/tmp").exists());
}
#[test]
fn should_not_size_a_job_it_will_not_touch() {
let fixture = tree(&["jobs/fresh/tmp/scratch.bin"]);
let root = fixture.path().join("jobs");
write_state(&root.join("fresh"), "session-nobody-is-running", &humantime_like_now());
let result = prune(&options(&root)).expect("the root resolves");
assert_eq!(result.jobs[0].bytes, None);
}
fn humantime_like_now() -> String {
let now = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap();
let days = now.as_secs() / 86400 + 3650;
let year = 1970 + days / 365;
format!("{year}-06-15T00:00:00.000Z")
}
}