use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum RemovalReason {
Merged,
MergedInto(String),
MergedThrough(String),
SessionMerged(String),
Verdict(String),
NoChanges,
ResearchReport,
ResearchReportInWorktree,
ResearchEndedWithoutReport(String),
ResearchStoppedWithoutSummary(u64),
OlderThan(u64),
}
impl std::fmt::Display for RemovalReason {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Merged => write!(f, "merged"),
Self::MergedInto(base) => write!(f, "merged into {base}"),
Self::MergedThrough(child) => write!(f, "merged through {child}"),
Self::SessionMerged(branch) => write!(f, "{branch} merged"),
Self::Verdict(v) => {
if v.is_empty() {
write!(f, "verdict")
} else {
write!(f, "verdict {v}")
}
}
Self::NoChanges => write!(f, "no changes"),
Self::ResearchReport => write!(f, "research report"),
Self::ResearchReportInWorktree => {
write!(f, "research report (copied out on removal)")
}
Self::ResearchEndedWithoutReport(outcome) => {
write!(f, "research run ended without a report ({outcome})")
}
Self::ResearchStoppedWithoutSummary(d) => {
write!(
f,
"research run stopped without a summary, started more than {d} days ago"
)
}
Self::OlderThan(d) => write!(f, "finished over {d} days ago"),
}
}
}
#[derive(Debug, PartialEq, Eq)]
pub enum KeptReason {
UncommittedChanges,
Running,
NoVerdict,
NotMergedYet,
NoReport,
UnreadableSummary,
InUse,
CannotCheckInUse(String),
UsedRecently(u64),
HoldsRuns(String),
UnreadableStartRecord(String),
UnreadableVerdict(String),
UnreadableChildState(String),
Custom(String),
}
impl std::fmt::Display for KeptReason {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::UncommittedChanges => write!(f, "uncommitted changes"),
Self::Running => write!(f, "running"),
Self::NoVerdict => write!(f, "no verdict"),
Self::NotMergedYet => write!(f, "not merged yet"),
Self::NoReport => write!(f, "no report"),
Self::UnreadableSummary => write!(f, "unreadable summary"),
Self::InUse => write!(f, "in use by a running process"),
Self::CannotCheckInUse(err) => {
write!(f, "cannot tell whether it is in use: {err}")
}
Self::UsedRecently(d) => write!(f, "used in the last {d} days"),
Self::HoldsRuns(path) => write!(f, "holds runs: review them from {path}"),
Self::UnreadableStartRecord(reason) => write!(f, "unreadable start record: {reason}"),
Self::UnreadableVerdict(reason) => write!(f, "unreadable verdict: {reason}"),
Self::UnreadableChildState(reason) => write!(f, "unreadable child state: {reason}"),
Self::Custom(s) => write!(f, "{s}"),
}
}
}
fn read_verdict_file(path: &Path) -> Result<Option<String>, String> {
let content = match std::fs::read_to_string(path) {
Ok(content) => content,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(err) => return Err(format!("{}: {err}", path.display())),
};
let value: serde_json::Value =
serde_json::from_str(&content).map_err(|err| format!("{}: {err}", path.display()))?;
let obj = value
.as_object()
.ok_or_else(|| format!("{}: not a JSON object", path.display()))?;
match obj.get("verdict") {
Some(serde_json::Value::String(s)) if !s.is_empty() => Ok(Some(s.clone())),
Some(serde_json::Value::String(_)) => {
Err(format!("{}: empty verdict field", path.display()))
}
Some(_) => Err(format!("{}: verdict field is not a string", path.display())),
None => Err(format!("{}: missing verdict field", path.display())),
}
}
fn read_child_summary_verified(path: &Path) -> Result<bool, String> {
let content = match std::fs::read_to_string(path) {
Ok(content) => content,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(false),
Err(err) => return Err(format!("{}: {err}", path.display())),
};
let value: serde_json::Value =
serde_json::from_str(&content).map_err(|err| format!("{}: {err}", path.display()))?;
let obj = value
.as_object()
.ok_or_else(|| format!("{}: not a JSON object", path.display()))?;
match obj.get("outcome") {
Some(serde_json::Value::String(s)) => Ok(s == "verified"),
Some(_) => Err(format!("{}: outcome field is not a string", path.display())),
None => Err(format!("{}: missing outcome field", path.display())),
}
}
pub fn dir_size(path: &Path) -> u64 {
let mut total = 0;
let Ok(meta) = std::fs::symlink_metadata(path) else {
return 0;
};
if meta.file_type().is_symlink() {
return 0;
}
if meta.is_file() {
return meta.len();
}
if meta.is_dir() {
let Ok(entries) = std::fs::read_dir(path) else {
return 0;
};
for entry in entries.flatten() {
let Ok(ft) = entry.file_type() else {
continue;
};
if ft.is_symlink() {
continue;
} else if ft.is_dir() {
total += dir_size(&entry.path());
} else if ft.is_file() {
if let Ok(m) = entry.metadata() {
total += m.len();
}
}
}
}
total
}
pub fn format_size(bytes: u64) -> String {
const KB: f64 = 1024.0;
const MB: f64 = 1024.0 * 1024.0;
const GB: f64 = 1024.0 * 1024.0 * 1024.0;
let b = bytes as f64;
let (val, unit) = if b >= GB {
(b / GB, "GB")
} else if b >= MB {
(b / MB, "MB")
} else if b >= KB {
(b / KB, "KB")
} else {
return format!("{bytes} B");
};
let s = if val >= 100.0 {
format!("{val:.0}")
} else {
let formatted = format!("{val:.1}");
formatted
.strip_suffix(".0")
.unwrap_or(&formatted)
.to_string()
};
format!("{s} {unit}")
}
pub fn is_pid_alive(pid: i64) -> bool {
if pid <= 0 {
return false;
}
let ret = unsafe { libc::kill(pid as libc::pid_t, 0) };
if ret == 0 {
true
} else {
std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
}
}
pub fn find_repo_root() -> Result<PathBuf, String> {
let out = std::process::Command::new("git")
.args([
"rev-parse",
"--path-format=absolute",
"--show-toplevel",
"--git-dir",
"--git-common-dir",
])
.output()
.map_err(|e| format!("git not found: {e}"))?;
if !out.status.success() {
return Err("not a git repository".to_string());
}
let text = String::from_utf8_lossy(&out.stdout);
let mut lines = text.lines();
let (Some(toplevel), Some(git_dir), Some(common_dir)) =
(lines.next(), lines.next(), lines.next())
else {
return Err("not a git repository".to_string());
};
let root = PathBuf::from(toplevel.trim());
let git_dir = git_dir.trim();
let common_dir = common_dir.trim();
if git_dir != common_dir {
let common = PathBuf::from(common_dir);
let main = (|| -> Option<PathBuf> {
if common.file_name()? != ".git" {
return None;
}
let parent = common.parent()?;
let parent_canon = parent.canonicalize().ok()?;
let root_canon = root.canonicalize().ok()?;
if parent_canon == root_canon {
return None;
}
Some(parent.to_path_buf())
})();
main.ok_or_else(|| {
format!(
"cannot find main checkout for linked worktree {}",
root.display()
)
})
} else {
Ok(root)
}
}
pub fn is_research(root: &Path, id: &str) -> bool {
let start_path = root.join(".wt").join(format!("{id}.start.json"));
if let Ok(s) = std::fs::read_to_string(&start_path) {
if let Ok(val) = serde_json::from_str::<serde_json::Value>(&s) {
return val
.get("research")
.and_then(|r| r.as_bool())
.unwrap_or(false);
}
}
false
}
pub fn has_uncommitted_changes(wt_path: &Path) -> bool {
let out = std::process::Command::new("git")
.args([
"-C",
wt_path.to_str().unwrap_or(""),
"status",
"--porcelain",
])
.output();
match out {
Ok(o) if o.status.success() => {
!o.stdout.is_empty() && !String::from_utf8_lossy(&o.stdout).trim().is_empty()
}
_ => true,
}
}
fn git_tree_sha(root: &Path, ref_name: &str) -> Option<String> {
let out = std::process::Command::new("git")
.args(["rev-parse", &format!("{ref_name}^{{tree}}")])
.current_dir(root)
.output()
.ok()?;
if out.status.success() {
Some(String::from_utf8_lossy(&out.stdout).trim().to_string())
} else {
None
}
}
fn is_cherry_merged_into_target(root: &Path, commit_sha: &str, target: &str) -> bool {
let cherry_out = std::process::Command::new("git")
.args(["cherry", target, commit_sha])
.current_dir(root)
.output();
if let Ok(o) = cherry_out {
if o.status.success() {
let s = String::from_utf8_lossy(&o.stdout);
let lines: Vec<&str> = s
.lines()
.map(|l| l.trim())
.filter(|l| !l.is_empty())
.collect();
if !lines.is_empty() && lines.iter().all(|l| l.starts_with('-')) {
return true;
}
}
}
false
}
fn is_merge_tree_merged_into_target(
root: &Path,
commit_sha: &str,
target: &str,
target_tree: Option<&str>,
) -> bool {
let target_tree_sha = match target_tree {
Some(t) => Some(t.to_string()),
None => git_tree_sha(root, target),
};
if let Some(target_tree_sha) = target_tree_sha {
let merge_tree_out = std::process::Command::new("git")
.args(["merge-tree", "--write-tree", target, commit_sha])
.current_dir(root)
.output();
if let Ok(mt_o) = merge_tree_out {
if mt_o.status.success() {
let mt_stdout = String::from_utf8_lossy(&mt_o.stdout);
if let Some(first_line) = mt_stdout.lines().next() {
if first_line.trim() == target_tree_sha {
return true;
}
}
}
}
}
false
}
fn parse_started_at(val: &serde_json::Value) -> Option<u64> {
let s = val.get("started_at")?;
if let Some(n) = s.as_u64() {
Some(n)
} else if let Some(n) = s.as_i64() {
if n >= 0 {
Some(n as u64)
} else {
None
}
} else if let Some(f) = s.as_f64() {
if f >= 0.0 {
Some(f as u64)
} else {
None
}
} else if let Some(st) = s.as_str() {
st.parse::<u64>().ok()
} else {
None
}
}
fn check_history_merged_with_base(
root: &Path,
tip_sha: &str,
target: &str,
merge_base: &str,
started_at: Option<&serde_json::Value>,
) -> bool {
let diff_out = std::process::Command::new("git")
.args(["diff", "--name-only", merge_base, tip_sha])
.current_dir(root)
.output();
let Ok(diff_o) = diff_out else {
return false;
};
if !diff_o.status.success() {
return false;
}
let files: Vec<String> = String::from_utf8_lossy(&diff_o.stdout)
.lines()
.map(|l| l.trim().to_string())
.filter(|l| !l.is_empty())
.collect();
if files.is_empty() {
return false;
}
let since_arg = started_at
.and_then(|v| {
if let Some(n) = v.as_i64() {
if n >= 100_000_000 {
Some(format!("--since={n}"))
} else {
Some("--since=1970-01-01T00:00:00Z".to_string())
}
} else if let Some(n) = v.as_u64() {
if n >= 100_000_000 {
Some(format!("--since={n}"))
} else {
Some("--since=1970-01-01T00:00:00Z".to_string())
}
} else {
v.as_str().map(|s| format!("--since={s}"))
}
})
.unwrap_or_else(|| "--since=1970-01-01T00:00:00Z".to_string());
let mut cmd = std::process::Command::new("git");
cmd.args([
"rev-list",
"--first-parent",
&since_arg,
"-n",
"20",
target,
"--",
]);
for f in &files {
cmd.arg(f);
}
cmd.current_dir(root);
let Ok(rev_o) = cmd.output() else {
return false;
};
if !rev_o.status.success() {
return false;
}
let commits: Vec<String> = String::from_utf8_lossy(&rev_o.stdout)
.lines()
.map(|l| l.trim().to_string())
.filter(|l| !l.is_empty())
.collect();
for c in commits {
let mt_out = std::process::Command::new("git")
.args(["merge-tree", "--write-tree", &c, tip_sha])
.current_dir(root)
.output();
let Ok(mt_o) = mt_out else {
continue;
};
if !mt_o.status.success() {
continue;
}
let mt_stdout = String::from_utf8_lossy(&mt_o.stdout);
let Some(first_line) = mt_stdout.lines().next() else {
continue;
};
let mt_tree = first_line.trim();
if let Some(c_tree) = git_tree_sha(root, &c) {
if mt_tree == c_tree {
return true;
}
}
}
false
}
pub fn read_start_record(root: &Path, id: &str) -> Result<Option<serde_json::Value>, String> {
let path = root.join(".wt").join(format!("{id}.start.json"));
let content = match std::fs::read_to_string(&path) {
Ok(content) => content,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(err) => return Err(format!("{}: {err}", path.display())),
};
match serde_json::from_str::<serde_json::Value>(&content) {
Ok(value) if value.is_object() => Ok(Some(value)),
Ok(_) => Err(format!("{}: not a JSON object", path.display())),
Err(err) => Err(format!("{}: {err}", path.display())),
}
}
#[derive(Debug, Clone)]
pub struct RefEntry {
pub objectname: String,
pub symref: Option<String>,
pub tree: Option<String>,
}
fn load_refs(root: &Path) -> (HashMap<String, RefEntry>, bool) {
let mut refs = HashMap::new();
let out = std::process::Command::new("git")
.args([
"for-each-ref",
"--format=%(refname)%09%(objectname)%09%(symref)%09%(tree)",
"refs/heads",
"refs/remotes/origin",
])
.current_dir(root)
.output();
let Ok(o) = out else {
return (refs, false);
};
if !o.status.success() {
return (refs, false);
}
for line in String::from_utf8_lossy(&o.stdout).lines() {
let mut cols = line.split('\t');
let Some(refname) = cols.next() else {
continue;
};
let Some(objectname) = cols.next() else {
continue;
};
let symref = cols.next().unwrap_or("");
let tree = cols.next().unwrap_or("");
if refname.is_empty() || objectname.is_empty() {
continue;
}
refs.insert(
refname.to_string(),
RefEntry {
objectname: objectname.to_string(),
symref: if symref.is_empty() {
None
} else {
Some(symref.to_string())
},
tree: if tree.is_empty() {
None
} else {
Some(tree.to_string())
},
},
);
}
(refs, true)
}
fn lookup_ref<'b>(
refs: &'b HashMap<String, RefEntry>,
name: &str,
) -> Option<(&'b str, &'b RefEntry)> {
if name.starts_with("refs/") {
return refs.get_key_value(name).map(|(k, v)| (k.as_str(), v));
}
let head_key = format!("refs/heads/{name}");
if let Some((k, v)) = refs.get_key_value(&head_key) {
return Some((k.as_str(), v));
}
let remote_key = format!("refs/remotes/{name}");
if let Some((k, v)) = refs.get_key_value(&remote_key) {
return Some((k.as_str(), v));
}
None
}
fn find_default_branch_from_refs(refs: &HashMap<String, RefEntry>) -> String {
if let Some(head_entry) = refs.get("refs/remotes/origin/HEAD") {
if let Some(ref symref) = head_entry.symref {
let target = symref.strip_prefix("refs/remotes/").unwrap_or(symref);
let branch_name = target.strip_prefix("origin/").unwrap_or(target);
if refs.contains_key(&format!("refs/heads/{branch_name}")) {
return branch_name.to_string();
}
if refs.contains_key(symref) || refs.contains_key(&format!("refs/remotes/{target}")) {
return target.to_string();
}
return branch_name.to_string();
}
}
if refs.contains_key("refs/heads/main") {
return "main".to_string();
}
if refs.contains_key("refs/heads/master") {
return "master".to_string();
}
"main".to_string()
}
pub struct CleanContext<'a> {
pub root: &'a Path,
pub start_files: HashMap<String, serde_json::Value>,
pub all_run_ids: Vec<String>,
pub refs: HashMap<String, RefEntry>,
pub refs_loaded: bool,
pub wip_branch_tips: HashMap<String, String>,
pub default_branch: String,
pub origin_default: Option<String>,
pub default_tree: Option<String>,
pub origin_default_tree: Option<String>,
pub wip_contains_cache: HashMap<String, Vec<String>>,
pub merged_cache: HashMap<String, Option<RemovalReason>>,
pub branch_contains_calls: usize,
pub cherry_pick_set: Option<HashSet<String>>,
pub rev_list_cache: HashMap<String, Vec<String>>,
pub ancestor_cache: HashMap<(String, String), bool>,
pub contains_target: HashSet<(String, String)>,
pub merge_base_cache: HashMap<(String, String), Option<String>>,
pub cherry_cache: HashMap<(String, String), bool>,
pub merge_tree_cache: HashMap<(String, String), bool>,
}
impl<'a> CleanContext<'a> {
pub fn new(root: &'a Path) -> Self {
let mut start_files = HashMap::new();
let mut all_run_ids = Vec::new();
let wt_dir = root.join(".wt");
if let Ok(entries) = std::fs::read_dir(&wt_dir) {
for entry in entries.flatten() {
let name = entry.file_name().to_string_lossy().to_string();
if let Some(id) = name.strip_suffix(".start.json") {
all_run_ids.push(id.to_string());
if let Ok(content) = std::fs::read_to_string(entry.path()) {
if let Ok(val) = serde_json::from_str::<serde_json::Value>(&content) {
start_files.insert(id.to_string(), val);
}
}
}
}
}
all_run_ids.sort();
let (refs, refs_loaded) = load_refs(root);
let mut wip_branch_tips = HashMap::new();
for (refname, entry) in &refs {
if let Some(short) = refname.strip_prefix("refs/heads/") {
if short.starts_with("wip/") {
wip_branch_tips.insert(short.to_string(), entry.objectname.clone());
}
}
}
let default_branch = if refs_loaded {
find_default_branch_from_refs(&refs)
} else {
find_default_branch(root)
};
let name = default_branch
.strip_prefix("origin/")
.unwrap_or(&default_branch);
let remote = format!("origin/{name}");
let origin_default = if remote != default_branch
&& if refs_loaded {
refs.contains_key(&format!("refs/remotes/{remote}"))
} else {
git_ok(root, &["rev-parse", "--verify", "--quiet", &remote])
} {
Some(remote)
} else {
None
};
let default_tree = if refs_loaded {
lookup_ref(&refs, &default_branch).and_then(|(_, e)| e.tree.clone())
} else {
git_tree_sha(root, &default_branch)
};
let origin_default_tree = origin_default.as_deref().and_then(|r| {
if refs_loaded {
lookup_ref(&refs, r).and_then(|(_, e)| e.tree.clone())
} else {
git_tree_sha(root, r)
}
});
let mut ancestor_cache = HashMap::new();
let mut contains_target = HashSet::new();
if refs_loaded {
let mut default_targets: Vec<String> = Vec::new();
if lookup_ref(&refs, &default_branch).is_some() {
default_targets.push(default_branch.clone());
}
if let Some(ref origin_def) = origin_default {
if lookup_ref(&refs, origin_def).is_some() {
default_targets.push(origin_def.clone());
}
}
let mut seen_target_shas = HashSet::new();
for target in &default_targets {
let Some((_, target_entry)) = lookup_ref(&refs, target) else {
continue;
};
let target_sha = target_entry.objectname.clone();
if !seen_target_shas.insert(target_sha.clone()) {
continue;
}
let merged_out = std::process::Command::new("git")
.args([
"for-each-ref",
&format!("--merged={target}"),
"--format=%(refname:short)",
"refs/heads",
])
.current_dir(root)
.output();
if let Ok(o) = merged_out {
if o.status.success() {
let merged_set: HashSet<String> = String::from_utf8_lossy(&o.stdout)
.lines()
.map(|l| l.trim().to_string())
.filter(|l| !l.is_empty())
.collect();
for (refname, entry) in &refs {
if let Some(short) = refname.strip_prefix("refs/heads/") {
ancestor_cache.insert(
(entry.objectname.clone(), target_sha.clone()),
merged_set.contains(short),
);
}
}
}
}
let contains_out = std::process::Command::new("git")
.args([
"for-each-ref",
&format!("--contains={target}"),
"--format=%(refname:short)",
"refs/heads",
])
.current_dir(root)
.output();
if let Ok(o) = contains_out {
if o.status.success() {
for line in String::from_utf8_lossy(&o.stdout).lines() {
let short = line.trim();
if short.is_empty() {
continue;
}
if let Some(entry) = refs.get(&format!("refs/heads/{short}")) {
contains_target
.insert((entry.objectname.clone(), target_sha.clone()));
}
}
}
}
}
}
Self {
root,
start_files,
all_run_ids,
refs,
refs_loaded,
wip_branch_tips,
default_branch,
origin_default,
default_tree,
origin_default_tree,
wip_contains_cache: HashMap::new(),
merged_cache: HashMap::new(),
branch_contains_calls: 0,
cherry_pick_set: None,
rev_list_cache: HashMap::new(),
ancestor_cache,
contains_target,
merge_base_cache: HashMap::new(),
cherry_cache: HashMap::new(),
merge_tree_cache: HashMap::new(),
}
}
pub fn remove_branch(&mut self, branch_name: &str) {
self.wip_branch_tips.remove(branch_name);
self.refs.remove(&format!("refs/heads/{branch_name}"));
}
pub fn tree_sha(&self, ref_name: &str) -> Option<String> {
if let Some((_, entry)) = lookup_ref(&self.refs, ref_name) {
if entry.tree.is_some() {
return entry.tree.clone();
}
}
if self.refs_loaded
&& (ref_name.starts_with("refs/heads/") || ref_name.starts_with("refs/remotes/origin/"))
{
return None;
}
git_tree_sha(self.root, ref_name)
}
fn ref_exists(&self, refname: &str) -> bool {
if lookup_ref(&self.refs, refname).is_some() {
return true;
}
if self.refs_loaded
&& (refname.starts_with("refs/heads/") || refname.starts_with("refs/remotes/origin/"))
{
return false;
}
git_ok(self.root, &["rev-parse", "--verify", "--quiet", refname])
}
fn resolve_base_targets(&self, base: &str) -> Option<(String, Vec<String>)> {
resolve_base_targets_with(base, |cand| self.ref_exists(cand))
}
fn target_key(&self, target: &str) -> String {
lookup_ref(&self.refs, target)
.map(|(_, e)| e.objectname.clone())
.unwrap_or_else(|| target.to_string())
}
fn target_is_ancestor_of(&self, target: &str, commit_sha: &str) -> bool {
let key = (commit_sha.to_string(), self.target_key(target));
self.contains_target.contains(&key)
}
fn merge_base(&mut self, target: &str, commit_sha: &str) -> Option<String> {
let key = (self.target_key(target), commit_sha.to_string());
if let Some(cached) = self.merge_base_cache.get(&key) {
return cached.clone();
}
let mb_out = std::process::Command::new("git")
.args(["merge-base", target, commit_sha])
.current_dir(self.root)
.output();
let mb = match mb_out {
Ok(o) if o.status.success() => {
let s = String::from_utf8_lossy(&o.stdout).trim().to_string();
if s.is_empty() {
None
} else {
Some(s)
}
}
_ => None,
};
self.merge_base_cache.insert(key, mb.clone());
mb
}
fn compute_cherry_pick_set(&self) -> HashSet<String> {
let unremoved_ids = find_blyte_worktrees(self.root);
let candidate_ids: &[String] = if unremoved_ids.is_empty() {
&self.all_run_ids
} else {
&unremoved_ids
};
let mut min_started_at: Option<u64> = None;
let mut all_valid = true;
for id in candidate_ids {
let start_val = self.start_files.get(id);
let parsed = start_val.and_then(parse_started_at);
match parsed {
Some(ts) => {
min_started_at = Some(min_started_at.map_or(ts, |m| m.min(ts)));
}
None => {
all_valid = false;
}
}
}
let since_arg = if let (true, Some(min_ts)) = (all_valid, min_started_at) {
if min_ts >= 86_400 + 100_000_000 {
format!("--since={}", min_ts - 86_400)
} else {
"--since=1970-01-01T00:00:00Z".to_string()
}
} else {
"--since=1970-01-01T00:00:00Z".to_string()
};
let mut targets = Vec::new();
let mut seen = HashSet::new();
if lookup_ref(&self.refs, &self.default_branch).is_some()
|| (!self.refs_loaded
&& git_ok(
self.root,
&["rev-parse", "--verify", "--quiet", &self.default_branch],
))
{
let key = lookup_ref(&self.refs, &self.default_branch)
.map(|(k, _)| k.to_string())
.unwrap_or_else(|| self.default_branch.clone());
if seen.insert(key) {
targets.push(self.default_branch.clone());
}
}
if let Some(ref origin_def) = self.origin_default {
if lookup_ref(&self.refs, origin_def).is_some()
|| (!self.refs_loaded
&& git_ok(self.root, &["rev-parse", "--verify", "--quiet", origin_def]))
{
let key = lookup_ref(&self.refs, origin_def)
.map(|(k, _)| k.to_string())
.unwrap_or_else(|| origin_def.clone());
if seen.insert(key) {
targets.push(origin_def.clone());
}
}
}
for id in &self.all_run_ids {
if let Some(base_str) = self
.start_files
.get(id)
.and_then(|s| s.get("base"))
.and_then(|b| b.as_str())
{
if let Some((_, base_targets)) = self.resolve_base_targets(base_str) {
for bt in base_targets {
let key = lookup_ref(&self.refs, &bt)
.map(|(k, _)| k.to_string())
.unwrap_or_else(|| bt.clone());
if seen.insert(key) {
targets.push(bt);
}
}
}
}
}
if targets.is_empty() {
return HashSet::new();
}
let mut cmd = std::process::Command::new("git");
cmd.args(["log", "--format=%B", &since_arg]);
for t in &targets {
cmd.arg(t);
}
cmd.current_dir(self.root);
let mut set = HashSet::new();
if let Ok(o) = cmd.output() {
if o.status.success() {
let text = String::from_utf8_lossy(&o.stdout);
for line in text.lines() {
let trimmed = line.trim();
if let Some(rest) = trimmed.strip_prefix("(cherry picked from commit ") {
if let Some(sha) = rest.strip_suffix(')') {
let sha = sha.trim();
if is_commit_id(sha) {
set.insert(sha.to_lowercase());
}
}
}
}
}
}
set
}
pub fn get_cherry_pick_set(&mut self) -> &HashSet<String> {
if self.cherry_pick_set.is_none() {
let set = self.compute_cherry_pick_set();
self.cherry_pick_set = Some(set);
}
self.cherry_pick_set.as_ref().unwrap()
}
fn is_ancestor_of_target(&mut self, commit_sha: &str, target: &str) -> bool {
let key = (commit_sha.to_string(), self.target_key(target));
if let Some(&cached) = self.ancestor_cache.get(&key) {
return cached;
}
let is_anc = std::process::Command::new("git")
.args(["merge-base", "--is-ancestor", commit_sha, target])
.current_dir(self.root)
.output()
.map(|c| c.status.success())
.unwrap_or(false);
self.ancestor_cache.insert(key, is_anc);
is_anc
}
fn is_ancestor_of_default(&mut self, commit_sha: &str) -> bool {
let def = self.default_branch.clone();
if self.is_ancestor_of_target(commit_sha, &def) {
return true;
}
if let Some(origin_def) = self.origin_default.clone() {
if self.is_ancestor_of_target(commit_sha, &origin_def) {
return true;
}
}
false
}
fn get_run_commits_against_default(&mut self, tip_sha: &str) -> Vec<String> {
if let Some(cached) = self.rev_list_cache.get(tip_sha) {
return cached.clone();
}
let out = std::process::Command::new("git")
.args(["rev-list", &format!("{}..{}", self.default_branch, tip_sha)])
.current_dir(self.root)
.output();
let commits: Vec<String> = match out {
Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout)
.lines()
.map(|l| l.trim().to_lowercase())
.filter(|l| !l.is_empty())
.collect(),
_ => Vec::new(),
};
self.rev_list_cache
.insert(tip_sha.to_string(), commits.clone());
commits
}
fn is_in_cherry_pick_record(&mut self, tip_sha: &str) -> bool {
if self.get_cherry_pick_set().is_empty() {
return false;
}
let commits = self.get_run_commits_against_default(tip_sha);
if commits.is_empty() {
return false;
}
let cherry_set = self.get_cherry_pick_set();
commits.iter().all(|c| cherry_set.contains(c))
}
pub fn get_branch_tip(&self, branch_name: &str) -> Option<String> {
if let Some(sha) = self.wip_branch_tips.get(branch_name) {
return Some(sha.clone());
}
if let Some(entry) = self.refs.get(&format!("refs/heads/{branch_name}")) {
return Some(entry.objectname.clone());
}
if self.refs_loaded {
return None;
}
get_branch_tip(self.root, branch_name)
}
pub fn is_research_run(&self, id: &str) -> bool {
self.start_files
.get(id)
.and_then(|v| v.get("research"))
.and_then(|r| r.as_bool())
.unwrap_or_else(|| is_research(self.root, id))
}
pub fn get_wip_branches_containing(&mut self, tip_sha: &str) -> Vec<String> {
if let Some(cached) = self.wip_contains_cache.get(tip_sha) {
return cached.clone();
}
self.branch_contains_calls += 1;
let out = std::process::Command::new("git")
.args([
"branch",
"--list",
"--format=%(refname:short)",
"wip/*",
"--contains",
tip_sha,
])
.current_dir(self.root)
.output();
let mut branches = Vec::new();
if let Ok(o) = out {
if o.status.success() {
for line in String::from_utf8_lossy(&o.stdout).lines() {
let trimmed = line.trim().trim_start_matches(['*', '+', ' ']).trim();
if !trimmed.is_empty() {
branches.push(trimmed.to_string());
}
}
}
}
self.wip_contains_cache
.insert(tip_sha.to_string(), branches.clone());
branches
}
pub fn get_children_of(&mut self, id: &str, tip_sha: &str) -> Vec<String> {
let mut children = Vec::new();
let mut seen = HashSet::new();
for (candidate_id, start_val) in &self.start_files {
if candidate_id == id {
continue;
}
if let Some(base_str) = start_val.get("base").and_then(|v| v.as_str()) {
let base_str = base_str.trim().trim_end_matches('/');
let target1 = format!("wip/{id}");
let target2 = format!("refs/heads/wip/{id}");
if (base_str == target1 || base_str == target2) && seen.insert(candidate_id.clone())
{
children.push(candidate_id.clone());
}
}
}
let has_other_without_base = self.start_files.iter().any(|(candidate_id, val)| {
candidate_id != id && val.get("base").is_none_or(|b| b.is_null())
});
if !tip_sha.is_empty() && has_other_without_base {
let tip_sha_owned = tip_sha.to_string();
let containing_branches = self.get_wip_branches_containing(&tip_sha_owned);
for b in containing_branches {
let clean_b = b.strip_prefix("refs/heads/").unwrap_or(&b);
if let Some(candidate_id) = clean_b.strip_prefix("wip/") {
if candidate_id == id {
continue;
}
if !self.start_files.contains_key(candidate_id) {
continue;
}
let has_base = self
.start_files
.get(candidate_id)
.and_then(|val| val.get("base"))
.is_some_and(|b| !b.is_null());
if !has_base && seen.insert(candidate_id.to_string()) {
children.push(candidate_id.to_string());
}
}
}
}
children.sort();
children
}
pub fn is_child_run_merged(
&mut self,
child: &str,
visited: &mut HashSet<String>,
) -> Result<bool, String> {
if self.is_research_run(child) {
return Ok(false);
}
let branch_name = format!("wip/{child}");
let tip = self.get_branch_tip(&branch_name);
if tip.is_none() {
let verdict_path = self.root.join(".wt").join(format!("{child}.verdict.json"));
let (has_accepted_verdict, is_redone) = match read_verdict_file(&verdict_path)? {
Some(v) => (v == "accepted" || v == "fixed", v == "redone"),
None => (false, false),
};
if is_redone {
return Ok(false);
}
let summary_path = self.root.join(".wt").join(format!("{child}.json"));
let is_verified = read_child_summary_verified(&summary_path)?;
let wt_gone = !self.root.join(".wt").join(child).is_dir();
return Ok(has_accepted_verdict || (is_verified && wt_gone));
}
Ok(self.check_run_merged_internal(child, visited)?.is_some())
}
pub fn check_run_merged(&mut self, id: &str) -> Result<Option<RemovalReason>, String> {
let mut visited = HashSet::new();
self.check_run_merged_internal(id, &mut visited)
}
fn check_run_merged_internal(
&mut self,
id: &str,
visited: &mut HashSet<String>,
) -> Result<Option<RemovalReason>, String> {
if visited.contains(id) {
return Ok(None);
}
if let Some(cached) = self.merged_cache.get(id) {
return Ok(cached.clone());
}
visited.insert(id.to_string());
let branch_name = format!("wip/{id}");
let tip_sha = self.get_branch_tip(&branch_name);
let result = self.decide_run_merged(id, tip_sha.as_deref(), visited);
visited.remove(id);
if let Ok(ref val) = result {
self.merged_cache.insert(id.to_string(), val.clone());
}
result
}
fn check_history_merged(
&mut self,
tip_sha: &str,
target: &str,
started_at: Option<&serde_json::Value>,
) -> bool {
if self.target_is_ancestor_of(target, tip_sha) {
return false;
}
let Some(merge_base) = self.merge_base(target, tip_sha) else {
return false;
};
check_history_merged_with_base(self.root, tip_sha, target, &merge_base, started_at)
}
fn is_squash_merged_into_target(&mut self, commit_sha: &str, target: &str) -> bool {
if self.target_is_ancestor_of(target, commit_sha) {
return false;
}
let Some(merge_base) = self.merge_base(target, commit_sha) else {
return false;
};
is_squash_merged_with_base(self.root, commit_sha, target, &merge_base)
}
fn is_cherry_merged_into_target(&mut self, commit_sha: &str, target: &str) -> bool {
let key = (commit_sha.to_string(), self.target_key(target));
if let Some(&cached) = self.cherry_cache.get(&key) {
return cached;
}
let merged = is_cherry_merged_into_target(self.root, commit_sha, target);
self.cherry_cache.insert(key, merged);
merged
}
fn is_merge_tree_merged_into_target(
&mut self,
commit_sha: &str,
target: &str,
target_tree: Option<&str>,
) -> bool {
let key = (commit_sha.to_string(), self.target_key(target));
if let Some(&cached) = self.merge_tree_cache.get(&key) {
return cached;
}
let resolved_tree = match target_tree {
Some(t) => Some(t.to_string()),
None => self.tree_sha(target),
};
let merged = match resolved_tree.as_deref() {
Some(tree) => {
is_merge_tree_merged_into_target(self.root, commit_sha, target, Some(tree))
}
None => false,
};
self.merge_tree_cache.insert(key, merged);
merged
}
fn merged_into(&mut self, commit_sha: &str, target: &str) -> bool {
if self.is_ancestor_of_target(commit_sha, target) {
return true;
}
if self.is_cherry_merged_into_target(commit_sha, target) {
return true;
}
if self.is_merge_tree_merged_into_target(commit_sha, target, None) {
return true;
}
if self.is_squash_merged_into_target(commit_sha, target) {
return true;
}
false
}
pub fn is_commit_merged_with_targets(
&mut self,
commit_sha: &str,
extra_targets: &[&str],
) -> bool {
let def = self.default_branch.clone();
if self.merged_into(commit_sha, &def) {
return true;
}
if let Some(origin_def) = self.origin_default.clone() {
if self.merged_into(commit_sha, &origin_def) {
return true;
}
}
for &extra in extra_targets {
if self.ref_exists(extra) && self.merged_into(commit_sha, extra) {
return true;
}
}
false
}
pub fn is_commit_merged(&mut self, commit_sha: &str) -> bool {
self.is_commit_merged_with_targets(commit_sha, &[])
}
pub fn is_branch_merged_with_targets(
&mut self,
branch_name: &str,
extra_targets: &[&str],
) -> bool {
let Some(tip) = self.get_branch_tip(branch_name) else {
return false;
};
self.is_commit_merged_with_targets(&tip, extra_targets)
}
pub fn is_branch_merged_checked(&mut self, branch_name: &str) -> Result<bool, String> {
if let Some(id) = branch_name.strip_prefix("wip/") {
Ok(self.check_run_merged(id)?.is_some())
} else {
Ok(self.is_branch_merged_with_targets(branch_name, &[]))
}
}
pub fn is_branch_merged(&mut self, branch_name: &str) -> bool {
match self.is_branch_merged_checked(branch_name) {
Ok(merged) => merged,
Err(err) => {
eprintln!("error: {err}");
false
}
}
}
fn decide_run_merged(
&mut self,
id: &str,
tip_sha: Option<&str>,
visited: &mut HashSet<String>,
) -> Result<Option<RemovalReason>, String> {
let base_opt = self.start_files.get(id).and_then(|s| {
s.get("base")
.and_then(|b| b.as_str())
.map(|b| b.to_string())
});
let base_targets = base_opt
.as_deref()
.and_then(|b| self.resolve_base_targets(b));
let started_at = self
.start_files
.get(id)
.and_then(|s| s.get("started_at"))
.cloned();
if let Some(tip_sha) = tip_sha {
if self.is_ancestor_of_default(tip_sha) {
return Ok(Some(RemovalReason::Merged));
}
if self.is_in_cherry_pick_record(tip_sha) {
return Ok(Some(RemovalReason::Merged));
}
if let Some((ref display_name, ref targets)) = base_targets {
for target in targets {
if self.is_ancestor_of_target(tip_sha, target) {
return Ok(Some(RemovalReason::MergedInto(display_name.clone())));
}
if self.is_cherry_merged_into_target(tip_sha, target) {
return Ok(Some(RemovalReason::MergedInto(display_name.clone())));
}
if self.is_merge_tree_merged_into_target(tip_sha, target, None) {
return Ok(Some(RemovalReason::MergedInto(display_name.clone())));
}
}
}
}
let children = self.get_children_of(id, tip_sha.unwrap_or(""));
for child in children {
if visited.contains(&child) {
continue;
}
if self.is_child_run_merged(&child, visited)? {
return Ok(Some(RemovalReason::MergedThrough(child)));
}
}
if let Some(tip_sha) = tip_sha {
let def = self.default_branch.clone();
if self.is_cherry_merged_into_target(tip_sha, &def) {
return Ok(Some(RemovalReason::Merged));
}
if let Some(origin_def) = self.origin_default.clone() {
if self.is_cherry_merged_into_target(tip_sha, &origin_def) {
return Ok(Some(RemovalReason::Merged));
}
}
let def_tree = self.default_tree.clone();
if self.is_merge_tree_merged_into_target(tip_sha, &def, def_tree.as_deref()) {
return Ok(Some(RemovalReason::Merged));
}
if let Some(origin_def) = self.origin_default.clone() {
let origin_tree = self.origin_default_tree.clone();
if self.is_merge_tree_merged_into_target(
tip_sha,
&origin_def,
origin_tree.as_deref(),
) {
return Ok(Some(RemovalReason::Merged));
}
}
if self.check_history_merged(tip_sha, &def, started_at.as_ref()) {
return Ok(Some(RemovalReason::Merged));
}
if let Some(origin_def) = self.origin_default.clone() {
if self.check_history_merged(tip_sha, &origin_def, started_at.as_ref()) {
return Ok(Some(RemovalReason::Merged));
}
}
if let Some((ref display_name, ref targets)) = base_targets {
for target in targets {
if self.check_history_merged(tip_sha, target, started_at.as_ref()) {
return Ok(Some(RemovalReason::MergedInto(display_name.clone())));
}
}
}
if let Some(reason) = self.squash_merged_reason(tip_sha, &base_targets) {
return Ok(Some(reason));
}
}
Ok(None)
}
fn squash_merged_reason(
&mut self,
tip_sha: &str,
base_targets: &Option<(String, Vec<String>)>,
) -> Option<RemovalReason> {
let def = self.default_branch.clone();
if self.is_squash_merged_into_target(tip_sha, &def) {
return Some(RemovalReason::Merged);
}
if let Some(origin_def) = self.origin_default.clone() {
if self.is_squash_merged_into_target(tip_sha, &origin_def) {
return Some(RemovalReason::Merged);
}
}
if let Some((ref display_name, ref targets)) = base_targets {
for target in targets {
if self.is_squash_merged_into_target(tip_sha, target) {
return Some(RemovalReason::MergedInto(display_name.clone()));
}
}
}
None
}
pub fn find_merged_followup(&mut self, id: &str) -> Result<Option<String>, String> {
let branch_name = format!("wip/{id}");
let tip_sha = self.get_branch_tip(&branch_name);
let mut visited = HashSet::new();
visited.insert(id.to_string());
let children = self.get_children_of(id, tip_sha.as_deref().unwrap_or(""));
for child in children {
if self.is_child_run_merged(&child, &mut visited)? {
return Ok(Some(child));
}
}
Ok(None)
}
pub fn check_removable(
&mut self,
id: &str,
older_than_days: u64,
) -> Result<RemovalReason, KeptReason> {
let wt_dir = self.root.join(".wt");
let summary_path = wt_dir.join(format!("{id}.json"));
let verdict_path = wt_dir.join(format!("{id}.verdict.json"));
let report_path = wt_dir.join(format!("{id}.report.md"));
match read_start_record(self.root, id) {
Err(reason) => return Err(KeptReason::UnreadableStartRecord(reason)),
Ok(Some(value)) => {
self.start_files.insert(id.to_string(), value);
}
Ok(None) => {
self.start_files.remove(id);
}
}
let start_json = self.start_files.get(id);
let summary_exists = summary_path.is_file();
if let Some(start) = start_json {
if let Some(pid) = start.get("pid").and_then(|p| p.as_i64()) {
if is_pid_alive(pid) {
if !summary_exists {
return Err(KeptReason::Running);
}
let Some(started_at) = parse_started_at(start) else {
return Err(KeptReason::Running);
};
let summary_mtime = std::fs::metadata(&summary_path)
.ok()
.and_then(|m| m.modified().ok())
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.map(|d| d.as_secs());
if summary_mtime.is_none_or(|mtime| mtime < started_at) {
return Err(KeptReason::Running);
}
}
}
}
let is_res = self.is_research_run(id);
let verdict_str = match read_verdict_file(&verdict_path) {
Ok(Some(v)) => v,
Ok(None) => String::new(),
Err(err) => return Err(KeptReason::UnreadableVerdict(err)),
};
if verdict_str == "redone" {
return Ok(RemovalReason::Verdict("redone".to_string()));
}
if summary_exists {
if let Ok(summary_str) = std::fs::read_to_string(&summary_path) {
if let Ok(val) = serde_json::from_str::<serde_json::Value>(&summary_str) {
if val.get("outcome").and_then(|o| o.as_str()) == Some("no_changes") {
return Ok(RemovalReason::NoChanges);
}
}
}
}
if is_res && report_path.is_file() {
return Ok(RemovalReason::ResearchReport);
}
if is_res {
let wt_report_path = wt_dir.join(id).join("report.md");
if wt_report_path.is_file() && !report_path.is_file() {
return Ok(RemovalReason::ResearchReportInWorktree);
}
if summary_exists {
let outcome = std::fs::read_to_string(&summary_path)
.ok()
.and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
.and_then(|v| {
v.get("outcome")
.and_then(|o| o.as_str())
.filter(|s| !s.is_empty())
.map(|s| s.to_string())
});
return match outcome {
Some(outcome) => Ok(RemovalReason::ResearchEndedWithoutReport(outcome)),
None => Err(KeptReason::UnreadableSummary),
};
}
let start_path = wt_dir.join(format!("{id}.start.json"));
if let Ok(meta) = std::fs::metadata(&start_path) {
if let Ok(mtime) = meta.modified() {
let age = std::time::SystemTime::now()
.duration_since(mtime)
.unwrap_or(std::time::Duration::ZERO);
if age >= std::time::Duration::from_secs(older_than_days.saturating_mul(86400))
{
return Ok(RemovalReason::ResearchStoppedWithoutSummary(
older_than_days,
));
}
}
}
}
if !is_res {
match self.check_run_merged(id) {
Ok(Some(reason)) => return Ok(reason),
Ok(None) => {}
Err(err) => return Err(KeptReason::UnreadableChildState(err)),
}
}
if summary_exists {
if let Ok(meta) = std::fs::metadata(&summary_path) {
if let Ok(mtime) = meta.modified() {
let age = std::time::SystemTime::now()
.duration_since(mtime)
.unwrap_or(std::time::Duration::ZERO);
if age >= std::time::Duration::from_secs(older_than_days.saturating_mul(86400))
{
return Ok(RemovalReason::OlderThan(older_than_days));
}
}
}
}
if !verdict_str.is_empty() {
return Err(KeptReason::NotMergedYet);
}
if is_res {
Err(KeptReason::NoReport)
} else {
Err(KeptReason::NoVerdict)
}
}
}
pub fn check_removable(
root: &Path,
id: &str,
older_than_days: u64,
) -> Result<RemovalReason, KeptReason> {
let mut ctx = CleanContext::new(root);
ctx.check_removable(id, older_than_days)
}
pub fn find_default_branch(root: &Path) -> String {
let sym_out = std::process::Command::new("git")
.args(["symbolic-ref", "--short", "refs/remotes/origin/HEAD"])
.current_dir(root)
.output();
if let Ok(o) = sym_out {
if o.status.success() {
let target = String::from_utf8_lossy(&o.stdout);
let target = target.trim();
let branch_name = target.strip_prefix("origin/").unwrap_or(target);
let local_check = std::process::Command::new("git")
.args([
"rev-parse",
"--verify",
&format!("refs/heads/{branch_name}"),
])
.current_dir(root)
.output();
if local_check.map(|c| c.status.success()).unwrap_or(false) {
return branch_name.to_string();
}
let remote_check = std::process::Command::new("git")
.args(["rev-parse", "--verify", target])
.current_dir(root)
.output();
if remote_check.map(|c| c.status.success()).unwrap_or(false) {
return target.to_string();
}
return branch_name.to_string();
}
}
let main_check = std::process::Command::new("git")
.args(["rev-parse", "--verify", "refs/heads/main"])
.current_dir(root)
.output();
if main_check.map(|c| c.status.success()).unwrap_or(false) {
return "main".to_string();
}
let master_check = std::process::Command::new("git")
.args(["rev-parse", "--verify", "refs/heads/master"])
.current_dir(root)
.output();
if master_check.map(|c| c.status.success()).unwrap_or(false) {
return "master".to_string();
}
"main".to_string()
}
fn is_commit_id(s: &str) -> bool {
(s.len() >= 7 && s.len() <= 64) && s.chars().all(|c| c.is_ascii_hexdigit())
}
fn resolve_base_targets_with<F>(base: &str, mut ref_exists: F) -> Option<(String, Vec<String>)>
where
F: FnMut(&str) -> bool,
{
let base = base.trim();
if base.is_empty() {
return None;
}
if base == "HEAD"
|| base.starts_with("HEAD~")
|| base.starts_with("HEAD^")
|| base.starts_with("HEAD@")
|| base.starts_with("HEAD:")
{
return None;
}
if base == "FETCH_HEAD" || base == "ORIG_HEAD" || base == "MERGE_HEAD" {
return None;
}
if is_commit_id(base) {
return None;
}
let clean = if let Some(stripped) = base.strip_prefix("refs/heads/") {
stripped
} else if let Some(stripped) = base.strip_prefix("refs/remotes/") {
stripped
} else {
base
};
let is_wip = clean == "wip"
|| clean.starts_with("wip/")
|| clean == "origin/wip"
|| clean.starts_with("origin/wip/");
if is_wip {
return None;
}
let (display_name, candidates) = if let Some(without_origin) = clean.strip_prefix("origin/") {
if without_origin.is_empty()
|| without_origin == "wip"
|| without_origin.starts_with("wip/")
|| without_origin == "HEAD"
|| without_origin.starts_with("HEAD~")
|| without_origin.starts_with("HEAD^")
|| is_commit_id(without_origin)
{
return None;
}
let cand1 = format!("refs/remotes/{clean}");
let cand2 = format!("refs/heads/{without_origin}");
(without_origin.to_string(), vec![cand1, cand2])
} else {
let cand1 = format!("refs/heads/{clean}");
let cand2 = format!("refs/remotes/origin/{clean}");
(clean.to_string(), vec![cand1, cand2])
};
let mut resolved = Vec::new();
for cand in candidates {
if ref_exists(&cand) {
resolved.push(cand);
}
}
if resolved.is_empty() {
None
} else {
Some((display_name, resolved))
}
}
pub fn resolve_base_targets(root: &Path, base: &str) -> Option<(String, Vec<String>)> {
resolve_base_targets_with(base, |cand| {
git_ok(root, &["rev-parse", "--verify", "--quiet", cand])
})
}
pub fn read_run_base(root: &Path, id: &str) -> Option<String> {
let start_path = root.join(".wt").join(format!("{id}.start.json"));
std::fs::read_to_string(&start_path)
.ok()
.and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
.and_then(|v| {
v.get("base")
.and_then(|b| b.as_str())
.map(|s| s.to_string())
})
}
pub fn get_branch_tip(root: &Path, branch_name: &str) -> Option<String> {
let check = std::process::Command::new("git")
.args([
"rev-parse",
"--verify",
&format!("refs/heads/{branch_name}"),
])
.current_dir(root)
.output()
.ok()?;
if !check.status.success() {
return None;
}
let tip_out = std::process::Command::new("git")
.args(["rev-parse", &format!("refs/heads/{branch_name}")])
.current_dir(root)
.output()
.ok()?;
if tip_out.status.success() {
Some(String::from_utf8_lossy(&tip_out.stdout).trim().to_string())
} else {
None
}
}
pub fn is_branch_merged(root: &Path, branch_name: &str) -> bool {
let mut ctx = CleanContext::new(root);
ctx.is_branch_merged(branch_name)
}
pub fn is_branch_merged_with_targets(
root: &Path,
branch_name: &str,
extra_targets: &[&str],
) -> bool {
let mut ctx = CleanContext::new(root);
ctx.is_branch_merged_with_targets(branch_name, extra_targets)
}
pub fn is_branch_merged_with_extra_targets(
root: &Path,
branch_name: &str,
extra_targets: &[&str],
) -> bool {
is_branch_merged_with_targets(root, branch_name, extra_targets)
}
pub fn is_commit_merged(root: &Path, commit_sha: &str) -> bool {
let mut ctx = CleanContext::new(root);
ctx.is_commit_merged(commit_sha)
}
pub fn is_commit_merged_with_targets(
root: &Path,
commit_sha: &str,
extra_targets: &[&str],
) -> bool {
let mut ctx = CleanContext::new(root);
ctx.is_commit_merged_with_targets(commit_sha, extra_targets)
}
fn git_ok(root: &Path, args: &[&str]) -> bool {
std::process::Command::new("git")
.args(args)
.current_dir(root)
.output()
.map(|o| o.status.success())
.unwrap_or(false)
}
fn is_squash_merged_with_base(root: &Path, commit_sha: &str, target: &str, base: &str) -> bool {
let subj_out = std::process::Command::new("git")
.args([
"log",
"--no-merges",
"--format=%s",
&format!("{target}..{commit_sha}"),
])
.current_dir(root)
.output();
let Ok(subj_o) = subj_out else {
return false;
};
if !subj_o.status.success() {
return false;
}
let subj_stdout = String::from_utf8_lossy(&subj_o.stdout);
let subjects: Vec<&str> = subj_stdout
.lines()
.map(|l| l.trim())
.filter(|l| !l.is_empty())
.collect();
if subjects.is_empty() {
return false;
}
let hay_out = std::process::Command::new("git")
.args(["log", "--format=%B", &format!("{base}..{target}")])
.current_dir(root)
.output();
let Ok(hay_o) = hay_out else {
return false;
};
if !hay_o.status.success() {
return false;
}
let hay_stdout = String::from_utf8_lossy(&hay_o.stdout);
let mut haystack_lines = HashSet::new();
for line in hay_stdout.lines() {
let trimmed = line.trim();
if trimmed.is_empty() {
continue;
}
haystack_lines.insert(trimmed.to_string());
if let Some(stripped) = trimmed
.strip_prefix("* ")
.or_else(|| trimmed.strip_prefix("- "))
{
let stripped = stripped.trim();
if !stripped.is_empty() {
haystack_lines.insert(stripped.to_string());
}
}
}
subjects.iter().all(|s| haystack_lines.contains(*s))
}
pub fn list_all_run_ids(root: &Path) -> Vec<String> {
let wt_dir = root.join(".wt");
let mut ids = Vec::new();
if let Ok(entries) = std::fs::read_dir(&wt_dir) {
for entry in entries.flatten() {
let name = entry.file_name().to_string_lossy().to_string();
if let Some(id) = name.strip_suffix(".start.json") {
ids.push(id.to_string());
}
}
}
ids.sort();
ids
}
pub fn find_merged_followup(root: &Path, id: &str) -> Result<Option<String>, String> {
let mut ctx = CleanContext::new(root);
ctx.find_merged_followup(id)
}
pub fn find_blyte_worktrees(root: &Path) -> Vec<String> {
let wt_dir = root.join(".wt");
if !wt_dir.is_dir() {
return Vec::new();
}
let mut ids = Vec::new();
if let Ok(entries) = std::fs::read_dir(&wt_dir) {
for entry in entries.flatten() {
if let Ok(ft) = entry.file_type() {
if ft.is_dir() {
let name = entry.file_name().to_string_lossy().to_string();
let start_file = wt_dir.join(format!("{name}.start.json"));
if start_file.is_file() {
ids.push(name);
}
}
}
}
}
ids.sort();
ids
}
#[derive(Debug, Default)]
pub struct CleanRepoStats {
pub removed_worktrees: usize,
pub freed_bytes: u64,
pub had_errors: bool,
}
pub const DEFAULT_SESSION_IDLE_DAYS: u64 = 7;
pub fn parse_lsof_cwd_output(stdout: &str) -> Vec<PathBuf> {
stdout
.lines()
.filter_map(|line| line.strip_prefix('n'))
.filter(|path| !path.is_empty())
.map(PathBuf::from)
.collect()
}
pub fn list_running_process_cwds() -> Result<Vec<PathBuf>, String> {
let out = std::process::Command::new("lsof")
.args(["-a", "-d", "cwd", "-Fn"])
.output()
.map_err(|e| e.to_string())?;
if !out.status.success() {
let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string();
if stderr.is_empty() {
return Err(format!("lsof exited with {}", out.status));
}
return Err(format!("lsof exited with {}: {stderr}", out.status));
}
let paths = parse_lsof_cwd_output(&String::from_utf8_lossy(&out.stdout));
if paths.is_empty() {
return Err("lsof listed no working directories".to_string());
}
Ok(paths)
}
pub fn is_session_worktree(root: &Path, wt_path: &Path) -> bool {
let root_canon = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
let wt_canon = wt_path
.canonicalize()
.unwrap_or_else(|_| wt_path.to_path_buf());
let Some(wt_parent) = wt_canon.parent() else {
return false;
};
let Some(wt_name) = wt_canon.file_name().and_then(|n| n.to_str()) else {
return false;
};
let wt_dir_canon = root_canon
.join(".wt")
.canonicalize()
.unwrap_or_else(|_| root_canon.join(".wt"));
if wt_parent == wt_dir_canon {
let start_file = wt_dir_canon.join(format!("{wt_name}.start.json"));
return !start_file.is_file();
}
let claude_wt_dir_canon = root_canon
.join(".claude")
.join("worktrees")
.canonicalize()
.unwrap_or_else(|_| root_canon.join(".claude").join("worktrees"));
if let Ok(rel) = wt_canon.strip_prefix(&claude_wt_dir_canon) {
if !rel.as_os_str().is_empty() && !has_wt_component(rel) {
return true;
}
}
false
}
pub fn has_dispatched_runs(wt_path: &Path) -> bool {
let wt_dir = wt_path.join(".wt");
let Ok(entries) = std::fs::read_dir(&wt_dir) else {
return false;
};
for entry in entries.flatten() {
let name = entry.file_name();
if name.to_string_lossy().ends_with(".start.json")
&& entry.file_type().map(|ft| ft.is_file()).unwrap_or(false)
{
return true;
}
}
false
}
pub fn is_worktree_in_use(wt_path: &Path, cwds: &[PathBuf]) -> bool {
let wt_canon = wt_path
.canonicalize()
.unwrap_or_else(|_| wt_path.to_path_buf());
cwds.iter().any(|cwd| {
let cwd_canon = cwd.canonicalize().unwrap_or_else(|_| cwd.clone());
cwd_canon.starts_with(&wt_canon)
})
}
pub fn is_worktree_idle(wt_path: &Path, idle_days: u64) -> Result<bool, String> {
let o = std::process::Command::new("git")
.arg("-C")
.arg(wt_path.as_os_str())
.args(["rev-parse", "--absolute-git-dir"])
.output()
.map_err(|e| format!("cannot run git: {e}"))?;
if !o.status.success() {
return Err(format!(
"git rev-parse --absolute-git-dir failed: {}",
String::from_utf8_lossy(&o.stderr).trim()
));
}
let git_dir_str = String::from_utf8_lossy(&o.stdout).trim().to_string();
if git_dir_str.is_empty() {
return Err("git rev-parse --absolute-git-dir printed nothing".to_string());
}
let git_dir = PathBuf::from(git_dir_str);
let now = std::time::SystemTime::now();
let threshold = std::time::Duration::from_secs(idle_days.saturating_mul(86400));
for name in ["index", "HEAD"] {
let p = git_dir.join(name);
let mtime = std::fs::metadata(&p)
.and_then(|m| m.modified())
.map_err(|e| format!("cannot read the time of {}: {e}", p.display()))?;
let age = now
.duration_since(mtime)
.unwrap_or(std::time::Duration::ZERO);
if idle_days > 0 && age <= threshold {
return Ok(false);
}
}
Ok(true)
}
fn check_session_worktree_removable_with_ctx(
ctx: &mut CleanContext<'_>,
wt: &GitWorktreeInfo,
cwds: &Result<Vec<PathBuf>, String>,
idle_days: u64,
) -> Result<RemovalReason, KeptReason> {
let is_merged = if let Some(ref branch) = wt.branch {
ctx.is_branch_merged_checked(branch)
.map_err(KeptReason::UnreadableChildState)?
} else if let Some(ref sha) = wt.head_sha {
ctx.is_commit_merged(sha)
} else {
false
};
if !is_merged {
return Err(KeptReason::NotMergedYet);
}
if has_dispatched_runs(&wt.path) {
let display_path = display_worktree_path(&wt.path, ctx.root);
return Err(KeptReason::HoldsRuns(display_path));
}
if !is_worktree_clean(&wt.path) {
return Err(KeptReason::UncommittedChanges);
}
match cwds {
Ok(list) => {
if is_worktree_in_use(&wt.path, list) {
return Err(KeptReason::InUse);
}
}
Err(err) => {
return Err(KeptReason::CannotCheckInUse(err.clone()));
}
}
match is_worktree_idle(&wt.path, idle_days) {
Ok(true) => {}
Ok(false) => return Err(KeptReason::UsedRecently(idle_days)),
Err(e) => {
return Err(KeptReason::Custom(format!(
"cannot tell when it was last used: {e}"
)))
}
}
let branch_label = wt.branch.clone().unwrap_or_else(|| {
wt.head_sha
.as_deref()
.map(|s| s[..s.len().min(7)].to_string())
.unwrap_or_else(|| "detached".to_string())
});
Ok(RemovalReason::SessionMerged(branch_label))
}
pub fn check_session_worktree_removable(
root: &Path,
wt: &GitWorktreeInfo,
cwds: &Result<Vec<PathBuf>, String>,
idle_days: u64,
) -> Result<RemovalReason, KeptReason> {
let mut ctx = CleanContext::new(root);
check_session_worktree_removable_with_ctx(&mut ctx, wt, cwds, idle_days)
}
fn branch_checked_out_elsewhere(
worktrees: &[GitWorktreeInfo],
removed_wt_paths: &HashSet<PathBuf>,
current_wt_canon: &Path,
branch_name: &str,
) -> bool {
for wt in worktrees {
if !wt.path.exists() {
continue;
}
let wt_canon = wt
.path
.canonicalize()
.unwrap_or_else(|_| wt.path.to_path_buf());
if wt_canon == current_wt_canon || removed_wt_paths.contains(&wt_canon) {
continue;
}
if wt.branch.as_deref() == Some(branch_name) {
return true;
}
}
false
}
pub fn clean_repo(
root: &Path,
older_than_days: u64,
dry_run: bool,
skip_id: Option<&str>,
quiet: bool,
) -> CleanRepoStats {
clean_repo_with_options(
root,
older_than_days,
dry_run,
skip_id,
quiet,
DEFAULT_SESSION_IDLE_DAYS,
None,
)
}
pub fn clean_repo_with_options(
root: &Path,
older_than_days: u64,
dry_run: bool,
skip_id: Option<&str>,
quiet: bool,
session_idle_days: u64,
process_cwds: Option<Result<Vec<PathBuf>, String>>,
) -> CleanRepoStats {
let mut removed_worktrees = 0;
let mut freed_bytes = 0;
let mut had_errors = false;
let mut needs_worktree_prune = false;
let mut ctx = CleanContext::new(root);
let is_linked = is_linked_worktree(root);
let all_worktrees = if !is_linked {
parse_worktree_list(root)
} else {
Vec::new()
};
let ids = find_blyte_worktrees(root);
for id in ids {
if skip_id == Some(&id) {
continue;
}
let wt_path = root.join(".wt").join(&id);
match ctx.check_removable(&id, older_than_days) {
Err(kept_reason) => {
if matches!(
kept_reason,
KeptReason::UnreadableVerdict(_) | KeptReason::UnreadableChildState(_)
) {
eprintln!("error: {kept_reason}");
had_errors = true;
}
if !quiet {
println!("kept .wt/{id} ({kept_reason})");
}
}
Ok(removal_reason) => {
let is_res = ctx.is_research_run(&id);
if !is_res && has_uncommitted_changes(&wt_path) {
if !quiet {
println!("kept .wt/{id} (uncommitted changes)");
}
continue;
}
let size = dir_size(&wt_path);
let branch_name = format!("wip/{id}");
let branch_exists = ctx.get_branch_tip(&branch_name).is_some();
let is_merged = if !branch_exists {
false
} else if matches!(
removal_reason,
RemovalReason::Merged
| RemovalReason::MergedInto(_)
| RemovalReason::MergedThrough(_)
) {
true
} else {
match ctx.check_run_merged(&id) {
Ok(Some(_)) => true,
Ok(None) => false,
Err(err) => {
eprintln!("error: {err}");
had_errors = true;
if !quiet {
println!("kept .wt/{id} (unreadable child state: {err})");
}
continue;
}
}
};
if dry_run {
if !quiet {
println!(
"would remove .wt/{id} ({removal_reason}, {})",
format_size(size)
);
if is_merged {
println!("would delete branch {branch_name} (merged)");
}
}
freed_bytes += size;
removed_worktrees += 1;
} else {
if removal_reason == RemovalReason::ResearchReportInWorktree {
let src = wt_path.join("report.md");
let dst = root.join(".wt").join(format!("{id}.report.md"));
if let Err(err) = std::fs::copy(&src, &dst) {
eprintln!(
"error: could not copy {} to {}: {err}",
src.display(),
dst.display()
);
if !quiet {
println!("kept .wt/{id} (report copy failed)");
}
continue;
}
}
if let Err(reason) = ctx.check_removable(&id, older_than_days) {
if matches!(
reason,
KeptReason::UnreadableVerdict(_) | KeptReason::UnreadableChildState(_)
) {
eprintln!("error: {reason}");
had_errors = true;
}
if !quiet {
println!("kept .wt/{id} ({reason})");
}
continue;
}
let had_prior_record = crate::removal_record::path(root, &id).exists();
if let Err(err) =
crate::removal_record::record_removal(root, &id, &removal_reason)
{
eprintln!("error: could not write removal record for {id}: {err}");
had_errors = true;
if !quiet {
println!("kept .wt/{id} (removal record write failed)");
}
continue;
}
let removed_ok = if is_res {
std::fs::remove_dir_all(&wt_path).is_ok()
} else {
let rm_out = std::process::Command::new("git")
.args(["worktree", "remove", wt_path.to_str().unwrap_or("")])
.current_dir(root)
.output();
needs_worktree_prune = true;
rm_out.map(|o| o.status.success()).unwrap_or(false)
};
if removed_ok {
freed_bytes += size;
removed_worktrees += 1;
if !quiet {
println!("removed .wt/{id} ({removal_reason}, {})", format_size(size));
}
if is_merged {
let del_out = std::process::Command::new("git")
.args(["branch", "-D", &branch_name])
.current_dir(root)
.output();
if del_out.map(|o| o.status.success()).unwrap_or(false) {
ctx.remove_branch(&branch_name);
if !quiet {
println!("deleted branch {branch_name} (merged)");
}
}
}
} else {
if !had_prior_record {
let _ = std::fs::remove_file(crate::removal_record::path(root, &id));
}
if !quiet {
println!("kept .wt/{id} (worktree remove failed)");
}
}
}
}
}
}
if !is_linked {
let root_canon = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
let main_canon = all_worktrees
.first()
.map(|wt| wt.path.canonicalize().unwrap_or_else(|_| wt.path.clone()));
let mut session_indices: Vec<(String, usize)> = all_worktrees
.iter()
.enumerate()
.skip(1)
.filter_map(|(idx, wt)| {
if wt.is_bare || !wt.path.exists() {
return None;
}
let wt_canon = wt.path.canonicalize().unwrap_or_else(|_| wt.path.clone());
if wt_canon == root_canon || Some(&wt_canon) == main_canon.as_ref() {
return None;
}
if !is_session_worktree(root, &wt.path) {
return None;
}
Some((display_worktree_path(&wt.path, root), idx))
})
.collect();
session_indices.sort_by(|a, b| a.0.cmp(&b.0));
if !session_indices.is_empty() {
let cwds = process_cwds.unwrap_or_else(list_running_process_cwds);
let mut removed_wt_paths = HashSet::new();
for (display_path, idx) in session_indices {
let wt = &all_worktrees[idx];
let wt_canon = wt.path.canonicalize().unwrap_or_else(|_| wt.path.clone());
match check_session_worktree_removable_with_ctx(
&mut ctx,
wt,
&cwds,
session_idle_days,
) {
Err(kept_reason) => {
if matches!(
kept_reason,
KeptReason::UnreadableVerdict(_) | KeptReason::UnreadableChildState(_)
) {
eprintln!("error: {kept_reason}");
had_errors = true;
}
if !quiet {
println!("kept {display_path} ({kept_reason})");
}
}
Ok(removal_reason) => {
let size = dir_size(&wt.path);
if dry_run {
removed_wt_paths.insert(wt_canon.clone());
if !quiet {
println!(
"would remove {display_path} ({removal_reason}, {})",
format_size(size)
);
if let Some(ref branch_name) = wt.branch {
if !branch_checked_out_elsewhere(
&all_worktrees,
&removed_wt_paths,
&wt_canon,
branch_name,
) && ctx.get_branch_tip(branch_name).is_some()
{
println!("would delete branch {branch_name} (merged)");
}
}
}
freed_bytes += size;
removed_worktrees += 1;
} else {
let rm_out = std::process::Command::new("git")
.arg("worktree")
.arg("remove")
.arg(&wt.path)
.current_dir(root)
.output();
match rm_out {
Ok(o) if o.status.success() => {
needs_worktree_prune = true;
removed_wt_paths.insert(wt_canon.clone());
freed_bytes += size;
removed_worktrees += 1;
if !quiet {
println!(
"removed {display_path} ({removal_reason}, {})",
format_size(size)
);
}
if let Some(ref branch_name) = wt.branch {
if !branch_checked_out_elsewhere(
&all_worktrees,
&removed_wt_paths,
&wt_canon,
branch_name,
) && ctx.get_branch_tip(branch_name).is_some()
{
let del_out = std::process::Command::new("git")
.args(["branch", "-D", branch_name])
.current_dir(root)
.output();
match del_out {
Ok(o) if o.status.success() => {
ctx.remove_branch(branch_name);
if !quiet {
println!(
"deleted branch {branch_name} (merged)"
);
}
}
Ok(o) => {
eprintln!(
"error: could not delete branch {branch_name}: {}",
String::from_utf8_lossy(&o.stderr).trim()
);
had_errors = true;
}
Err(e) => {
eprintln!(
"error: could not delete branch {branch_name}: {e}"
);
had_errors = true;
}
}
}
}
}
Ok(o) => {
let stderr =
String::from_utf8_lossy(&o.stderr).trim().to_string();
let stdout =
String::from_utf8_lossy(&o.stdout).trim().to_string();
let msg = if !stderr.is_empty() {
stderr
} else if !stdout.is_empty() {
stdout
} else {
format!("exit status {}", o.status)
};
eprintln!("error: could not remove {display_path}: {msg}");
had_errors = true;
}
Err(e) => {
eprintln!("error: could not remove {display_path}: {e}");
had_errors = true;
}
}
}
}
}
}
}
}
if needs_worktree_prune {
let _ = std::process::Command::new("git")
.args(["worktree", "prune"])
.current_dir(root)
.output();
}
if !quiet && !is_linked {
report_other_worktrees_with_ctx(root, &mut ctx, &all_worktrees);
}
if !is_linked
&& run_clean_surfaces_at(
root,
older_than_days,
dry_run,
quiet,
std::time::SystemTime::now(),
)
{
had_errors = true;
}
CleanRepoStats {
removed_worktrees,
freed_bytes,
had_errors,
}
}
fn unix_secs_from_system_time(now: std::time::SystemTime) -> Result<u64, String> {
now.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.map_err(|e| format!("system clock is before UNIX_EPOCH: {e}"))
}
fn run_clean_surfaces_at(
root: &Path,
older_than_days: u64,
dry_run: bool,
quiet: bool,
now: std::time::SystemTime,
) -> bool {
match unix_secs_from_system_time(now)
.and_then(|now_secs| clean_surfaces(root, older_than_days, dry_run, now_secs))
{
Ok(lines) => {
if !quiet {
for line in lines {
println!("{line}");
}
}
false
}
Err(err) => {
eprintln!("blyte: {err}");
true
}
}
}
const LEGACY_SURFACE_PROBE_TIMEOUT: std::time::Duration = std::time::Duration::from_millis(300);
#[derive(serde::Deserialize)]
struct LegacySurfaceFile {
port: u16,
session_id: String,
}
fn is_legacy_surface_running(port: u16, expected_session_id: &str) -> bool {
if port == 0 {
return false;
}
let agent = ureq::AgentBuilder::new()
.timeout_connect(LEGACY_SURFACE_PROBE_TIMEOUT)
.timeout_read(LEGACY_SURFACE_PROBE_TIMEOUT)
.timeout_write(LEGACY_SURFACE_PROBE_TIMEOUT)
.timeout(LEGACY_SURFACE_PROBE_TIMEOUT)
.redirects(0)
.build();
let url = format!("http://127.0.0.1:{port}/api/health");
let resp = match agent.get(&url).call() {
Ok(r) => r,
Err(_) => return false,
};
if resp.status() != 200 {
return false;
}
let val: serde_json::Value = match resp.into_json() {
Ok(v) => v,
Err(_) => return false,
};
val.get("session_id").and_then(|v| v.as_str()) == Some(expected_session_id)
}
fn path_present(path: &Path) -> Result<bool, String> {
match std::fs::symlink_metadata(path) {
Ok(_) => Ok(true),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
Err(e) => Err(format!("failed to inspect {}: {e}", path.display())),
}
}
fn remove_file_if_present(
path: &Path,
label: &str,
dry_run: bool,
lines: &mut Vec<String>,
) -> Result<(), String> {
if !path_present(path)? {
return Ok(());
}
let verb = if dry_run { "would remove" } else { "removed" };
if !dry_run {
std::fs::remove_file(path)
.map_err(|e| format!("failed to remove {}: {e}", path.display()))?;
}
lines.push(format!("{verb} {label}"));
Ok(())
}
fn remove_dir_if_present(
path: &Path,
label: &str,
dry_run: bool,
lines: &mut Vec<String>,
) -> Result<(), String> {
if !path_present(path)? {
return Ok(());
}
let verb = if dry_run { "would remove" } else { "removed" };
if !dry_run {
std::fs::remove_dir_all(path)
.map_err(|e| format!("failed to remove {}: {e}", path.display()))?;
}
lines.push(format!("{verb} {label}"));
Ok(())
}
fn newest_file_mtime_in(
dir: &Path,
newest: &mut Option<std::time::SystemTime>,
) -> Result<(), String> {
let entries = std::fs::read_dir(dir)
.map_err(|e| format!("failed to read directory {}: {e}", dir.display()))?;
for entry in entries {
let entry =
entry.map_err(|e| format!("failed to read directory {}: {e}", dir.display()))?;
let path = entry.path();
let meta = std::fs::symlink_metadata(&path)
.map_err(|e| format!("failed to inspect {}: {e}", path.display()))?;
if meta.is_dir() {
newest_file_mtime_in(&path, newest)?;
} else {
let mtime = meta
.modified()
.map_err(|e| format!("failed to read modified time of {}: {e}", path.display()))?;
if newest.is_none_or(|cur| mtime > cur) {
*newest = Some(mtime);
}
}
}
Ok(())
}
fn newest_file_mtime(dir: &Path) -> Result<std::time::SystemTime, String> {
let mut newest = None;
newest_file_mtime_in(dir, &mut newest)?;
newest.ok_or_else(|| format!("surface directory {} contains no files", dir.display()))
}
pub fn clean_surfaces(
main_checkout: &Path,
older_than_days: u64,
dry_run: bool,
now_secs: u64,
) -> Result<Vec<String>, String> {
let mut lines = Vec::new();
let wt_dir = main_checkout.join(".wt");
let old_surface_path = wt_dir.join("surface.json");
let old_sessions_dir = wt_dir.join("sessions");
match std::fs::read_to_string(&old_surface_path) {
Ok(raw) => {
let info: LegacySurfaceFile = serde_json::from_str(&raw)
.map_err(|e| format!("failed to parse {}: {e}", old_surface_path.display()))?;
if !is_legacy_surface_running(info.port, &info.session_id) {
let token_path = blyte_agent::sandbox::surface_token_path(main_checkout)?;
let token_label = token_path.display().to_string();
remove_file_if_present(&old_surface_path, ".wt/surface.json", dry_run, &mut lines)?;
remove_dir_if_present(&old_sessions_dir, ".wt/sessions/", dry_run, &mut lines)?;
remove_file_if_present(&token_path, &token_label, dry_run, &mut lines)?;
}
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
remove_dir_if_present(&old_sessions_dir, ".wt/sessions/", dry_run, &mut lines)?;
}
Err(e) => {
return Err(format!(
"failed to read {}: {e}",
old_surface_path.display()
));
}
}
let state_dir = crate::surface_registry::state_dir()?;
let records = crate::surface_dir::list_records_for_root(main_checkout, Some(&state_dir))?;
let now = std::time::UNIX_EPOCH + std::time::Duration::from_secs(now_secs);
let max_age = std::time::Duration::from_secs(older_than_days.saturating_mul(86_400));
for located in records {
if crate::surface_dir::is_running(&located.record) {
continue;
}
let dir = &located.dir;
let newest = newest_file_mtime(dir)?;
let is_older = match now.duration_since(newest) {
Ok(age) => age > max_age,
Err(_) => false,
};
if !is_older {
continue;
}
let token_path = blyte_agent::sandbox::surface_token_path_for_id(&located.record.id)?;
let dir_label = if dir.starts_with(main_checkout) {
format!(".wt/surfaces/{}", located.record.id)
} else {
dir.display().to_string()
};
let token_label = token_path.display().to_string();
remove_dir_if_present(dir, &dir_label, dry_run, &mut lines)?;
remove_file_if_present(&token_path, &token_label, dry_run, &mut lines)?;
}
Ok(lines)
}
#[derive(Debug)]
pub struct GitWorktreeInfo {
pub path: PathBuf,
pub head_sha: Option<String>,
pub branch: Option<String>,
pub is_detached: bool,
pub is_bare: bool,
}
pub fn parse_worktree_list(root: &Path) -> Vec<GitWorktreeInfo> {
let out = std::process::Command::new("git")
.args(["worktree", "list", "--porcelain"])
.current_dir(root)
.output();
let Ok(o) = out else {
return Vec::new();
};
if !o.status.success() {
return Vec::new();
}
let text = String::from_utf8_lossy(&o.stdout);
let mut list = Vec::new();
let mut cur_path: Option<PathBuf> = None;
let mut cur_head: Option<String> = None;
let mut cur_branch: Option<String> = None;
let mut cur_detached = false;
let mut cur_bare = false;
let mut finish_entry = |path: &mut Option<PathBuf>,
head: &mut Option<String>,
branch: &mut Option<String>,
detached: &mut bool,
bare: &mut bool| {
if let Some(p) = path.take() {
list.push(GitWorktreeInfo {
path: p,
head_sha: head.take(),
branch: branch.take(),
is_detached: *detached,
is_bare: *bare,
});
*detached = false;
*bare = false;
}
};
for line in text.lines() {
let line = line.trim();
if line.is_empty() {
finish_entry(
&mut cur_path,
&mut cur_head,
&mut cur_branch,
&mut cur_detached,
&mut cur_bare,
);
} else if let Some(p) = line.strip_prefix("worktree ") {
finish_entry(
&mut cur_path,
&mut cur_head,
&mut cur_branch,
&mut cur_detached,
&mut cur_bare,
);
cur_path = Some(PathBuf::from(p.trim()));
} else if let Some(h) = line.strip_prefix("HEAD ") {
cur_head = Some(h.trim().to_string());
} else if let Some(b) = line.strip_prefix("branch ") {
let b_str = b.trim();
let b_name = b_str.strip_prefix("refs/heads/").unwrap_or(b_str);
cur_branch = Some(b_name.to_string());
} else if line == "detached" {
cur_detached = true;
} else if line == "bare" {
cur_bare = true;
}
}
finish_entry(
&mut cur_path,
&mut cur_head,
&mut cur_branch,
&mut cur_detached,
&mut cur_bare,
);
list
}
pub fn display_worktree_path(target: &Path, root: &Path) -> String {
let target_canon = target
.canonicalize()
.unwrap_or_else(|_| target.to_path_buf());
let root_canon = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
if let Ok(rel) = target_canon.strip_prefix(&root_canon) {
if !rel.as_os_str().is_empty() {
return rel.to_string_lossy().replace('\\', "/");
}
}
if target_canon != root_canon {
if let (Some(root_parent), Some(target_parent)) =
(root_canon.parent(), target_canon.parent())
{
if root_parent == target_parent {
if let Some(file_name) = target_canon.file_name() {
let rel = Path::new("..").join(file_name);
return rel.to_string_lossy().replace('\\', "/");
}
}
}
}
target_canon.to_string_lossy().replace('\\', "/")
}
pub fn is_linked_worktree(root: &Path) -> bool {
let out = std::process::Command::new("git")
.args([
"rev-parse",
"--path-format=absolute",
"--git-dir",
"--git-common-dir",
])
.current_dir(root)
.output();
match out {
Ok(o) if o.status.success() => {
let text = String::from_utf8_lossy(&o.stdout);
let mut lines = text.lines();
let (Some(gd_str), Some(cd_str)) = (lines.next(), lines.next()) else {
return false;
};
let gd_str = gd_str.trim();
let cd_str = cd_str.trim();
if gd_str == cd_str {
return false;
}
let gd_path = PathBuf::from(gd_str);
let cd_path = PathBuf::from(cd_str);
let gd_canon = gd_path.canonicalize().unwrap_or(gd_path);
let cd_canon = cd_path.canonicalize().unwrap_or(cd_path);
gd_canon != cd_canon
}
_ => false,
}
}
pub fn has_wt_component(path: &Path) -> bool {
path.components().any(|c| c.as_os_str() == ".wt")
}
pub fn is_worktree_clean(wt_path: &Path) -> bool {
let out = std::process::Command::new("git")
.arg("--no-optional-locks")
.arg("-C")
.arg(wt_path.as_os_str())
.args(["status", "--porcelain", "-u"])
.output();
match out {
Ok(o) if o.status.success() => {
let stdout = String::from_utf8_lossy(&o.stdout);
for line in stdout.lines() {
let trimmed = line.trim();
if trimmed.is_empty() {
continue;
}
if line.len() < 3 {
return false;
}
let mut path_part = line[3..].trim();
if let Some((_, new_path)) = path_part.split_once(" -> ") {
path_part = new_path.trim();
}
let unquoted = path_part
.strip_prefix('"')
.and_then(|p| p.strip_suffix('"'))
.unwrap_or(path_part);
if Path::new(unquoted).file_name() != Some(std::ffi::OsStr::new(".DS_Store")) {
return false;
}
}
true
}
_ => false,
}
}
fn report_other_worktrees_with_ctx(
root: &Path,
ctx: &mut CleanContext<'_>,
worktrees: &[GitWorktreeInfo],
) {
let root_canon = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
let main_canon = worktrees
.first()
.map(|wt| wt.path.canonicalize().unwrap_or_else(|_| wt.path.clone()));
let mut other_count = 0;
let mut other_bytes = 0;
for (idx, wt) in worktrees.iter().enumerate() {
if idx == 0 {
continue;
}
if wt.is_bare {
continue;
}
if !wt.path.exists() {
continue;
}
let wt_canon = wt.path.canonicalize().unwrap_or_else(|_| wt.path.clone());
if wt_canon == root_canon || wt.path == root {
continue;
}
if Some(&wt_canon) == main_canon.as_ref() {
continue;
}
if has_wt_component(&wt.path)
|| has_wt_component(&wt_canon)
|| is_session_worktree(root, &wt.path)
{
continue;
}
let is_merged = if let Some(ref branch) = wt.branch {
match ctx.is_branch_merged_checked(branch) {
Ok(merged) => merged,
Err(err) => {
eprintln!("error: {err}");
false
}
}
} else if let Some(ref sha) = wt.head_sha {
ctx.is_commit_merged(sha)
} else {
false
};
if !is_merged {
continue;
}
if !is_worktree_clean(&wt.path) {
continue;
}
let size = dir_size(&wt.path);
let path_str = display_worktree_path(&wt.path, root);
let branch_label = wt.branch.as_deref().unwrap_or_else(|| {
wt.head_sha
.as_deref()
.map(|s| &s[..s.len().min(7)])
.unwrap_or("detached")
});
println!(
"merged worktree {path_str} ({branch_label}, {}): git worktree remove {path_str}",
format_size(size)
);
other_count += 1;
other_bytes += size;
}
if other_count > 0 {
println!(
"{other_count} other worktrees are merged and clean ({}); remove them with the commands above",
format_size(other_bytes)
);
}
}
pub fn report_other_worktrees(root: &Path) {
if is_linked_worktree(root) {
return;
}
let worktrees = parse_worktree_list(root);
let mut ctx = CleanContext::new(root);
report_other_worktrees_with_ctx(root, &mut ctx, &worktrees);
}
struct CleanLockGuard(PathBuf);
impl Drop for CleanLockGuard {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.0);
}
}
enum LockOutcome {
Acquired(CleanLockGuard),
AlreadyRunning,
Error(String),
}
fn acquire_clean_lock(root: &Path) -> LockOutcome {
use std::io::Write;
let wt_dir = root.join(".wt");
if let Err(e) = std::fs::create_dir_all(&wt_dir) {
return LockOutcome::Error(format!("{}: {e}", wt_dir.display()));
}
let lock_path = wt_dir.join("clean.lock");
let pid_str = format!("{}\n", std::process::id());
match std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&lock_path)
{
Ok(mut f) => {
if let Err(e) = f.write_all(pid_str.as_bytes()) {
let _ = std::fs::remove_file(&lock_path);
return LockOutcome::Error(format!("{}: {e}", lock_path.display()));
}
LockOutcome::Acquired(CleanLockGuard(lock_path))
}
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
let contents = match std::fs::read_to_string(&lock_path) {
Ok(c) => c,
Err(read_err) => {
return LockOutcome::Error(format!("{}: {read_err}", lock_path.display()));
}
};
let old_pid: i64 = match contents.trim().parse() {
Ok(p) => p,
Err(parse_err) => {
return LockOutcome::Error(format!(
"{}: invalid pid: {parse_err}",
lock_path.display()
));
}
};
if is_pid_alive(old_pid) {
return LockOutcome::AlreadyRunning;
}
eprintln!(
"replacing stale {} from dead pid {old_pid}",
lock_path.display()
);
if let Err(rm_err) = std::fs::remove_file(&lock_path) {
return LockOutcome::Error(format!("{}: {rm_err}", lock_path.display()));
}
match std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&lock_path)
{
Ok(mut f) => {
if let Err(write_err) = f.write_all(pid_str.as_bytes()) {
let _ = std::fs::remove_file(&lock_path);
return LockOutcome::Error(format!("{}: {write_err}", lock_path.display()));
}
LockOutcome::Acquired(CleanLockGuard(lock_path))
}
Err(open_err) => LockOutcome::Error(format!("{}: {open_err}", lock_path.display())),
}
}
Err(e) => LockOutcome::Error(format!("{}: {e}", lock_path.display())),
}
}
pub fn run(args: &crate::cli::CleanArgs) -> i32 {
if (args.quiet || args.skip.is_some()) && (args.all || args.dry_run) {
eprintln!("error: --quiet and --skip cannot be combined with --all or --dry-run");
return 2;
}
let repos = if args.all {
let tidy_res = if args.dry_run {
crate::registry::missing_registered()
} else {
crate::registry::prune_missing()
};
match tidy_res {
Ok(removed) if !removed.is_empty() => {
let verb = if args.dry_run {
"would forget"
} else {
"forgot"
};
let list = removed
.iter()
.map(|p| p.display().to_string())
.collect::<Vec<_>>()
.join(", ");
println!(
"{verb} {} repositories that no longer exist: {list}",
removed.len()
);
}
Ok(_) => {}
Err(err) => {
let path = crate::registry::state_dir()
.map(|d| d.join("repos").display().to_string())
.unwrap_or_default();
eprintln!("error: could not tidy the repository registry {path}: {err}");
}
}
crate::registry::registered()
} else {
match find_repo_root() {
Ok(root) => vec![root],
Err(e) => {
eprintln!("error: {e}");
return 2;
}
}
};
let _lock_guard = if args.quiet {
let Some(root) = repos.first() else {
eprintln!("error: blyte clean --quiet found no repository to clean");
return 1;
};
match acquire_clean_lock(root) {
LockOutcome::Acquired(guard) => Some(guard),
LockOutcome::AlreadyRunning => return 0,
LockOutcome::Error(e) => {
eprintln!("error: {e}");
return 1;
}
}
} else {
None
};
let mut total_freed = 0;
let mut had_errors = false;
for repo in &repos {
let stats = clean_repo(
repo,
args.older_than,
args.dry_run,
args.skip.as_deref(),
args.quiet,
);
total_freed += stats.freed_bytes;
if stats.had_errors {
had_errors = true;
}
}
if !args.quiet {
if args.dry_run {
println!("would free {}", format_size(total_freed));
} else {
println!("freed {}", format_size(total_freed));
}
}
if had_errors {
1
} else {
0
}
}
fn delete_wip_branch_strict(root: &Path, branch_name: &str) -> Result<(), String> {
let del_out = std::process::Command::new("git")
.args(["branch", "-D", branch_name])
.current_dir(root)
.output()
.map_err(|e| format!("git branch -D {branch_name}: {e}"))?;
if !del_out.status.success() {
return Err(format!(
"git branch -D {branch_name}: {}",
String::from_utf8_lossy(&del_out.stderr).trim()
));
}
Ok(())
}
pub fn remove_finished_run(root: &Path, id: &str) -> Result<Option<String>, String> {
let wt_path = root.join(".wt").join(id);
let branch_name = format!("wip/{id}");
let mut ctx = CleanContext::new(root);
if wt_path.exists() {
let reason = match ctx.check_removable(id, u64::MAX) {
Ok(
r @ (RemovalReason::Merged
| RemovalReason::MergedInto(_)
| RemovalReason::MergedThrough(_)
| RemovalReason::NoChanges),
) => r,
Err(KeptReason::UnreadableVerdict(err) | KeptReason::UnreadableChildState(err)) => {
return Err(err);
}
Ok(
RemovalReason::SessionMerged(_)
| RemovalReason::Verdict(_)
| RemovalReason::OlderThan(_)
| RemovalReason::ResearchReport
| RemovalReason::ResearchReportInWorktree
| RemovalReason::ResearchEndedWithoutReport(_)
| RemovalReason::ResearchStoppedWithoutSummary(_),
)
| Err(_) => return Ok(None),
};
if has_uncommitted_changes(&wt_path) {
return Ok(None);
}
let had_prior_record = crate::removal_record::path(root, id).exists();
crate::removal_record::record_removal(root, id, &reason)?;
let wt_rel = format!(".wt/{id}");
let rm_out = std::process::Command::new("git")
.args(["worktree", "remove", &wt_rel])
.current_dir(root)
.output()
.map_err(|e| {
if !had_prior_record {
let _ = std::fs::remove_file(crate::removal_record::path(root, id));
}
format!("git worktree remove {wt_rel}: {e}")
})?;
if !rm_out.status.success() {
if !had_prior_record {
let _ = std::fs::remove_file(crate::removal_record::path(root, id));
}
return Err(format!(
"git worktree remove {wt_rel}: {}",
String::from_utf8_lossy(&rm_out.stderr).trim()
));
}
if ctx.get_branch_tip(&branch_name).is_some() {
delete_wip_branch_strict(root, &branch_name)?;
}
return Ok(Some(reason.to_string()));
}
if ctx.get_branch_tip(&branch_name).is_some() {
let Some(reason) = ctx.check_run_merged(id)? else {
return Ok(None);
};
let had_prior_record = crate::removal_record::path(root, id).exists();
crate::removal_record::record_removal(root, id, &reason)?;
if let Err(err) = delete_wip_branch_strict(root, &branch_name) {
if !had_prior_record {
let _ = std::fs::remove_file(crate::removal_record::path(root, id));
}
return Err(err);
}
return Ok(Some(reason.to_string()));
}
Ok(None)
}
pub fn spawn_background_clean(root: &Path, skip_id: Option<&str>) {
let res: Result<(), std::io::Error> = (|| {
let wt_dir = root.join(".wt");
std::fs::create_dir_all(&wt_dir)?;
let log_file = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(wt_dir.join("clean.log"))?;
let stderr_file = log_file.try_clone()?;
let exe = std::env::current_exe()?;
let mut cmd = std::process::Command::new(exe);
cmd.arg("clean").arg("--quiet");
if let Some(id) = skip_id {
cmd.arg("--skip").arg(id);
}
cmd.current_dir(root)
.env_remove(blyte_agent::shell::MODEL_SHELL_ENV)
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::from(log_file))
.stderr(std::process::Stdio::from(stderr_file));
let _child = cmd.spawn()?;
Ok(())
})();
if let Err(e) = res {
eprintln!("warning: could not start the background clean: {e}");
}
}
pub fn clean_on_review(root: &Path, id: &str) {
let wt_path = root.join(".wt").join(id);
if !wt_path.exists() {
spawn_background_clean(root, Some(id));
return;
}
let mut ctx = CleanContext::new(root);
let branch_name = format!("wip/{id}");
let branch_exists = ctx.get_branch_tip(&branch_name).is_some();
let verdict_path = root.join(".wt").join(format!("{id}.verdict.json"));
let verdict_str = match read_verdict_file(&verdict_path) {
Ok(Some(v)) => v,
Ok(None) => String::new(),
Err(err) => {
eprintln!("error: {err}");
spawn_background_clean(root, Some(id));
return;
}
};
let is_res = ctx.is_research_run(id);
let removal_reason = match ctx.check_removable(id, 14) {
Ok(r) if is_res || !has_uncommitted_changes(&wt_path) => Some(r),
Err(err @ (KeptReason::UnreadableVerdict(_) | KeptReason::UnreadableChildState(_))) => {
eprintln!("error: {err}");
spawn_background_clean(root, Some(id));
return;
}
_ => None,
};
let Some(removal_reason) = removal_reason else {
if verdict_str == "accepted" || verdict_str == "fixed" {
println!("worktree .wt/{id} kept until {branch_name} is merged");
}
spawn_background_clean(root, Some(id));
return;
};
if removal_reason == RemovalReason::ResearchReportInWorktree {
let src = wt_path.join("report.md");
let dst = root.join(".wt").join(format!("{id}.report.md"));
if let Err(err) = std::fs::copy(&src, &dst) {
eprintln!(
"error: could not copy {} to {}: {err}",
src.display(),
dst.display()
);
spawn_background_clean(root, Some(id));
return;
}
}
let had_prior_record = crate::removal_record::path(root, id).exists();
if let Err(err) = crate::removal_record::record_removal(root, id, &removal_reason) {
eprintln!("error: could not write removal record for {id}: {err}");
spawn_background_clean(root, Some(id));
return;
}
let removed_ok = if is_res {
std::fs::remove_dir_all(&wt_path).is_ok()
} else {
let rm_out = std::process::Command::new("git")
.args(["worktree", "remove", wt_path.to_str().unwrap_or("")])
.current_dir(root)
.output();
let _ = std::process::Command::new("git")
.args(["worktree", "prune"])
.current_dir(root)
.output();
rm_out.map(|o| o.status.success()).unwrap_or(false)
};
if !removed_ok {
if !had_prior_record {
let _ = std::fs::remove_file(crate::removal_record::path(root, id));
}
if verdict_str == "accepted" || verdict_str == "fixed" {
println!("worktree .wt/{id} kept until {branch_name} is merged");
}
spawn_background_clean(root, Some(id));
return;
}
if branch_exists {
let is_merged = if matches!(
removal_reason,
RemovalReason::Merged | RemovalReason::MergedInto(_) | RemovalReason::MergedThrough(_)
) {
true
} else {
match ctx.check_run_merged(id) {
Ok(Some(_)) => true,
Ok(None) => false,
Err(err) => {
eprintln!("error: {err}");
false
}
}
};
if is_merged {
let del_out = std::process::Command::new("git")
.args(["branch", "-D", &branch_name])
.current_dir(root)
.output();
if del_out.map(|o| o.status.success()).unwrap_or(false) {
ctx.wip_branch_tips.remove(&branch_name);
println!("removed .wt/{id}; branch {branch_name} deleted");
} else {
println!("removed .wt/{id}; branch {branch_name} kept");
}
} else {
println!("removed .wt/{id}; branch {branch_name} kept");
}
} else {
println!("removed .wt/{id}");
}
spawn_background_clean(root, Some(id));
}
#[cfg(test)]
mod tests {
use super::{run_clean_surfaces_at, unix_secs_from_system_time};
use std::time::{Duration, UNIX_EPOCH};
#[test]
fn unix_secs_from_system_time_rejects_pre_epoch_time() {
let pre_epoch = UNIX_EPOCH
.checked_sub(Duration::from_secs(1))
.expect("pre-epoch SystemTime");
let err = unix_secs_from_system_time(pre_epoch)
.expect_err("expected error for time before UNIX_EPOCH");
assert!(
err.contains("UNIX_EPOCH"),
"error should name UNIX_EPOCH: {err}"
);
}
#[test]
fn unix_secs_from_system_time_accepts_post_epoch_time() {
let ts = UNIX_EPOCH + Duration::from_secs(1_800_000_000);
assert_eq!(unix_secs_from_system_time(ts), Ok(1_800_000_000));
}
#[test]
fn run_clean_surfaces_at_reports_error_on_pre_epoch_time() {
let tmp = tempfile::tempdir().expect("tempdir");
let pre_epoch = UNIX_EPOCH
.checked_sub(Duration::from_secs(1))
.expect("pre-epoch SystemTime");
let had_errors = run_clean_surfaces_at(tmp.path(), 14, false, true, pre_epoch);
assert!(had_errors, "pre-epoch system clock must set had_errors");
}
}