Skip to main content

blyte_cli/
clean.rs

1//! Worktree cleanup for finished runs: `blyte clean`, on review, and at dispatch.
2
3use std::collections::{HashMap, HashSet};
4use std::path::{Path, PathBuf};
5
6#[derive(Debug, PartialEq, Eq, Clone)]
7pub enum RemovalReason {
8    Merged,
9    MergedInto(String),
10    MergedThrough(String),
11    SessionMerged(String),
12    Verdict(String),
13    NoChanges,
14    ResearchReport,
15    ResearchReportInWorktree,
16    ResearchEndedWithoutReport(String),
17    ResearchStoppedWithoutSummary(u64),
18    OlderThan(u64),
19}
20
21impl std::fmt::Display for RemovalReason {
22    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
23        match self {
24            Self::Merged => write!(f, "merged"),
25            Self::MergedInto(base) => write!(f, "merged into {base}"),
26            Self::MergedThrough(child) => write!(f, "merged through {child}"),
27            Self::SessionMerged(branch) => write!(f, "{branch} merged"),
28            Self::Verdict(v) => {
29                if v.is_empty() {
30                    write!(f, "verdict")
31                } else {
32                    write!(f, "verdict {v}")
33                }
34            }
35            Self::NoChanges => write!(f, "no changes"),
36            Self::ResearchReport => write!(f, "research report"),
37            Self::ResearchReportInWorktree => {
38                write!(f, "research report (copied out on removal)")
39            }
40            Self::ResearchEndedWithoutReport(outcome) => {
41                write!(f, "research run ended without a report ({outcome})")
42            }
43            Self::ResearchStoppedWithoutSummary(d) => {
44                write!(
45                    f,
46                    "research run stopped without a summary, started more than {d} days ago"
47                )
48            }
49            Self::OlderThan(d) => write!(f, "finished over {d} days ago"),
50        }
51    }
52}
53
54#[derive(Debug, PartialEq, Eq)]
55pub enum KeptReason {
56    UncommittedChanges,
57    Running,
58    NoVerdict,
59    NotMergedYet,
60    NoReport,
61    UnreadableSummary,
62    InUse,
63    CannotCheckInUse(String),
64    UsedRecently(u64),
65    HoldsRuns(String),
66    Custom(String),
67}
68
69impl std::fmt::Display for KeptReason {
70    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
71        match self {
72            Self::UncommittedChanges => write!(f, "uncommitted changes"),
73            Self::Running => write!(f, "running"),
74            Self::NoVerdict => write!(f, "no verdict"),
75            Self::NotMergedYet => write!(f, "not merged yet"),
76            Self::NoReport => write!(f, "no report"),
77            Self::UnreadableSummary => write!(f, "unreadable summary"),
78            Self::InUse => write!(f, "in use by a running process"),
79            Self::CannotCheckInUse(err) => {
80                write!(f, "cannot tell whether it is in use: {err}")
81            }
82            Self::UsedRecently(d) => write!(f, "used in the last {d} days"),
83            Self::HoldsRuns(path) => write!(f, "holds runs: review them from {path}"),
84            Self::Custom(s) => write!(f, "{s}"),
85        }
86    }
87}
88
89/// Recursively computes directory size in bytes without following symlinks.
90pub fn dir_size(path: &Path) -> u64 {
91    let mut total = 0;
92    let Ok(meta) = std::fs::symlink_metadata(path) else {
93        return 0;
94    };
95    if meta.file_type().is_symlink() {
96        return 0;
97    }
98    if meta.is_file() {
99        return meta.len();
100    }
101    if meta.is_dir() {
102        let Ok(entries) = std::fs::read_dir(path) else {
103            return 0;
104        };
105        for entry in entries.flatten() {
106            let Ok(ft) = entry.file_type() else {
107                continue;
108            };
109            if ft.is_symlink() {
110                continue;
111            } else if ft.is_dir() {
112                total += dir_size(&entry.path());
113            } else if ft.is_file() {
114                if let Ok(m) = entry.metadata() {
115                    total += m.len();
116                }
117            }
118        }
119    }
120    total
121}
122
123/// Formats byte count into human-readable representation: e.g. "812 MB", "12.3 GB".
124pub fn format_size(bytes: u64) -> String {
125    const KB: f64 = 1024.0;
126    const MB: f64 = 1024.0 * 1024.0;
127    const GB: f64 = 1024.0 * 1024.0 * 1024.0;
128    let b = bytes as f64;
129    let (val, unit) = if b >= GB {
130        (b / GB, "GB")
131    } else if b >= MB {
132        (b / MB, "MB")
133    } else if b >= KB {
134        (b / KB, "KB")
135    } else {
136        return format!("{bytes} B");
137    };
138
139    let s = if val >= 100.0 {
140        format!("{val:.0}")
141    } else {
142        let formatted = format!("{val:.1}");
143        formatted
144            .strip_suffix(".0")
145            .unwrap_or(&formatted)
146            .to_string()
147    };
148    format!("{s} {unit}")
149}
150
151/// Checks whether a process with the given PID is alive.
152pub fn is_pid_alive(pid: i64) -> bool {
153    if pid <= 0 {
154        return false;
155    }
156    let ret = unsafe { libc::kill(pid as libc::pid_t, 0) };
157    if ret == 0 {
158        true
159    } else {
160        std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
161    }
162}
163
164/// Finds the root repository (resolving the main checkout if inside a linked worktree).
165pub fn find_repo_root() -> Result<PathBuf, String> {
166    let out = std::process::Command::new("git")
167        .args(["rev-parse", "--show-toplevel"])
168        .output()
169        .map_err(|e| format!("git not found: {e}"))?;
170    if !out.status.success() {
171        return Err("not a git repository".to_string());
172    }
173    let root = PathBuf::from(String::from_utf8_lossy(&out.stdout).trim());
174    // A linked worktree has its own git dir apart from the shared one. A submodule also has a
175    // `.git` file, but its git dir is the common dir, so it is its own main checkout.
176    let dirs = std::process::Command::new("git")
177        .args([
178            "rev-parse",
179            "--path-format=absolute",
180            "--git-dir",
181            "--git-common-dir",
182        ])
183        .current_dir(&root)
184        .output()
185        .map_err(|e| format!("git not found: {e}"))?;
186    if !dirs.status.success() {
187        return Err(format!(
188            "cannot read the git dirs of {}: {}",
189            root.display(),
190            String::from_utf8_lossy(&dirs.stderr).trim()
191        ));
192    }
193    let dirs = String::from_utf8_lossy(&dirs.stdout);
194    let mut lines = dirs.lines();
195    let (Some(git_dir), Some(common_dir)) = (lines.next(), lines.next()) else {
196        return Err(format!("cannot read the git dirs of {}", root.display()));
197    };
198    if git_dir != common_dir {
199        crate::config::main_checkout(&root).ok_or_else(|| {
200            format!(
201                "cannot find main checkout for linked worktree {}",
202                root.display()
203            )
204        })
205    } else {
206        Ok(root)
207    }
208}
209
210/// Checks whether a run is a research run from its start file.
211pub fn is_research(root: &Path, id: &str) -> bool {
212    let start_path = root.join(".wt").join(format!("{id}.start.json"));
213    if let Ok(s) = std::fs::read_to_string(&start_path) {
214        if let Ok(val) = serde_json::from_str::<serde_json::Value>(&s) {
215            return val
216                .get("research")
217                .and_then(|r| r.as_bool())
218                .unwrap_or(false);
219        }
220    }
221    false
222}
223
224/// Checks whether a worktree has uncommitted changes via `git status --porcelain`.
225pub fn has_uncommitted_changes(wt_path: &Path) -> bool {
226    let out = std::process::Command::new("git")
227        .args([
228            "-C",
229            wt_path.to_str().unwrap_or(""),
230            "status",
231            "--porcelain",
232        ])
233        .output();
234    match out {
235        Ok(o) if o.status.success() => {
236            !o.stdout.is_empty() && !String::from_utf8_lossy(&o.stdout).trim().is_empty()
237        }
238        _ => true,
239    }
240}
241
242fn git_tree_sha(root: &Path, ref_name: &str) -> Option<String> {
243    let out = std::process::Command::new("git")
244        .args(["rev-parse", &format!("{ref_name}^{{tree}}")])
245        .current_dir(root)
246        .output()
247        .ok()?;
248    if out.status.success() {
249        Some(String::from_utf8_lossy(&out.stdout).trim().to_string())
250    } else {
251        None
252    }
253}
254
255fn is_cherry_merged_into_target(root: &Path, commit_sha: &str, target: &str) -> bool {
256    let cherry_out = std::process::Command::new("git")
257        .args(["cherry", target, commit_sha])
258        .current_dir(root)
259        .output();
260    if let Ok(o) = cherry_out {
261        if o.status.success() {
262            let s = String::from_utf8_lossy(&o.stdout);
263            let lines: Vec<&str> = s
264                .lines()
265                .map(|l| l.trim())
266                .filter(|l| !l.is_empty())
267                .collect();
268            if !lines.is_empty() && lines.iter().all(|l| l.starts_with('-')) {
269                return true;
270            }
271        }
272    }
273    false
274}
275
276fn is_merge_tree_merged_into_target(
277    root: &Path,
278    commit_sha: &str,
279    target: &str,
280    target_tree: Option<&str>,
281) -> bool {
282    let target_tree_sha = match target_tree {
283        Some(t) => Some(t.to_string()),
284        None => git_tree_sha(root, target),
285    };
286    if let Some(target_tree_sha) = target_tree_sha {
287        let merge_tree_out = std::process::Command::new("git")
288            .args(["merge-tree", "--write-tree", target, commit_sha])
289            .current_dir(root)
290            .output();
291        if let Ok(mt_o) = merge_tree_out {
292            if mt_o.status.success() {
293                let mt_stdout = String::from_utf8_lossy(&mt_o.stdout);
294                if let Some(first_line) = mt_stdout.lines().next() {
295                    if first_line.trim() == target_tree_sha {
296                        return true;
297                    }
298                }
299            }
300        }
301    }
302    false
303}
304
305fn parse_started_at(val: &serde_json::Value) -> Option<u64> {
306    let s = val.get("started_at")?;
307    if let Some(n) = s.as_u64() {
308        Some(n)
309    } else if let Some(n) = s.as_i64() {
310        if n >= 0 {
311            Some(n as u64)
312        } else {
313            None
314        }
315    } else if let Some(f) = s.as_f64() {
316        if f >= 0.0 {
317            Some(f as u64)
318        } else {
319            None
320        }
321    } else if let Some(st) = s.as_str() {
322        st.parse::<u64>().ok()
323    } else {
324        None
325    }
326}
327
328fn check_history_merged(
329    root: &Path,
330    tip_sha: &str,
331    target: &str,
332    started_at: Option<&serde_json::Value>,
333) -> bool {
334    let mb_out = std::process::Command::new("git")
335        .args(["merge-base", target, tip_sha])
336        .current_dir(root)
337        .output();
338    let Ok(mb_o) = mb_out else {
339        return false;
340    };
341    if !mb_o.status.success() {
342        return false;
343    }
344    let merge_base = String::from_utf8_lossy(&mb_o.stdout).trim().to_string();
345    if merge_base.is_empty() {
346        return false;
347    }
348
349    let diff_out = std::process::Command::new("git")
350        .args(["diff", "--name-only", &merge_base, tip_sha])
351        .current_dir(root)
352        .output();
353    let Ok(diff_o) = diff_out else {
354        return false;
355    };
356    if !diff_o.status.success() {
357        return false;
358    }
359    let files: Vec<String> = String::from_utf8_lossy(&diff_o.stdout)
360        .lines()
361        .map(|l| l.trim().to_string())
362        .filter(|l| !l.is_empty())
363        .collect();
364
365    if files.is_empty() {
366        return false;
367    }
368
369    let since_arg = started_at
370        .and_then(|v| {
371            if let Some(n) = v.as_i64() {
372                if n >= 100_000_000 {
373                    Some(format!("--since={n}"))
374                } else {
375                    Some("--since=1970-01-01T00:00:00Z".to_string())
376                }
377            } else if let Some(n) = v.as_u64() {
378                if n >= 100_000_000 {
379                    Some(format!("--since={n}"))
380                } else {
381                    Some("--since=1970-01-01T00:00:00Z".to_string())
382                }
383            } else {
384                v.as_str().map(|s| format!("--since={s}"))
385            }
386        })
387        .unwrap_or_else(|| "--since=1970-01-01T00:00:00Z".to_string());
388
389    let mut cmd = std::process::Command::new("git");
390    cmd.args([
391        "rev-list",
392        "--first-parent",
393        &since_arg,
394        "-n",
395        "20",
396        target,
397        "--",
398    ]);
399    for f in &files {
400        cmd.arg(f);
401    }
402    cmd.current_dir(root);
403    let Ok(rev_o) = cmd.output() else {
404        return false;
405    };
406    if !rev_o.status.success() {
407        return false;
408    }
409
410    let commits: Vec<String> = String::from_utf8_lossy(&rev_o.stdout)
411        .lines()
412        .map(|l| l.trim().to_string())
413        .filter(|l| !l.is_empty())
414        .collect();
415
416    for c in commits {
417        let mt_out = std::process::Command::new("git")
418            .args(["merge-tree", "--write-tree", &c, tip_sha])
419            .current_dir(root)
420            .output();
421        let Ok(mt_o) = mt_out else {
422            continue;
423        };
424        if !mt_o.status.success() {
425            continue;
426        }
427        let mt_stdout = String::from_utf8_lossy(&mt_o.stdout);
428        let Some(first_line) = mt_stdout.lines().next() else {
429            continue;
430        };
431        let mt_tree = first_line.trim();
432
433        if let Some(c_tree) = git_tree_sha(root, &c) {
434            if mt_tree == c_tree {
435                return true;
436            }
437        }
438    }
439
440    false
441}
442
443/// Context for cleaning a repository, caching metadata to avoid redundant git calls and disk reads.
444pub struct CleanContext<'a> {
445    pub root: &'a Path,
446    pub start_files: HashMap<String, serde_json::Value>,
447    pub all_run_ids: Vec<String>,
448    pub wip_branch_tips: HashMap<String, String>,
449    pub default_branch: String,
450    pub origin_default: Option<String>,
451    pub default_tree: Option<String>,
452    pub origin_default_tree: Option<String>,
453    pub wip_contains_cache: HashMap<String, Vec<String>>,
454    pub merged_cache: HashMap<String, Option<RemovalReason>>,
455    pub branch_contains_calls: usize,
456    pub cherry_pick_set: Option<HashSet<String>>,
457    pub rev_list_cache: HashMap<String, Vec<String>>,
458    pub ancestor_cache: HashMap<(String, String), bool>,
459}
460
461impl<'a> CleanContext<'a> {
462    pub fn new(root: &'a Path) -> Self {
463        let mut start_files = HashMap::new();
464        let mut all_run_ids = Vec::new();
465        let wt_dir = root.join(".wt");
466        if let Ok(entries) = std::fs::read_dir(&wt_dir) {
467            for entry in entries.flatten() {
468                let name = entry.file_name().to_string_lossy().to_string();
469                if let Some(id) = name.strip_suffix(".start.json") {
470                    all_run_ids.push(id.to_string());
471                    if let Ok(content) = std::fs::read_to_string(entry.path()) {
472                        if let Ok(val) = serde_json::from_str::<serde_json::Value>(&content) {
473                            start_files.insert(id.to_string(), val);
474                        }
475                    }
476                }
477            }
478        }
479        all_run_ids.sort();
480
481        let mut wip_branch_tips = HashMap::new();
482        let ref_out = std::process::Command::new("git")
483            .args([
484                "for-each-ref",
485                "--format=%(refname:short) %(objectname)",
486                "refs/heads/wip/",
487            ])
488            .current_dir(root)
489            .output();
490        if let Ok(o) = ref_out {
491            if o.status.success() {
492                for line in String::from_utf8_lossy(&o.stdout).lines() {
493                    let mut parts = line.split_whitespace();
494                    if let (Some(refname), Some(sha)) = (parts.next(), parts.next()) {
495                        wip_branch_tips.insert(refname.to_string(), sha.to_string());
496                    }
497                }
498            }
499        }
500
501        let default_branch = find_default_branch(root);
502        let name = default_branch
503            .strip_prefix("origin/")
504            .unwrap_or(&default_branch);
505        let remote = format!("origin/{name}");
506        let origin_default = if remote != default_branch
507            && git_ok(root, &["rev-parse", "--verify", "--quiet", &remote])
508        {
509            Some(remote)
510        } else {
511            None
512        };
513
514        let default_tree = git_tree_sha(root, &default_branch);
515        let origin_default_tree = origin_default
516            .as_deref()
517            .and_then(|r| git_tree_sha(root, r));
518
519        Self {
520            root,
521            start_files,
522            all_run_ids,
523            wip_branch_tips,
524            default_branch,
525            origin_default,
526            default_tree,
527            origin_default_tree,
528            wip_contains_cache: HashMap::new(),
529            merged_cache: HashMap::new(),
530            branch_contains_calls: 0,
531            cherry_pick_set: None,
532            rev_list_cache: HashMap::new(),
533            ancestor_cache: HashMap::new(),
534        }
535    }
536
537    fn compute_cherry_pick_set(&self) -> HashSet<String> {
538        let unremoved_ids = find_blyte_worktrees(self.root);
539        let candidate_ids: &[String] = if unremoved_ids.is_empty() {
540            &self.all_run_ids
541        } else {
542            &unremoved_ids
543        };
544
545        let mut min_started_at: Option<u64> = None;
546        let mut all_valid = true;
547
548        for id in candidate_ids {
549            let start_val = self.start_files.get(id);
550            let parsed = start_val.and_then(parse_started_at);
551            match parsed {
552                Some(ts) => {
553                    min_started_at = Some(min_started_at.map_or(ts, |m| m.min(ts)));
554                }
555                None => {
556                    all_valid = false;
557                }
558            }
559        }
560
561        let since_arg = if let (true, Some(min_ts)) = (all_valid, min_started_at) {
562            if min_ts >= 86_400 + 100_000_000 {
563                format!("--since={}", min_ts - 86_400)
564            } else {
565                "--since=1970-01-01T00:00:00Z".to_string()
566            }
567        } else {
568            "--since=1970-01-01T00:00:00Z".to_string()
569        };
570
571        let mut targets = Vec::new();
572        let mut seen = HashSet::new();
573
574        if git_ok(
575            self.root,
576            &["rev-parse", "--verify", "--quiet", &self.default_branch],
577        ) && seen.insert(self.default_branch.clone())
578        {
579            targets.push(self.default_branch.clone());
580        }
581
582        if let Some(ref origin_def) = self.origin_default {
583            if git_ok(self.root, &["rev-parse", "--verify", "--quiet", origin_def])
584                && seen.insert(origin_def.clone())
585            {
586                targets.push(origin_def.clone());
587            }
588        }
589
590        for id in &self.all_run_ids {
591            if let Some(base_str) = self
592                .start_files
593                .get(id)
594                .and_then(|s| s.get("base"))
595                .and_then(|b| b.as_str())
596            {
597                if let Some((_, base_targets)) = resolve_base_targets(self.root, base_str) {
598                    for bt in base_targets {
599                        if seen.insert(bt.clone()) {
600                            targets.push(bt);
601                        }
602                    }
603                }
604            }
605        }
606
607        if targets.is_empty() {
608            return HashSet::new();
609        }
610
611        let mut cmd = std::process::Command::new("git");
612        cmd.args(["log", "--format=%B", &since_arg]);
613        for t in &targets {
614            cmd.arg(t);
615        }
616        cmd.current_dir(self.root);
617
618        let mut set = HashSet::new();
619        if let Ok(o) = cmd.output() {
620            if o.status.success() {
621                let text = String::from_utf8_lossy(&o.stdout);
622                for line in text.lines() {
623                    let trimmed = line.trim();
624                    if let Some(rest) = trimmed.strip_prefix("(cherry picked from commit ") {
625                        if let Some(sha) = rest.strip_suffix(')') {
626                            let sha = sha.trim();
627                            if is_commit_id(sha) {
628                                set.insert(sha.to_lowercase());
629                            }
630                        }
631                    }
632                }
633            }
634        }
635
636        set
637    }
638
639    pub fn get_cherry_pick_set(&mut self) -> &HashSet<String> {
640        if self.cherry_pick_set.is_none() {
641            let set = self.compute_cherry_pick_set();
642            self.cherry_pick_set = Some(set);
643        }
644        self.cherry_pick_set.as_ref().unwrap()
645    }
646
647    fn is_ancestor_of_target(&mut self, commit_sha: &str, target: &str) -> bool {
648        let key = (commit_sha.to_string(), target.to_string());
649        if let Some(&cached) = self.ancestor_cache.get(&key) {
650            return cached;
651        }
652        let is_anc = std::process::Command::new("git")
653            .args(["merge-base", "--is-ancestor", commit_sha, target])
654            .current_dir(self.root)
655            .output()
656            .map(|c| c.status.success())
657            .unwrap_or(false);
658        self.ancestor_cache.insert(key, is_anc);
659        is_anc
660    }
661
662    fn is_ancestor_of_default(&mut self, commit_sha: &str) -> bool {
663        let def = self.default_branch.clone();
664        if self.is_ancestor_of_target(commit_sha, &def) {
665            return true;
666        }
667        if let Some(origin_def) = self.origin_default.clone() {
668            if self.is_ancestor_of_target(commit_sha, &origin_def) {
669                return true;
670            }
671        }
672        false
673    }
674
675    fn get_run_commits_against_default(&mut self, tip_sha: &str) -> Vec<String> {
676        if let Some(cached) = self.rev_list_cache.get(tip_sha) {
677            return cached.clone();
678        }
679        let out = std::process::Command::new("git")
680            .args(["rev-list", &format!("{}..{}", self.default_branch, tip_sha)])
681            .current_dir(self.root)
682            .output();
683        let commits: Vec<String> = match out {
684            Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout)
685                .lines()
686                .map(|l| l.trim().to_lowercase())
687                .filter(|l| !l.is_empty())
688                .collect(),
689            _ => Vec::new(),
690        };
691        self.rev_list_cache
692            .insert(tip_sha.to_string(), commits.clone());
693        commits
694    }
695
696    fn is_in_cherry_pick_record(&mut self, tip_sha: &str) -> bool {
697        let commits = self.get_run_commits_against_default(tip_sha);
698        if commits.is_empty() {
699            return false;
700        }
701        let cherry_set = self.get_cherry_pick_set();
702        commits.iter().all(|c| cherry_set.contains(c))
703    }
704
705    pub fn get_branch_tip(&self, branch_name: &str) -> Option<String> {
706        if let Some(sha) = self.wip_branch_tips.get(branch_name) {
707            return Some(sha.clone());
708        }
709        get_branch_tip(self.root, branch_name)
710    }
711
712    pub fn is_research_run(&self, id: &str) -> bool {
713        self.start_files
714            .get(id)
715            .and_then(|v| v.get("research"))
716            .and_then(|r| r.as_bool())
717            .unwrap_or_else(|| is_research(self.root, id))
718    }
719
720    pub fn get_wip_branches_containing(&mut self, tip_sha: &str) -> Vec<String> {
721        if let Some(cached) = self.wip_contains_cache.get(tip_sha) {
722            return cached.clone();
723        }
724
725        self.branch_contains_calls += 1;
726
727        let out = std::process::Command::new("git")
728            .args([
729                "branch",
730                "--list",
731                "--format=%(refname:short)",
732                "wip/*",
733                "--contains",
734                tip_sha,
735            ])
736            .current_dir(self.root)
737            .output();
738
739        let mut branches = Vec::new();
740        if let Ok(o) = out {
741            if o.status.success() {
742                for line in String::from_utf8_lossy(&o.stdout).lines() {
743                    let trimmed = line.trim().trim_start_matches(['*', '+', ' ']).trim();
744                    if !trimmed.is_empty() {
745                        branches.push(trimmed.to_string());
746                    }
747                }
748            }
749        }
750        self.wip_contains_cache
751            .insert(tip_sha.to_string(), branches.clone());
752        branches
753    }
754
755    pub fn get_children_of(&mut self, id: &str, tip_sha: &str) -> Vec<String> {
756        let mut children = Vec::new();
757        let mut seen = HashSet::new();
758
759        // 1. Edges from base fields directly
760        for (candidate_id, start_val) in &self.start_files {
761            if candidate_id == id {
762                continue;
763            }
764            if let Some(base_str) = start_val.get("base").and_then(|v| v.as_str()) {
765                let base_str = base_str.trim().trim_end_matches('/');
766                let target1 = format!("wip/{id}");
767                let target2 = format!("refs/heads/wip/{id}");
768                if (base_str == target1 || base_str == target2) && seen.insert(candidate_id.clone())
769                {
770                    children.push(candidate_id.clone());
771                }
772            }
773        }
774
775        // 2. Edges for runs without base:
776        if !tip_sha.is_empty() {
777            let tip_sha_owned = tip_sha.to_string();
778            let containing_branches = self.get_wip_branches_containing(&tip_sha_owned);
779            for b in containing_branches {
780                let clean_b = b.strip_prefix("refs/heads/").unwrap_or(&b);
781                if let Some(candidate_id) = clean_b.strip_prefix("wip/") {
782                    if candidate_id == id {
783                        continue;
784                    }
785                    if !self.start_files.contains_key(candidate_id) {
786                        continue;
787                    }
788                    let has_base = self
789                        .start_files
790                        .get(candidate_id)
791                        .and_then(|val| val.get("base"))
792                        .is_some_and(|b| !b.is_null());
793                    if !has_base && seen.insert(candidate_id.to_string()) {
794                        children.push(candidate_id.to_string());
795                    }
796                }
797            }
798        }
799
800        children.sort();
801        children
802    }
803
804    pub fn is_child_run_merged(&mut self, child: &str, visited: &mut HashSet<String>) -> bool {
805        if self.is_research_run(child) {
806            return false;
807        }
808
809        let branch_name = format!("wip/{child}");
810        let tip = self.get_branch_tip(&branch_name);
811
812        if tip.is_none() {
813            let verdict_path = self.root.join(".wt").join(format!("{child}.verdict.json"));
814            let (has_accepted_verdict, is_redone) = if verdict_path.is_file() {
815                let v = std::fs::read_to_string(&verdict_path)
816                    .ok()
817                    .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
818                    .and_then(|v| {
819                        v.get("verdict")
820                            .and_then(|s| s.as_str())
821                            .map(|s| s.to_string())
822                    })
823                    .unwrap_or_default();
824                (v == "accepted" || v == "fixed", v == "redone")
825            } else {
826                (false, false)
827            };
828
829            if is_redone {
830                return false;
831            }
832
833            let summary_path = self.root.join(".wt").join(format!("{child}.json"));
834            let is_verified = std::fs::read_to_string(&summary_path)
835                .ok()
836                .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
837                .and_then(|v| {
838                    v.get("outcome")
839                        .and_then(|s| s.as_str())
840                        .map(|s| s == "verified")
841                })
842                .unwrap_or(false);
843
844            let wt_gone = !self.root.join(".wt").join(child).is_dir();
845
846            return has_accepted_verdict || (is_verified && wt_gone);
847        }
848
849        self.check_run_merged_internal(child, visited).is_some()
850    }
851
852    pub fn check_run_merged(&mut self, id: &str) -> Option<RemovalReason> {
853        let mut visited = HashSet::new();
854        self.check_run_merged_internal(id, &mut visited)
855    }
856
857    fn check_run_merged_internal(
858        &mut self,
859        id: &str,
860        visited: &mut HashSet<String>,
861    ) -> Option<RemovalReason> {
862        if visited.contains(id) {
863            return None;
864        }
865
866        if let Some(cached) = self.merged_cache.get(id) {
867            return cached.clone();
868        }
869
870        visited.insert(id.to_string());
871
872        let branch_name = format!("wip/{id}");
873        let tip_sha = self.get_branch_tip(&branch_name);
874
875        let result = self.decide_run_merged(id, tip_sha.as_deref(), visited);
876
877        visited.remove(id);
878
879        self.merged_cache.insert(id.to_string(), result.clone());
880        result
881    }
882
883    fn decide_run_merged(
884        &mut self,
885        id: &str,
886        tip_sha: Option<&str>,
887        visited: &mut HashSet<String>,
888    ) -> Option<RemovalReason> {
889        let base_opt = self.start_files.get(id).and_then(|s| {
890            s.get("base")
891                .and_then(|b| b.as_str())
892                .map(|b| b.to_string())
893        });
894        let base_targets = base_opt
895            .as_deref()
896            .and_then(|b| resolve_base_targets(self.root, b));
897        let started_at = self
898            .start_files
899            .get(id)
900            .and_then(|s| s.get("started_at"))
901            .cloned();
902
903        if let Some(tip_sha) = tip_sha {
904            // 1. Ancestor (merge-base --is-ancestor)
905            if self.is_ancestor_of_default(tip_sha) {
906                return Some(RemovalReason::Merged);
907            }
908
909            // 2. The cherry-pick record
910            if self.is_in_cherry_pick_record(tip_sha) {
911                return Some(RemovalReason::Merged);
912            }
913
914            // 3. The base-branch checks
915            if let Some((ref display_name, ref targets)) = base_targets {
916                for target in targets {
917                    if self.is_ancestor_of_target(tip_sha, target) {
918                        return Some(RemovalReason::MergedInto(display_name.clone()));
919                    }
920                    if is_cherry_merged_into_target(self.root, tip_sha, target) {
921                        return Some(RemovalReason::MergedInto(display_name.clone()));
922                    }
923                    if is_merge_tree_merged_into_target(self.root, tip_sha, target, None) {
924                        return Some(RemovalReason::MergedInto(display_name.clone()));
925                    }
926                }
927            }
928        }
929
930        // 4. The follow-up rule
931        let children = self.get_children_of(id, tip_sha.unwrap_or(""));
932        for child in children {
933            if visited.contains(&child) {
934                continue;
935            }
936            if self.is_child_run_merged(&child, visited) {
937                return Some(RemovalReason::MergedThrough(child));
938            }
939        }
940
941        if let Some(tip_sha) = tip_sha {
942            // 5. git cherry
943            if is_cherry_merged_into_target(self.root, tip_sha, &self.default_branch) {
944                return Some(RemovalReason::Merged);
945            }
946            if let Some(ref origin_def) = self.origin_default {
947                if is_cherry_merged_into_target(self.root, tip_sha, origin_def) {
948                    return Some(RemovalReason::Merged);
949                }
950            }
951
952            // 6. merge-tree against current tips
953            if is_merge_tree_merged_into_target(
954                self.root,
955                tip_sha,
956                &self.default_branch,
957                self.default_tree.as_deref(),
958            ) {
959                return Some(RemovalReason::Merged);
960            }
961            if let Some(ref origin_def) = self.origin_default {
962                if is_merge_tree_merged_into_target(
963                    self.root,
964                    tip_sha,
965                    origin_def,
966                    self.origin_default_tree.as_deref(),
967                ) {
968                    return Some(RemovalReason::Merged);
969                }
970            }
971
972            // 7. history walk (explicit blyte clean only)
973            if check_history_merged(
974                self.root,
975                tip_sha,
976                &self.default_branch,
977                started_at.as_ref(),
978            ) {
979                return Some(RemovalReason::Merged);
980            }
981            if let Some(ref origin_def) = self.origin_default {
982                if check_history_merged(self.root, tip_sha, origin_def, started_at.as_ref()) {
983                    return Some(RemovalReason::Merged);
984                }
985            }
986            if let Some((ref display_name, ref targets)) = base_targets {
987                for target in targets {
988                    if check_history_merged(self.root, tip_sha, target, started_at.as_ref()) {
989                        return Some(RemovalReason::MergedInto(display_name.clone()));
990                    }
991                }
992            }
993
994            // 8. squash-merge subject match
995            if let Some(reason) = self.squash_merged_reason(tip_sha, &base_targets) {
996                return Some(reason);
997            }
998        }
999
1000        None
1001    }
1002
1003    fn squash_merged_reason(
1004        &self,
1005        tip_sha: &str,
1006        base_targets: &Option<(String, Vec<String>)>,
1007    ) -> Option<RemovalReason> {
1008        if is_squash_merged_into_target(self.root, tip_sha, &self.default_branch) {
1009            return Some(RemovalReason::Merged);
1010        }
1011        if let Some(ref origin_def) = self.origin_default {
1012            if is_squash_merged_into_target(self.root, tip_sha, origin_def) {
1013                return Some(RemovalReason::Merged);
1014            }
1015        }
1016        if let Some((ref display_name, ref targets)) = base_targets {
1017            for target in targets {
1018                if is_squash_merged_into_target(self.root, tip_sha, target) {
1019                    return Some(RemovalReason::MergedInto(display_name.clone()));
1020                }
1021            }
1022        }
1023        None
1024    }
1025
1026    pub fn find_merged_followup(&mut self, id: &str) -> Option<String> {
1027        let branch_name = format!("wip/{id}");
1028        let tip_sha = self.get_branch_tip(&branch_name);
1029        let mut visited = HashSet::new();
1030        visited.insert(id.to_string());
1031        let children = self.get_children_of(id, tip_sha.as_deref().unwrap_or(""));
1032        children
1033            .into_iter()
1034            .find(|child| self.is_child_run_merged(child, &mut visited))
1035    }
1036
1037    pub fn check_removable(
1038        &mut self,
1039        id: &str,
1040        older_than_days: u64,
1041    ) -> Result<RemovalReason, KeptReason> {
1042        let wt_dir = self.root.join(".wt");
1043        let summary_path = wt_dir.join(format!("{id}.json"));
1044        let verdict_path = wt_dir.join(format!("{id}.verdict.json"));
1045        let report_path = wt_dir.join(format!("{id}.report.md"));
1046
1047        let start_json = self.start_files.get(id);
1048        let summary_exists = summary_path.is_file();
1049
1050        // Check if run is finished: no live process (pid not running) or a summary from this run exists.
1051        if let Some(start) = start_json {
1052            if let Some(pid) = start.get("pid").and_then(|p| p.as_i64()) {
1053                if is_pid_alive(pid) {
1054                    if !summary_exists {
1055                        return Err(KeptReason::Running);
1056                    }
1057                    let Some(started_at) = parse_started_at(start) else {
1058                        return Err(KeptReason::Running);
1059                    };
1060                    let summary_mtime = std::fs::metadata(&summary_path)
1061                        .ok()
1062                        .and_then(|m| m.modified().ok())
1063                        .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
1064                        .map(|d| d.as_secs());
1065                    if summary_mtime.is_none_or(|mtime| mtime < started_at) {
1066                        return Err(KeptReason::Running);
1067                    }
1068                }
1069            }
1070        }
1071
1072        let is_res = self.is_research_run(id);
1073
1074        // Rule 2: Discarded (the verdict is redone, or the outcome is no_changes)
1075        let verdict_str = if verdict_path.is_file() {
1076            std::fs::read_to_string(&verdict_path)
1077                .ok()
1078                .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
1079                .and_then(|v| {
1080                    v.get("verdict")
1081                        .and_then(|s| s.as_str())
1082                        .map(|s| s.to_string())
1083                })
1084                .unwrap_or_default()
1085        } else {
1086            String::new()
1087        };
1088
1089        if verdict_str == "redone" {
1090            return Ok(RemovalReason::Verdict("redone".to_string()));
1091        }
1092
1093        if summary_exists {
1094            if let Ok(summary_str) = std::fs::read_to_string(&summary_path) {
1095                if let Ok(val) = serde_json::from_str::<serde_json::Value>(&summary_str) {
1096                    if val.get("outcome").and_then(|o| o.as_str()) == Some("no_changes") {
1097                        return Ok(RemovalReason::NoChanges);
1098                    }
1099                }
1100            }
1101        }
1102
1103        // Rule 3: Research run and its report was copied out (.wt/<id>.report.md exists)
1104        if is_res && report_path.is_file() {
1105            return Ok(RemovalReason::ResearchReport);
1106        }
1107
1108        if is_res {
1109            let wt_report_path = wt_dir.join(id).join("report.md");
1110            if wt_report_path.is_file() && !report_path.is_file() {
1111                return Ok(RemovalReason::ResearchReportInWorktree);
1112            }
1113            if summary_exists {
1114                let outcome = std::fs::read_to_string(&summary_path)
1115                    .ok()
1116                    .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
1117                    .and_then(|v| {
1118                        v.get("outcome")
1119                            .and_then(|o| o.as_str())
1120                            .filter(|s| !s.is_empty())
1121                            .map(|s| s.to_string())
1122                    });
1123                return match outcome {
1124                    Some(outcome) => Ok(RemovalReason::ResearchEndedWithoutReport(outcome)),
1125                    None => Err(KeptReason::UnreadableSummary),
1126                };
1127            }
1128            let start_path = wt_dir.join(format!("{id}.start.json"));
1129            if let Ok(meta) = std::fs::metadata(&start_path) {
1130                if let Ok(mtime) = meta.modified() {
1131                    let age = std::time::SystemTime::now()
1132                        .duration_since(mtime)
1133                        .unwrap_or(std::time::Duration::ZERO);
1134                    if age >= std::time::Duration::from_secs(older_than_days.saturating_mul(86400))
1135                    {
1136                        return Ok(RemovalReason::ResearchStoppedWithoutSummary(
1137                            older_than_days,
1138                        ));
1139                    }
1140                }
1141            }
1142        }
1143
1144        // Rule 1: Merged (its work is on the default branch or base branch or follow-up)
1145        if !is_res {
1146            if let Some(reason) = self.check_run_merged(id) {
1147                return Ok(reason);
1148            }
1149        }
1150
1151        // Rule 4: Finished more than older_than days ago, by the summary file's mtime
1152        if summary_exists {
1153            if let Ok(meta) = std::fs::metadata(&summary_path) {
1154                if let Ok(mtime) = meta.modified() {
1155                    let age = std::time::SystemTime::now()
1156                        .duration_since(mtime)
1157                        .unwrap_or(std::time::Duration::ZERO);
1158                    if age >= std::time::Duration::from_secs(older_than_days.saturating_mul(86400))
1159                    {
1160                        return Ok(RemovalReason::OlderThan(older_than_days));
1161                    }
1162                }
1163            }
1164        }
1165
1166        // A verdict of accepted or fixed on its own no longer makes a worktree removable
1167        if !verdict_str.is_empty() {
1168            return Err(KeptReason::NotMergedYet);
1169        }
1170
1171        if is_res {
1172            Err(KeptReason::NoReport)
1173        } else {
1174            Err(KeptReason::NoVerdict)
1175        }
1176    }
1177}
1178
1179/// Evaluates whether a worktree is removable according to the clean rules.
1180pub fn check_removable(
1181    root: &Path,
1182    id: &str,
1183    older_than_days: u64,
1184) -> Result<RemovalReason, KeptReason> {
1185    let mut ctx = CleanContext::new(root);
1186    ctx.check_removable(id, older_than_days)
1187}
1188
1189/// Identifies the default branch (origin/HEAD's target, else main, else master).
1190pub fn find_default_branch(root: &Path) -> String {
1191    let sym_out = std::process::Command::new("git")
1192        .args(["symbolic-ref", "--short", "refs/remotes/origin/HEAD"])
1193        .current_dir(root)
1194        .output();
1195    if let Ok(o) = sym_out {
1196        if o.status.success() {
1197            let target = String::from_utf8_lossy(&o.stdout);
1198            let target = target.trim();
1199            let branch_name = target.strip_prefix("origin/").unwrap_or(target);
1200            let local_check = std::process::Command::new("git")
1201                .args([
1202                    "rev-parse",
1203                    "--verify",
1204                    &format!("refs/heads/{branch_name}"),
1205                ])
1206                .current_dir(root)
1207                .output();
1208            if local_check.map(|c| c.status.success()).unwrap_or(false) {
1209                return branch_name.to_string();
1210            }
1211            let remote_check = std::process::Command::new("git")
1212                .args(["rev-parse", "--verify", target])
1213                .current_dir(root)
1214                .output();
1215            if remote_check.map(|c| c.status.success()).unwrap_or(false) {
1216                return target.to_string();
1217            }
1218            return branch_name.to_string();
1219        }
1220    }
1221
1222    let main_check = std::process::Command::new("git")
1223        .args(["rev-parse", "--verify", "refs/heads/main"])
1224        .current_dir(root)
1225        .output();
1226    if main_check.map(|c| c.status.success()).unwrap_or(false) {
1227        return "main".to_string();
1228    }
1229
1230    let master_check = std::process::Command::new("git")
1231        .args(["rev-parse", "--verify", "refs/heads/master"])
1232        .current_dir(root)
1233        .output();
1234    if master_check.map(|c| c.status.success()).unwrap_or(false) {
1235        return "master".to_string();
1236    }
1237
1238    "main".to_string()
1239}
1240
1241/// Determines if a string is a commit SHA (hex-only, length 7 to 64).
1242fn is_commit_id(s: &str) -> bool {
1243    (s.len() >= 7 && s.len() <= 64) && s.chars().all(|c| c.is_ascii_hexdigit())
1244}
1245
1246/// Resolves candidate git refs for a run's base branch.
1247/// Returns (display_name, targets) if `base` is a branch name that resolves.
1248/// Returns None if `base` is not a branch name (e.g. HEAD, commit id, wip/ branch)
1249/// or if none of the candidate refs resolve in git.
1250pub fn resolve_base_targets(root: &Path, base: &str) -> Option<(String, Vec<String>)> {
1251    let base = base.trim();
1252    if base.is_empty() {
1253        return None;
1254    }
1255
1256    if base == "HEAD"
1257        || base.starts_with("HEAD~")
1258        || base.starts_with("HEAD^")
1259        || base.starts_with("HEAD@")
1260        || base.starts_with("HEAD:")
1261    {
1262        return None;
1263    }
1264
1265    if base == "FETCH_HEAD" || base == "ORIG_HEAD" || base == "MERGE_HEAD" {
1266        return None;
1267    }
1268
1269    if is_commit_id(base) {
1270        return None;
1271    }
1272
1273    let clean = if let Some(stripped) = base.strip_prefix("refs/heads/") {
1274        stripped
1275    } else if let Some(stripped) = base.strip_prefix("refs/remotes/") {
1276        stripped
1277    } else {
1278        base
1279    };
1280
1281    let is_wip = clean == "wip"
1282        || clean.starts_with("wip/")
1283        || clean == "origin/wip"
1284        || clean.starts_with("origin/wip/");
1285    if is_wip {
1286        return None;
1287    }
1288
1289    let (display_name, candidates) = if let Some(without_origin) = clean.strip_prefix("origin/") {
1290        if without_origin.is_empty()
1291            || without_origin == "wip"
1292            || without_origin.starts_with("wip/")
1293            || without_origin == "HEAD"
1294            || without_origin.starts_with("HEAD~")
1295            || without_origin.starts_with("HEAD^")
1296            || is_commit_id(without_origin)
1297        {
1298            return None;
1299        }
1300        let cand1 = format!("refs/remotes/{clean}");
1301        let cand2 = format!("refs/heads/{without_origin}");
1302        (without_origin.to_string(), vec![cand1, cand2])
1303    } else {
1304        let cand1 = format!("refs/heads/{clean}");
1305        let cand2 = format!("refs/remotes/origin/{clean}");
1306        (clean.to_string(), vec![cand1, cand2])
1307    };
1308
1309    let mut resolved = Vec::new();
1310    for cand in candidates {
1311        if git_ok(root, &["rev-parse", "--verify", "--quiet", &cand]) {
1312            resolved.push(cand);
1313        }
1314    }
1315
1316    if resolved.is_empty() {
1317        None
1318    } else {
1319        Some((display_name, resolved))
1320    }
1321}
1322
1323/// Reads `base` from `.wt/<id>.start.json` if present.
1324pub fn read_run_base(root: &Path, id: &str) -> Option<String> {
1325    let start_path = root.join(".wt").join(format!("{id}.start.json"));
1326    std::fs::read_to_string(&start_path)
1327        .ok()
1328        .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
1329        .and_then(|v| {
1330            v.get("base")
1331                .and_then(|b| b.as_str())
1332                .map(|s| s.to_string())
1333        })
1334}
1335
1336/// Returns the commit SHA at the tip of `branch_name` if it exists.
1337pub fn get_branch_tip(root: &Path, branch_name: &str) -> Option<String> {
1338    let check = std::process::Command::new("git")
1339        .args([
1340            "rev-parse",
1341            "--verify",
1342            &format!("refs/heads/{branch_name}"),
1343        ])
1344        .current_dir(root)
1345        .output()
1346        .ok()?;
1347    if !check.status.success() {
1348        return None;
1349    }
1350
1351    let tip_out = std::process::Command::new("git")
1352        .args(["rev-parse", &format!("refs/heads/{branch_name}")])
1353        .current_dir(root)
1354        .output()
1355        .ok()?;
1356    if tip_out.status.success() {
1357        Some(String::from_utf8_lossy(&tip_out.stdout).trim().to_string())
1358    } else {
1359        None
1360    }
1361}
1362
1363/// Checks whether a branch's work is on the default branch when any of:
1364/// - `git merge-base --is-ancestor <tip> <default>` succeeds;
1365/// - every commit `git cherry <default> <branch>` lists is marked `-`;
1366/// - merging it would change nothing: `git merge-tree --write-tree <default> <branch>` exits 0
1367///   and the tree id it prints (first line) equals `git rev-parse <default>^{tree}`;
1368/// - every commit's subject on <branch> appears as a whole line in the messages of <default>'s commits since the branch forked (a GitHub squash merge lists them).
1369pub fn is_branch_merged(root: &Path, branch_name: &str) -> bool {
1370    let mut ctx = CleanContext::new(root);
1371    if let Some(id) = branch_name.strip_prefix("wip/") {
1372        ctx.check_run_merged(id).is_some()
1373    } else {
1374        is_branch_merged_with_targets(root, branch_name, &[])
1375    }
1376}
1377
1378/// Checks whether a branch's work is on the default branch or any of the extra target refs.
1379pub fn is_branch_merged_with_targets(
1380    root: &Path,
1381    branch_name: &str,
1382    extra_targets: &[&str],
1383) -> bool {
1384    let Some(tip_sha) = get_branch_tip(root, branch_name) else {
1385        return false;
1386    };
1387
1388    is_commit_merged_with_targets(root, &tip_sha, extra_targets)
1389}
1390
1391/// Checks whether a branch's work is on the default branch or any of the extra target refs.
1392pub fn is_branch_merged_with_extra_targets(
1393    root: &Path,
1394    branch_name: &str,
1395    extra_targets: &[&str],
1396) -> bool {
1397    is_branch_merged_with_targets(root, branch_name, extra_targets)
1398}
1399
1400/// Checks whether a commit's work is on the default branch when any of:
1401/// - `git merge-base --is-ancestor <commit> <default>` succeeds;
1402/// - every commit `git cherry <default> <commit>` lists is marked `-`;
1403/// - merging it would change nothing: `git merge-tree --write-tree <default> <commit>` exits 0
1404///   and the tree id it prints equals `git rev-parse <default>^{tree}`.
1405pub fn is_commit_merged(root: &Path, commit_sha: &str) -> bool {
1406    is_commit_merged_with_targets(root, commit_sha, &[])
1407}
1408
1409/// Checks whether a commit's work is on the default branch or any of the extra target refs.
1410pub fn is_commit_merged_with_targets(
1411    root: &Path,
1412    commit_sha: &str,
1413    extra_targets: &[&str],
1414) -> bool {
1415    let default_branch = find_default_branch(root);
1416    // The local default branch can be far behind the remote one (1,292 commits in one repository,
1417    // 2026-10-01), so the remote-tracking branch, as of the last fetch, counts too.
1418    let name = default_branch
1419        .strip_prefix("origin/")
1420        .unwrap_or(&default_branch);
1421    let remote = format!("origin/{name}");
1422    let mut targets = vec![default_branch.clone()];
1423    if remote != default_branch && git_ok(root, &["rev-parse", "--verify", "--quiet", &remote]) {
1424        targets.push(remote);
1425    }
1426    for extra in extra_targets {
1427        if git_ok(root, &["rev-parse", "--verify", "--quiet", extra]) {
1428            targets.push(extra.to_string());
1429        }
1430    }
1431    targets
1432        .iter()
1433        .any(|target| merged_into(root, commit_sha, target))
1434}
1435
1436fn git_ok(root: &Path, args: &[&str]) -> bool {
1437    std::process::Command::new("git")
1438        .args(args)
1439        .current_dir(root)
1440        .output()
1441        .map(|o| o.status.success())
1442        .unwrap_or(false)
1443}
1444
1445/// Whether the commit's work is already on `default_branch`.
1446fn merged_into(root: &Path, commit_sha: &str, default_branch: &str) -> bool {
1447    // 1. `git merge-base --is-ancestor <tip> <default>` succeeds
1448    let ancestor_check = std::process::Command::new("git")
1449        .args(["merge-base", "--is-ancestor", commit_sha, default_branch])
1450        .current_dir(root)
1451        .output();
1452    if ancestor_check.map(|c| c.status.success()).unwrap_or(false) {
1453        return true;
1454    }
1455
1456    // 2. every commit `git cherry <default> <commit>` lists is marked `-`
1457    let cherry_out = std::process::Command::new("git")
1458        .args(["cherry", default_branch, commit_sha])
1459        .current_dir(root)
1460        .output();
1461    if let Ok(o) = cherry_out {
1462        if o.status.success() {
1463            let s = String::from_utf8_lossy(&o.stdout);
1464            let lines: Vec<&str> = s
1465                .lines()
1466                .map(|l| l.trim())
1467                .filter(|l| !l.is_empty())
1468                .collect();
1469            if !lines.is_empty() && lines.iter().all(|l| l.starts_with('-')) {
1470                return true;
1471            }
1472        }
1473    }
1474
1475    // 3. merging it would change nothing: `git merge-tree --write-tree <default> <commit>` exits 0
1476    // and the tree id it prints equals `git rev-parse <default>^{tree}`
1477    let default_tree_out = std::process::Command::new("git")
1478        .args(["rev-parse", &format!("{default_branch}^{{tree}}")])
1479        .current_dir(root)
1480        .output();
1481    if let Ok(tree_o) = default_tree_out {
1482        if tree_o.status.success() {
1483            let default_tree = String::from_utf8_lossy(&tree_o.stdout).trim().to_string();
1484            let merge_tree_out = std::process::Command::new("git")
1485                .args(["merge-tree", "--write-tree", default_branch, commit_sha])
1486                .current_dir(root)
1487                .output();
1488            if let Ok(mt_o) = merge_tree_out {
1489                if mt_o.status.success() {
1490                    let mt_stdout = String::from_utf8_lossy(&mt_o.stdout);
1491                    if let Some(first_line) = mt_stdout.lines().next() {
1492                        if first_line.trim() == default_tree {
1493                            return true;
1494                        }
1495                    }
1496                }
1497            }
1498        }
1499    }
1500
1501    // 4. every commit's subject on <commit> appears as a whole line in the messages of <default>'s
1502    // commits since the branch forked
1503    is_squash_merged_into_target(root, commit_sha, default_branch)
1504}
1505
1506fn is_squash_merged_into_target(root: &Path, commit_sha: &str, target: &str) -> bool {
1507    let mb_out = std::process::Command::new("git")
1508        .args(["merge-base", target, commit_sha])
1509        .current_dir(root)
1510        .output();
1511    let Ok(mb_o) = mb_out else {
1512        return false;
1513    };
1514    if !mb_o.status.success() {
1515        return false;
1516    }
1517    let base = String::from_utf8_lossy(&mb_o.stdout).trim().to_string();
1518    if base.is_empty() {
1519        return false;
1520    }
1521
1522    let subj_out = std::process::Command::new("git")
1523        .args([
1524            "log",
1525            "--no-merges",
1526            "--format=%s",
1527            &format!("{target}..{commit_sha}"),
1528        ])
1529        .current_dir(root)
1530        .output();
1531    let Ok(subj_o) = subj_out else {
1532        return false;
1533    };
1534    if !subj_o.status.success() {
1535        return false;
1536    }
1537    let subj_stdout = String::from_utf8_lossy(&subj_o.stdout);
1538    let subjects: Vec<&str> = subj_stdout
1539        .lines()
1540        .map(|l| l.trim())
1541        .filter(|l| !l.is_empty())
1542        .collect();
1543    if subjects.is_empty() {
1544        return false;
1545    }
1546
1547    let hay_out = std::process::Command::new("git")
1548        .args(["log", "--format=%B", &format!("{base}..{target}")])
1549        .current_dir(root)
1550        .output();
1551    let Ok(hay_o) = hay_out else {
1552        return false;
1553    };
1554    if !hay_o.status.success() {
1555        return false;
1556    }
1557    let hay_stdout = String::from_utf8_lossy(&hay_o.stdout);
1558    let mut haystack_lines = HashSet::new();
1559    for line in hay_stdout.lines() {
1560        let trimmed = line.trim();
1561        if trimmed.is_empty() {
1562            continue;
1563        }
1564        haystack_lines.insert(trimmed.to_string());
1565        if let Some(stripped) = trimmed
1566            .strip_prefix("* ")
1567            .or_else(|| trimmed.strip_prefix("- "))
1568        {
1569            let stripped = stripped.trim();
1570            if !stripped.is_empty() {
1571                haystack_lines.insert(stripped.to_string());
1572            }
1573        }
1574    }
1575
1576    subjects.iter().all(|s| haystack_lines.contains(*s))
1577}
1578
1579/// Lists all run IDs that have a corresponding `.wt/<id>.start.json`.
1580pub fn list_all_run_ids(root: &Path) -> Vec<String> {
1581    let wt_dir = root.join(".wt");
1582    let mut ids = Vec::new();
1583    if let Ok(entries) = std::fs::read_dir(&wt_dir) {
1584        for entry in entries.flatten() {
1585            let name = entry.file_name().to_string_lossy().to_string();
1586            if let Some(id) = name.strip_suffix(".start.json") {
1587                ids.push(id.to_string());
1588            }
1589        }
1590    }
1591    ids.sort();
1592    ids
1593}
1594
1595/// Finds a follow-up run that makes `<id>` merged.
1596pub fn find_merged_followup(root: &Path, id: &str) -> Option<String> {
1597    let mut ctx = CleanContext::new(root);
1598    ctx.find_merged_followup(id)
1599}
1600
1601/// Lists all `.wt/<id>` directories that have a corresponding `.wt/<id>.start.json`.
1602pub fn find_blyte_worktrees(root: &Path) -> Vec<String> {
1603    let wt_dir = root.join(".wt");
1604    if !wt_dir.is_dir() {
1605        return Vec::new();
1606    }
1607    let mut ids = Vec::new();
1608    if let Ok(entries) = std::fs::read_dir(&wt_dir) {
1609        for entry in entries.flatten() {
1610            if let Ok(ft) = entry.file_type() {
1611                if ft.is_dir() {
1612                    let name = entry.file_name().to_string_lossy().to_string();
1613                    let start_file = wt_dir.join(format!("{name}.start.json"));
1614                    if start_file.is_file() {
1615                        ids.push(name);
1616                    }
1617                }
1618            }
1619        }
1620    }
1621    ids.sort();
1622    ids
1623}
1624
1625#[derive(Debug, Default)]
1626pub struct CleanRepoStats {
1627    pub removed_worktrees: usize,
1628    pub freed_bytes: u64,
1629    pub had_errors: bool,
1630}
1631
1632/// Default idle threshold in days for session worktrees.
1633pub const DEFAULT_SESSION_IDLE_DAYS: u64 = 7;
1634
1635/// Parses `lsof -a -d cwd -Fn` output into a list of working directory paths.
1636pub fn parse_lsof_cwd_output(stdout: &str) -> Vec<PathBuf> {
1637    stdout
1638        .lines()
1639        .filter_map(|line| line.strip_prefix('n'))
1640        .filter(|path| !path.is_empty())
1641        .map(PathBuf::from)
1642        .collect()
1643}
1644
1645/// Lists the current working directories of all running processes via `lsof -a -d cwd -Fn`.
1646pub fn list_running_process_cwds() -> Result<Vec<PathBuf>, String> {
1647    let out = std::process::Command::new("lsof")
1648        .args(["-a", "-d", "cwd", "-Fn"])
1649        .output()
1650        .map_err(|e| e.to_string())?;
1651    // A failed lsof may have listed only some processes, so its output is not trusted.
1652    if !out.status.success() {
1653        let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string();
1654        if stderr.is_empty() {
1655            return Err(format!("lsof exited with {}", out.status));
1656        }
1657        return Err(format!("lsof exited with {}: {stderr}", out.status));
1658    }
1659    let paths = parse_lsof_cwd_output(&String::from_utf8_lossy(&out.stdout));
1660    if paths.is_empty() {
1661        return Err("lsof listed no working directories".to_string());
1662    }
1663    Ok(paths)
1664}
1665
1666/// Returns true if `wt_path` is a session worktree of `root`:
1667/// - directly under `<root>/.wt/` with no `<root>/.wt/<name>.start.json`, or
1668/// - under `<root>/.claude/worktrees/` (excluding any nested `.wt` run worktrees).
1669pub fn is_session_worktree(root: &Path, wt_path: &Path) -> bool {
1670    let root_canon = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
1671    let wt_canon = wt_path
1672        .canonicalize()
1673        .unwrap_or_else(|_| wt_path.to_path_buf());
1674    let Some(wt_parent) = wt_canon.parent() else {
1675        return false;
1676    };
1677    let Some(wt_name) = wt_canon.file_name().and_then(|n| n.to_str()) else {
1678        return false;
1679    };
1680
1681    let wt_dir_canon = root_canon
1682        .join(".wt")
1683        .canonicalize()
1684        .unwrap_or_else(|_| root_canon.join(".wt"));
1685    if wt_parent == wt_dir_canon {
1686        let start_file = wt_dir_canon.join(format!("{wt_name}.start.json"));
1687        return !start_file.is_file();
1688    }
1689
1690    let claude_wt_dir_canon = root_canon
1691        .join(".claude")
1692        .join("worktrees")
1693        .canonicalize()
1694        .unwrap_or_else(|_| root_canon.join(".claude").join("worktrees"));
1695    if let Ok(rel) = wt_canon.strip_prefix(&claude_wt_dir_canon) {
1696        if !rel.as_os_str().is_empty() && !has_wt_component(rel) {
1697            return true;
1698        }
1699    }
1700
1701    false
1702}
1703
1704/// Returns true if `<wt_path>/.wt/` contains any `*.start.json` file.
1705pub fn has_dispatched_runs(wt_path: &Path) -> bool {
1706    let wt_dir = wt_path.join(".wt");
1707    let Ok(entries) = std::fs::read_dir(&wt_dir) else {
1708        return false;
1709    };
1710    for entry in entries.flatten() {
1711        let name = entry.file_name();
1712        if name.to_string_lossy().ends_with(".start.json")
1713            && entry.file_type().map(|ft| ft.is_file()).unwrap_or(false)
1714        {
1715            return true;
1716        }
1717    }
1718    false
1719}
1720
1721/// Returns true if any process working directory in `cwds` is `wt_path` or a subdirectory of it.
1722/// Compares canonical paths.
1723pub fn is_worktree_in_use(wt_path: &Path, cwds: &[PathBuf]) -> bool {
1724    let wt_canon = wt_path
1725        .canonicalize()
1726        .unwrap_or_else(|_| wt_path.to_path_buf());
1727    cwds.iter().any(|cwd| {
1728        let cwd_canon = cwd.canonicalize().unwrap_or_else(|_| cwd.clone());
1729        cwd_canon.starts_with(&wt_canon)
1730    })
1731}
1732
1733/// Returns whether `index` and `HEAD` in the worktree's git admin directory
1734/// (`git -C <wt> rev-parse --absolute-git-dir`) are both more than `idle_days` days old.
1735/// Errors name what could not be read.
1736pub fn is_worktree_idle(wt_path: &Path, idle_days: u64) -> Result<bool, String> {
1737    let o = std::process::Command::new("git")
1738        .arg("-C")
1739        .arg(wt_path.as_os_str())
1740        .args(["rev-parse", "--absolute-git-dir"])
1741        .output()
1742        .map_err(|e| format!("cannot run git: {e}"))?;
1743    if !o.status.success() {
1744        return Err(format!(
1745            "git rev-parse --absolute-git-dir failed: {}",
1746            String::from_utf8_lossy(&o.stderr).trim()
1747        ));
1748    }
1749    let git_dir_str = String::from_utf8_lossy(&o.stdout).trim().to_string();
1750    if git_dir_str.is_empty() {
1751        return Err("git rev-parse --absolute-git-dir printed nothing".to_string());
1752    }
1753    let git_dir = PathBuf::from(git_dir_str);
1754    let now = std::time::SystemTime::now();
1755    let threshold = std::time::Duration::from_secs(idle_days.saturating_mul(86400));
1756    for name in ["index", "HEAD"] {
1757        let p = git_dir.join(name);
1758        let mtime = std::fs::metadata(&p)
1759            .and_then(|m| m.modified())
1760            .map_err(|e| format!("cannot read the time of {}: {e}", p.display()))?;
1761        let age = now
1762            .duration_since(mtime)
1763            .unwrap_or(std::time::Duration::ZERO);
1764        if idle_days > 0 && age <= threshold {
1765            return Ok(false);
1766        }
1767    }
1768    Ok(true)
1769}
1770
1771/// Evaluates whether a session worktree is removable.
1772pub fn check_session_worktree_removable(
1773    root: &Path,
1774    wt: &GitWorktreeInfo,
1775    cwds: &Result<Vec<PathBuf>, String>,
1776    idle_days: u64,
1777) -> Result<RemovalReason, KeptReason> {
1778    let is_merged = if let Some(ref branch) = wt.branch {
1779        is_branch_merged(root, branch)
1780    } else if let Some(ref sha) = wt.head_sha {
1781        is_commit_merged(root, sha)
1782    } else {
1783        false
1784    };
1785    if !is_merged {
1786        return Err(KeptReason::NotMergedYet);
1787    }
1788
1789    if has_dispatched_runs(&wt.path) {
1790        let display_path = display_worktree_path(&wt.path, root);
1791        return Err(KeptReason::HoldsRuns(display_path));
1792    }
1793
1794    if !is_worktree_clean(&wt.path) {
1795        return Err(KeptReason::UncommittedChanges);
1796    }
1797
1798    match cwds {
1799        Ok(list) => {
1800            if is_worktree_in_use(&wt.path, list) {
1801                return Err(KeptReason::InUse);
1802            }
1803        }
1804        Err(err) => {
1805            return Err(KeptReason::CannotCheckInUse(err.clone()));
1806        }
1807    }
1808
1809    match is_worktree_idle(&wt.path, idle_days) {
1810        Ok(true) => {}
1811        Ok(false) => return Err(KeptReason::UsedRecently(idle_days)),
1812        Err(e) => {
1813            return Err(KeptReason::Custom(format!(
1814                "cannot tell when it was last used: {e}"
1815            )))
1816        }
1817    }
1818
1819    let branch_label = wt.branch.clone().unwrap_or_else(|| {
1820        wt.head_sha
1821            .as_deref()
1822            .map(|s| s[..s.len().min(7)].to_string())
1823            .unwrap_or_else(|| "detached".to_string())
1824    });
1825    Ok(RemovalReason::SessionMerged(branch_label))
1826}
1827
1828fn branch_checked_out_elsewhere(
1829    worktrees: &[GitWorktreeInfo],
1830    removed_wt_paths: &HashSet<PathBuf>,
1831    current_wt_canon: &Path,
1832    branch_name: &str,
1833) -> bool {
1834    for wt in worktrees {
1835        if !wt.path.exists() {
1836            continue;
1837        }
1838        let wt_canon = wt
1839            .path
1840            .canonicalize()
1841            .unwrap_or_else(|_| wt.path.to_path_buf());
1842        if wt_canon == current_wt_canon || removed_wt_paths.contains(&wt_canon) {
1843            continue;
1844        }
1845        if wt.branch.as_deref() == Some(branch_name) {
1846            return true;
1847        }
1848    }
1849    false
1850}
1851
1852/// Cleans one repository.
1853pub fn clean_repo(
1854    root: &Path,
1855    older_than_days: u64,
1856    dry_run: bool,
1857    skip_id: Option<&str>,
1858    quiet: bool,
1859) -> CleanRepoStats {
1860    clean_repo_with_options(
1861        root,
1862        older_than_days,
1863        dry_run,
1864        skip_id,
1865        quiet,
1866        DEFAULT_SESSION_IDLE_DAYS,
1867        None,
1868    )
1869}
1870
1871/// Cleans one repository with configurable session worktree idle threshold and process cwd list.
1872pub fn clean_repo_with_options(
1873    root: &Path,
1874    older_than_days: u64,
1875    dry_run: bool,
1876    skip_id: Option<&str>,
1877    quiet: bool,
1878    session_idle_days: u64,
1879    process_cwds: Option<Result<Vec<PathBuf>, String>>,
1880) -> CleanRepoStats {
1881    let mut removed_worktrees = 0;
1882    let mut freed_bytes = 0;
1883    let mut had_errors = false;
1884
1885    let mut ctx = CleanContext::new(root);
1886    let ids = find_blyte_worktrees(root);
1887    for id in ids {
1888        if skip_id == Some(&id) {
1889            continue;
1890        }
1891
1892        let wt_path = root.join(".wt").join(&id);
1893        match ctx.check_removable(&id, older_than_days) {
1894            Err(kept_reason) => {
1895                if !quiet {
1896                    println!("kept .wt/{id} ({kept_reason})");
1897                }
1898            }
1899            Ok(removal_reason) => {
1900                let is_res = ctx.is_research_run(&id);
1901                if !is_res && has_uncommitted_changes(&wt_path) {
1902                    if !quiet {
1903                        println!("kept .wt/{id} (uncommitted changes)");
1904                    }
1905                    continue;
1906                }
1907
1908                let size = dir_size(&wt_path);
1909                let branch_name = format!("wip/{id}");
1910                let branch_exists = ctx.get_branch_tip(&branch_name).is_some();
1911                let is_merged = branch_exists
1912                    && (matches!(
1913                        removal_reason,
1914                        RemovalReason::Merged
1915                            | RemovalReason::MergedInto(_)
1916                            | RemovalReason::MergedThrough(_)
1917                    ) || ctx.check_run_merged(&id).is_some());
1918
1919                if dry_run {
1920                    if !quiet {
1921                        println!(
1922                            "would remove .wt/{id} ({removal_reason}, {})",
1923                            format_size(size)
1924                        );
1925                        if is_merged {
1926                            println!("would delete branch {branch_name} (merged)");
1927                        }
1928                    }
1929                    freed_bytes += size;
1930                    removed_worktrees += 1;
1931                } else {
1932                    if removal_reason == RemovalReason::ResearchReportInWorktree {
1933                        let src = wt_path.join("report.md");
1934                        let dst = root.join(".wt").join(format!("{id}.report.md"));
1935                        if let Err(err) = std::fs::copy(&src, &dst) {
1936                            eprintln!(
1937                                "error: could not copy {} to {}: {err}",
1938                                src.display(),
1939                                dst.display()
1940                            );
1941                            if !quiet {
1942                                println!("kept .wt/{id} (report copy failed)");
1943                            }
1944                            continue;
1945                        }
1946                    }
1947
1948                    let removed_ok = if is_res {
1949                        std::fs::remove_dir_all(&wt_path).is_ok()
1950                    } else {
1951                        let rm_out = std::process::Command::new("git")
1952                            .args(["worktree", "remove", wt_path.to_str().unwrap_or("")])
1953                            .current_dir(root)
1954                            .output();
1955                        let _ = std::process::Command::new("git")
1956                            .args(["worktree", "prune"])
1957                            .current_dir(root)
1958                            .output();
1959                        rm_out.map(|o| o.status.success()).unwrap_or(false)
1960                    };
1961
1962                    if removed_ok {
1963                        freed_bytes += size;
1964                        removed_worktrees += 1;
1965                        if !quiet {
1966                            println!("removed .wt/{id} ({removal_reason}, {})", format_size(size));
1967                        }
1968                        if is_merged {
1969                            let del_out = std::process::Command::new("git")
1970                                .args(["branch", "-D", &branch_name])
1971                                .current_dir(root)
1972                                .output();
1973                            if del_out.map(|o| o.status.success()).unwrap_or(false) {
1974                                ctx.wip_branch_tips.remove(&branch_name);
1975                                if !quiet {
1976                                    println!("deleted branch {branch_name} (merged)");
1977                                }
1978                            }
1979                        }
1980                    } else if !quiet {
1981                        println!("kept .wt/{id} (worktree remove failed)");
1982                    }
1983                }
1984            }
1985        }
1986    }
1987
1988    if !is_linked_worktree(root) {
1989        let all_worktrees = parse_worktree_list(root);
1990        let root_canon = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
1991        let main_canon = all_worktrees
1992            .first()
1993            .map(|wt| wt.path.canonicalize().unwrap_or_else(|_| wt.path.clone()));
1994
1995        let mut session_indices: Vec<(String, usize)> = all_worktrees
1996            .iter()
1997            .enumerate()
1998            .skip(1)
1999            .filter_map(|(idx, wt)| {
2000                if wt.is_bare || !wt.path.exists() {
2001                    return None;
2002                }
2003                let wt_canon = wt.path.canonicalize().unwrap_or_else(|_| wt.path.clone());
2004                if wt_canon == root_canon || Some(&wt_canon) == main_canon.as_ref() {
2005                    return None;
2006                }
2007                if !is_session_worktree(root, &wt.path) {
2008                    return None;
2009                }
2010                Some((display_worktree_path(&wt.path, root), idx))
2011            })
2012            .collect();
2013        session_indices.sort_by(|a, b| a.0.cmp(&b.0));
2014
2015        if !session_indices.is_empty() {
2016            let cwds = process_cwds.unwrap_or_else(list_running_process_cwds);
2017            let mut removed_wt_paths = HashSet::new();
2018
2019            for (display_path, idx) in session_indices {
2020                let wt = &all_worktrees[idx];
2021                let wt_canon = wt.path.canonicalize().unwrap_or_else(|_| wt.path.clone());
2022                match check_session_worktree_removable(root, wt, &cwds, session_idle_days) {
2023                    Err(kept_reason) => {
2024                        if !quiet {
2025                            println!("kept {display_path} ({kept_reason})");
2026                        }
2027                    }
2028                    Ok(removal_reason) => {
2029                        let size = dir_size(&wt.path);
2030                        if dry_run {
2031                            removed_wt_paths.insert(wt_canon.clone());
2032                            if !quiet {
2033                                println!(
2034                                    "would remove {display_path} ({removal_reason}, {})",
2035                                    format_size(size)
2036                                );
2037                                if let Some(ref branch_name) = wt.branch {
2038                                    if !branch_checked_out_elsewhere(
2039                                        &all_worktrees,
2040                                        &removed_wt_paths,
2041                                        &wt_canon,
2042                                        branch_name,
2043                                    ) && get_branch_tip(root, branch_name).is_some()
2044                                    {
2045                                        println!("would delete branch {branch_name} (merged)");
2046                                    }
2047                                }
2048                            }
2049                            freed_bytes += size;
2050                            removed_worktrees += 1;
2051                        } else {
2052                            let rm_out = std::process::Command::new("git")
2053                                .arg("worktree")
2054                                .arg("remove")
2055                                .arg(&wt.path)
2056                                .current_dir(root)
2057                                .output();
2058                            match rm_out {
2059                                Ok(o) if o.status.success() => {
2060                                    let _ = std::process::Command::new("git")
2061                                        .args(["worktree", "prune"])
2062                                        .current_dir(root)
2063                                        .output();
2064                                    removed_wt_paths.insert(wt_canon.clone());
2065                                    freed_bytes += size;
2066                                    removed_worktrees += 1;
2067                                    if !quiet {
2068                                        println!(
2069                                            "removed {display_path} ({removal_reason}, {})",
2070                                            format_size(size)
2071                                        );
2072                                    }
2073                                    if let Some(ref branch_name) = wt.branch {
2074                                        if !branch_checked_out_elsewhere(
2075                                            &all_worktrees,
2076                                            &removed_wt_paths,
2077                                            &wt_canon,
2078                                            branch_name,
2079                                        ) && get_branch_tip(root, branch_name).is_some()
2080                                        {
2081                                            let del_out = std::process::Command::new("git")
2082                                                .args(["branch", "-D", branch_name])
2083                                                .current_dir(root)
2084                                                .output();
2085                                            match del_out {
2086                                                Ok(o) if o.status.success() => {
2087                                                    ctx.wip_branch_tips.remove(branch_name);
2088                                                    if !quiet {
2089                                                        println!(
2090                                                            "deleted branch {branch_name} (merged)"
2091                                                        );
2092                                                    }
2093                                                }
2094                                                Ok(o) => {
2095                                                    eprintln!(
2096                                                        "error: could not delete branch {branch_name}: {}",
2097                                                        String::from_utf8_lossy(&o.stderr).trim()
2098                                                    );
2099                                                    had_errors = true;
2100                                                }
2101                                                Err(e) => {
2102                                                    eprintln!(
2103                                                        "error: could not delete branch {branch_name}: {e}"
2104                                                    );
2105                                                    had_errors = true;
2106                                                }
2107                                            }
2108                                        }
2109                                    }
2110                                }
2111                                Ok(o) => {
2112                                    let stderr =
2113                                        String::from_utf8_lossy(&o.stderr).trim().to_string();
2114                                    let stdout =
2115                                        String::from_utf8_lossy(&o.stdout).trim().to_string();
2116                                    let msg = if !stderr.is_empty() {
2117                                        stderr
2118                                    } else if !stdout.is_empty() {
2119                                        stdout
2120                                    } else {
2121                                        format!("exit status {}", o.status)
2122                                    };
2123                                    eprintln!("error: could not remove {display_path}: {msg}");
2124                                    had_errors = true;
2125                                }
2126                                Err(e) => {
2127                                    eprintln!("error: could not remove {display_path}: {e}");
2128                                    had_errors = true;
2129                                }
2130                            }
2131                        }
2132                    }
2133                }
2134            }
2135        }
2136    }
2137
2138    if !quiet {
2139        report_other_worktrees(root);
2140    }
2141
2142    CleanRepoStats {
2143        removed_worktrees,
2144        freed_bytes,
2145        had_errors,
2146    }
2147}
2148
2149#[derive(Debug)]
2150pub struct GitWorktreeInfo {
2151    pub path: PathBuf,
2152    pub head_sha: Option<String>,
2153    pub branch: Option<String>,
2154    pub is_detached: bool,
2155    pub is_bare: bool,
2156}
2157
2158/// Parses git worktrees from `git worktree list --porcelain`.
2159pub fn parse_worktree_list(root: &Path) -> Vec<GitWorktreeInfo> {
2160    let out = std::process::Command::new("git")
2161        .args(["worktree", "list", "--porcelain"])
2162        .current_dir(root)
2163        .output();
2164    let Ok(o) = out else {
2165        return Vec::new();
2166    };
2167    if !o.status.success() {
2168        return Vec::new();
2169    }
2170    let text = String::from_utf8_lossy(&o.stdout);
2171
2172    let mut list = Vec::new();
2173    let mut cur_path: Option<PathBuf> = None;
2174    let mut cur_head: Option<String> = None;
2175    let mut cur_branch: Option<String> = None;
2176    let mut cur_detached = false;
2177    let mut cur_bare = false;
2178
2179    let mut finish_entry = |path: &mut Option<PathBuf>,
2180                            head: &mut Option<String>,
2181                            branch: &mut Option<String>,
2182                            detached: &mut bool,
2183                            bare: &mut bool| {
2184        if let Some(p) = path.take() {
2185            list.push(GitWorktreeInfo {
2186                path: p,
2187                head_sha: head.take(),
2188                branch: branch.take(),
2189                is_detached: *detached,
2190                is_bare: *bare,
2191            });
2192            *detached = false;
2193            *bare = false;
2194        }
2195    };
2196
2197    for line in text.lines() {
2198        let line = line.trim();
2199        if line.is_empty() {
2200            finish_entry(
2201                &mut cur_path,
2202                &mut cur_head,
2203                &mut cur_branch,
2204                &mut cur_detached,
2205                &mut cur_bare,
2206            );
2207        } else if let Some(p) = line.strip_prefix("worktree ") {
2208            finish_entry(
2209                &mut cur_path,
2210                &mut cur_head,
2211                &mut cur_branch,
2212                &mut cur_detached,
2213                &mut cur_bare,
2214            );
2215            cur_path = Some(PathBuf::from(p.trim()));
2216        } else if let Some(h) = line.strip_prefix("HEAD ") {
2217            cur_head = Some(h.trim().to_string());
2218        } else if let Some(b) = line.strip_prefix("branch ") {
2219            let b_str = b.trim();
2220            let b_name = b_str.strip_prefix("refs/heads/").unwrap_or(b_str);
2221            cur_branch = Some(b_name.to_string());
2222        } else if line == "detached" {
2223            cur_detached = true;
2224        } else if line == "bare" {
2225            cur_bare = true;
2226        }
2227    }
2228    finish_entry(
2229        &mut cur_path,
2230        &mut cur_head,
2231        &mut cur_branch,
2232        &mut cur_detached,
2233        &mut cur_bare,
2234    );
2235    list
2236}
2237
2238/// Formats a worktree path for display and for git CLI commands:
2239/// relative to `root` if inside `root` or a sibling (same parent directory);
2240/// otherwise absolute.
2241pub fn display_worktree_path(target: &Path, root: &Path) -> String {
2242    let target_canon = target
2243        .canonicalize()
2244        .unwrap_or_else(|_| target.to_path_buf());
2245    let root_canon = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
2246
2247    // Inside the repository root
2248    if let Ok(rel) = target_canon.strip_prefix(&root_canon) {
2249        if !rel.as_os_str().is_empty() {
2250            return rel.to_string_lossy().replace('\\', "/");
2251        }
2252    }
2253
2254    // Sibling (same parent directory, e.g. ../app--side)
2255    if target_canon != root_canon {
2256        if let (Some(root_parent), Some(target_parent)) =
2257            (root_canon.parent(), target_canon.parent())
2258        {
2259            if root_parent == target_parent {
2260                if let Some(file_name) = target_canon.file_name() {
2261                    let rel = Path::new("..").join(file_name);
2262                    return rel.to_string_lossy().replace('\\', "/");
2263                }
2264            }
2265        }
2266    }
2267
2268    // Otherwise show the absolute path
2269    target_canon.to_string_lossy().replace('\\', "/")
2270}
2271
2272/// Returns true if `root` is a linked worktree (its git-dir differs from its git-common-dir).
2273pub fn is_linked_worktree(root: &Path) -> bool {
2274    let git_dir_out = std::process::Command::new("git")
2275        .args(["rev-parse", "--git-dir"])
2276        .current_dir(root)
2277        .output();
2278    let common_dir_out = std::process::Command::new("git")
2279        .args(["rev-parse", "--git-common-dir"])
2280        .current_dir(root)
2281        .output();
2282    match (git_dir_out, common_dir_out) {
2283        (Ok(gd), Ok(cd)) if gd.status.success() && cd.status.success() => {
2284            let gd_str = String::from_utf8_lossy(&gd.stdout).trim().to_string();
2285            let cd_str = String::from_utf8_lossy(&cd.stdout).trim().to_string();
2286            if gd_str == cd_str {
2287                return false;
2288            }
2289            let gd_path = if Path::new(&gd_str).is_absolute() {
2290                PathBuf::from(&gd_str)
2291            } else {
2292                root.join(&gd_str)
2293            };
2294            let cd_path = if Path::new(&cd_str).is_absolute() {
2295                PathBuf::from(&cd_str)
2296            } else {
2297                root.join(&cd_str)
2298            };
2299            let gd_canon = gd_path.canonicalize().unwrap_or(gd_path);
2300            let cd_canon = cd_path.canonicalize().unwrap_or(cd_path);
2301            gd_canon != cd_canon
2302        }
2303        _ => false,
2304    }
2305}
2306
2307/// Returns true if any path component is `.wt`.
2308pub fn has_wt_component(path: &Path) -> bool {
2309    path.components().any(|c| c.as_os_str() == ".wt")
2310}
2311
2312/// Checks whether a worktree's working tree is clean:
2313/// `git status --porcelain` lists nothing other than `.DS_Store` files, at any depth.
2314pub fn is_worktree_clean(wt_path: &Path) -> bool {
2315    let out = std::process::Command::new("git")
2316        .arg("--no-optional-locks")
2317        .arg("-C")
2318        .arg(wt_path.as_os_str())
2319        .args(["status", "--porcelain", "-u"])
2320        .output();
2321    match out {
2322        Ok(o) if o.status.success() => {
2323            let stdout = String::from_utf8_lossy(&o.stdout);
2324            for line in stdout.lines() {
2325                let trimmed = line.trim();
2326                if trimmed.is_empty() {
2327                    continue;
2328                }
2329                if line.len() < 3 {
2330                    return false;
2331                }
2332                let mut path_part = line[3..].trim();
2333                if let Some((_, new_path)) = path_part.split_once(" -> ") {
2334                    path_part = new_path.trim();
2335                }
2336                let unquoted = path_part
2337                    .strip_prefix('"')
2338                    .and_then(|p| p.strip_suffix('"'))
2339                    .unwrap_or(path_part);
2340                if Path::new(unquoted).file_name() != Some(std::ffi::OsStr::new(".DS_Store")) {
2341                    return false;
2342                }
2343            }
2344            true
2345        }
2346        _ => false,
2347    }
2348}
2349
2350/// Inspects other worktrees (excluding main checkout, linked-worktree roots,
2351/// and blyte's `.wt/<id>` runs), and reports any that are both merged and clean.
2352/// Never deletes them.
2353pub fn report_other_worktrees(root: &Path) {
2354    // Only report from the main worktree. If the root being cleaned is a linked worktree,
2355    // print nothing about other worktrees for it.
2356    if is_linked_worktree(root) {
2357        return;
2358    }
2359
2360    let worktrees = parse_worktree_list(root);
2361    let root_canon = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
2362    let main_canon = worktrees
2363        .first()
2364        .map(|wt| wt.path.canonicalize().unwrap_or_else(|_| wt.path.clone()));
2365
2366    let mut other_count = 0;
2367    let mut other_bytes = 0;
2368
2369    for (idx, wt) in worktrees.into_iter().enumerate() {
2370        // Never list the main worktree (first entry of git worktree list --porcelain)
2371        if idx == 0 {
2372            continue;
2373        }
2374        if wt.is_bare {
2375            continue;
2376        }
2377        if !wt.path.exists() {
2378            continue;
2379        }
2380
2381        let wt_canon = wt.path.canonicalize().unwrap_or_else(|_| wt.path.clone());
2382        // Skip the main checkout as well as the root itself
2383        if wt_canon == root_canon || wt.path == root {
2384            continue;
2385        }
2386        if Some(&wt_canon) == main_canon.as_ref() {
2387            continue;
2388        }
2389        // Never list blyte runs or session worktrees handled by clean_repo
2390        if has_wt_component(&wt.path)
2391            || has_wt_component(&wt_canon)
2392            || is_session_worktree(root, &wt.path)
2393        {
2394            continue;
2395        }
2396
2397        // Check if merged
2398        let is_merged = if let Some(ref branch) = wt.branch {
2399            is_branch_merged(root, branch)
2400        } else if let Some(ref sha) = wt.head_sha {
2401            is_commit_merged(root, sha)
2402        } else {
2403            false
2404        };
2405
2406        if !is_merged {
2407            continue;
2408        }
2409
2410        // Check if clean (lists nothing other than .DS_Store files)
2411        if !is_worktree_clean(&wt.path) {
2412            continue;
2413        }
2414
2415        let size = dir_size(&wt.path);
2416        let path_str = display_worktree_path(&wt.path, root);
2417        let branch_label = wt.branch.as_deref().unwrap_or_else(|| {
2418            wt.head_sha
2419                .as_deref()
2420                .map(|s| &s[..s.len().min(7)])
2421                .unwrap_or("detached")
2422        });
2423
2424        println!(
2425            "merged worktree {path_str} ({branch_label}, {}): git worktree remove {path_str}",
2426            format_size(size)
2427        );
2428
2429        other_count += 1;
2430        other_bytes += size;
2431    }
2432
2433    if other_count > 0 {
2434        println!(
2435            "{other_count} other worktrees are merged and clean ({}); remove them with the commands above",
2436            format_size(other_bytes)
2437        );
2438    }
2439}
2440
2441struct CleanLockGuard(PathBuf);
2442
2443impl Drop for CleanLockGuard {
2444    fn drop(&mut self) {
2445        let _ = std::fs::remove_file(&self.0);
2446    }
2447}
2448
2449enum LockOutcome {
2450    Acquired(CleanLockGuard),
2451    AlreadyRunning,
2452    Error(String),
2453}
2454
2455fn acquire_clean_lock(root: &Path) -> LockOutcome {
2456    use std::io::Write;
2457    let wt_dir = root.join(".wt");
2458    if let Err(e) = std::fs::create_dir_all(&wt_dir) {
2459        return LockOutcome::Error(format!("{}: {e}", wt_dir.display()));
2460    }
2461    let lock_path = wt_dir.join("clean.lock");
2462    let pid_str = format!("{}\n", std::process::id());
2463
2464    match std::fs::OpenOptions::new()
2465        .write(true)
2466        .create_new(true)
2467        .open(&lock_path)
2468    {
2469        Ok(mut f) => {
2470            if let Err(e) = f.write_all(pid_str.as_bytes()) {
2471                let _ = std::fs::remove_file(&lock_path);
2472                return LockOutcome::Error(format!("{}: {e}", lock_path.display()));
2473            }
2474            LockOutcome::Acquired(CleanLockGuard(lock_path))
2475        }
2476        Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
2477            let contents = match std::fs::read_to_string(&lock_path) {
2478                Ok(c) => c,
2479                Err(read_err) => {
2480                    return LockOutcome::Error(format!("{}: {read_err}", lock_path.display()));
2481                }
2482            };
2483            let old_pid: i64 = match contents.trim().parse() {
2484                Ok(p) => p,
2485                Err(parse_err) => {
2486                    return LockOutcome::Error(format!(
2487                        "{}: invalid pid: {parse_err}",
2488                        lock_path.display()
2489                    ));
2490                }
2491            };
2492            if is_pid_alive(old_pid) {
2493                return LockOutcome::AlreadyRunning;
2494            }
2495            eprintln!(
2496                "replacing stale {} from dead pid {old_pid}",
2497                lock_path.display()
2498            );
2499            if let Err(rm_err) = std::fs::remove_file(&lock_path) {
2500                return LockOutcome::Error(format!("{}: {rm_err}", lock_path.display()));
2501            }
2502            match std::fs::OpenOptions::new()
2503                .write(true)
2504                .create_new(true)
2505                .open(&lock_path)
2506            {
2507                Ok(mut f) => {
2508                    if let Err(write_err) = f.write_all(pid_str.as_bytes()) {
2509                        let _ = std::fs::remove_file(&lock_path);
2510                        return LockOutcome::Error(format!("{}: {write_err}", lock_path.display()));
2511                    }
2512                    LockOutcome::Acquired(CleanLockGuard(lock_path))
2513                }
2514                Err(open_err) => LockOutcome::Error(format!("{}: {open_err}", lock_path.display())),
2515            }
2516        }
2517        Err(e) => LockOutcome::Error(format!("{}: {e}", lock_path.display())),
2518    }
2519}
2520
2521/// Runs the `blyte clean` command.
2522pub fn run(args: &crate::cli::CleanArgs) -> i32 {
2523    if (args.quiet || args.skip.is_some()) && (args.all || args.dry_run) {
2524        eprintln!("error: --quiet and --skip cannot be combined with --all or --dry-run");
2525        return 2;
2526    }
2527
2528    let repos = if args.all {
2529        let tidy_res = if args.dry_run {
2530            crate::registry::missing_registered()
2531        } else {
2532            crate::registry::prune_missing()
2533        };
2534        match tidy_res {
2535            Ok(removed) if !removed.is_empty() => {
2536                let verb = if args.dry_run {
2537                    "would forget"
2538                } else {
2539                    "forgot"
2540                };
2541                let list = removed
2542                    .iter()
2543                    .map(|p| p.display().to_string())
2544                    .collect::<Vec<_>>()
2545                    .join(", ");
2546                println!(
2547                    "{verb} {} repositories that no longer exist: {list}",
2548                    removed.len()
2549                );
2550            }
2551            Ok(_) => {}
2552            Err(err) => {
2553                let path = crate::registry::state_dir()
2554                    .map(|d| d.join("repos").display().to_string())
2555                    .unwrap_or_default();
2556                eprintln!("error: could not tidy the repository registry {path}: {err}");
2557            }
2558        }
2559        crate::registry::registered()
2560    } else {
2561        match find_repo_root() {
2562            Ok(root) => vec![root],
2563            Err(e) => {
2564                eprintln!("error: {e}");
2565                return 2;
2566            }
2567        }
2568    };
2569
2570    let _lock_guard = if args.quiet {
2571        let Some(root) = repos.first() else {
2572            eprintln!("error: blyte clean --quiet found no repository to clean");
2573            return 1;
2574        };
2575        match acquire_clean_lock(root) {
2576            LockOutcome::Acquired(guard) => Some(guard),
2577            LockOutcome::AlreadyRunning => return 0,
2578            LockOutcome::Error(e) => {
2579                eprintln!("error: {e}");
2580                return 1;
2581            }
2582        }
2583    } else {
2584        None
2585    };
2586
2587    let mut total_freed = 0;
2588    let mut had_errors = false;
2589    for repo in &repos {
2590        let stats = clean_repo(
2591            repo,
2592            args.older_than,
2593            args.dry_run,
2594            args.skip.as_deref(),
2595            args.quiet,
2596        );
2597        total_freed += stats.freed_bytes;
2598        if stats.had_errors {
2599            had_errors = true;
2600        }
2601    }
2602
2603    if !args.quiet {
2604        if args.dry_run {
2605            println!("would free {}", format_size(total_freed));
2606        } else {
2607            println!("freed {}", format_size(total_freed));
2608        }
2609    }
2610
2611    if had_errors {
2612        1
2613    } else {
2614        0
2615    }
2616}
2617
2618fn delete_wip_branch_strict(root: &Path, branch_name: &str) -> Result<(), String> {
2619    let del_out = std::process::Command::new("git")
2620        .args(["branch", "-D", branch_name])
2621        .current_dir(root)
2622        .output()
2623        .map_err(|e| format!("git branch -D {branch_name}: {e}"))?;
2624    if !del_out.status.success() {
2625        return Err(format!(
2626            "git branch -D {branch_name}: {}",
2627            String::from_utf8_lossy(&del_out.stderr).trim()
2628        ));
2629    }
2630    Ok(())
2631}
2632
2633/// Removes a finished run `<id>` when its work is merged (or it made no changes) and its worktree
2634/// has no uncommitted changes.
2635pub fn remove_finished_run(root: &Path, id: &str) -> Result<Option<String>, String> {
2636    let wt_path = root.join(".wt").join(id);
2637    let branch_name = format!("wip/{id}");
2638    let mut ctx = CleanContext::new(root);
2639
2640    if wt_path.exists() {
2641        let reason = match ctx.check_removable(id, u64::MAX) {
2642            Ok(
2643                r @ (RemovalReason::Merged
2644                | RemovalReason::MergedInto(_)
2645                | RemovalReason::MergedThrough(_)
2646                | RemovalReason::NoChanges),
2647            ) => r,
2648            Ok(
2649                RemovalReason::SessionMerged(_)
2650                | RemovalReason::Verdict(_)
2651                | RemovalReason::OlderThan(_)
2652                | RemovalReason::ResearchReport
2653                | RemovalReason::ResearchReportInWorktree
2654                | RemovalReason::ResearchEndedWithoutReport(_)
2655                | RemovalReason::ResearchStoppedWithoutSummary(_),
2656            )
2657            | Err(_) => return Ok(None),
2658        };
2659        if has_uncommitted_changes(&wt_path) {
2660            return Ok(None);
2661        }
2662
2663        let wt_rel = format!(".wt/{id}");
2664        let rm_out = std::process::Command::new("git")
2665            .args(["worktree", "remove", &wt_rel])
2666            .current_dir(root)
2667            .output()
2668            .map_err(|e| format!("git worktree remove {wt_rel}: {e}"))?;
2669        if !rm_out.status.success() {
2670            return Err(format!(
2671                "git worktree remove {wt_rel}: {}",
2672                String::from_utf8_lossy(&rm_out.stderr).trim()
2673            ));
2674        }
2675
2676        if ctx.get_branch_tip(&branch_name).is_some() {
2677            delete_wip_branch_strict(root, &branch_name)?;
2678        }
2679
2680        return Ok(Some(reason.to_string()));
2681    }
2682
2683    if ctx.get_branch_tip(&branch_name).is_some() {
2684        if !is_branch_merged(root, &branch_name) {
2685            return Ok(None);
2686        }
2687        let reason = ctx
2688            .check_run_merged(id)
2689            .unwrap_or(RemovalReason::Merged)
2690            .to_string();
2691        delete_wip_branch_strict(root, &branch_name)?;
2692        return Ok(Some(reason));
2693    }
2694
2695    Ok(None)
2696}
2697
2698/// Starts `blyte clean --quiet [--skip <ID>]` in the background without waiting for it.
2699pub fn spawn_background_clean(root: &Path, skip_id: Option<&str>) {
2700    let res: Result<(), std::io::Error> = (|| {
2701        let wt_dir = root.join(".wt");
2702        std::fs::create_dir_all(&wt_dir)?;
2703        let log_file = std::fs::OpenOptions::new()
2704            .create(true)
2705            .append(true)
2706            .open(wt_dir.join("clean.log"))?;
2707        let stderr_file = log_file.try_clone()?;
2708        let exe = std::env::current_exe()?;
2709        let mut cmd = std::process::Command::new(exe);
2710        cmd.arg("clean").arg("--quiet");
2711        if let Some(id) = skip_id {
2712            cmd.arg("--skip").arg(id);
2713        }
2714        cmd.current_dir(root)
2715            .stdin(std::process::Stdio::null())
2716            .stdout(std::process::Stdio::from(log_file))
2717            .stderr(std::process::Stdio::from(stderr_file));
2718        let _child = cmd.spawn()?;
2719        Ok(())
2720    })();
2721    if let Err(e) = res {
2722        eprintln!("warning: could not start the background clean: {e}");
2723    }
2724}
2725
2726/// Removes a run's worktree on review after recording the verdict under the same rules.
2727/// Removes the worktree only when the rules allow it now (e.g. redone, or work already merged);
2728/// otherwise prints nothing extra beyond the verdict line, except for accepted/fixed prints
2729/// `worktree .wt/<id> kept until wip/<id> is merged`.
2730pub fn clean_on_review(root: &Path, id: &str) {
2731    let wt_path = root.join(".wt").join(id);
2732    if !wt_path.exists() {
2733        spawn_background_clean(root, Some(id));
2734        return;
2735    }
2736
2737    let mut ctx = CleanContext::new(root);
2738    let branch_name = format!("wip/{id}");
2739    let branch_exists = ctx.get_branch_tip(&branch_name).is_some();
2740
2741    let verdict_path = root.join(".wt").join(format!("{id}.verdict.json"));
2742    let verdict_str = std::fs::read_to_string(&verdict_path)
2743        .ok()
2744        .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
2745        .and_then(|v| {
2746            v.get("verdict")
2747                .and_then(|s| s.as_str())
2748                .map(|s| s.to_string())
2749        })
2750        .unwrap_or_default();
2751
2752    let is_res = ctx.is_research_run(id);
2753    let removal_reason = match ctx.check_removable(id, 14) {
2754        Ok(r) if is_res || !has_uncommitted_changes(&wt_path) => Some(r),
2755        _ => None,
2756    };
2757
2758    let Some(removal_reason) = removal_reason else {
2759        if verdict_str == "accepted" || verdict_str == "fixed" {
2760            println!("worktree .wt/{id} kept until {branch_name} is merged");
2761        }
2762        spawn_background_clean(root, Some(id));
2763        return;
2764    };
2765
2766    if removal_reason == RemovalReason::ResearchReportInWorktree {
2767        let src = wt_path.join("report.md");
2768        let dst = root.join(".wt").join(format!("{id}.report.md"));
2769        if let Err(err) = std::fs::copy(&src, &dst) {
2770            eprintln!(
2771                "error: could not copy {} to {}: {err}",
2772                src.display(),
2773                dst.display()
2774            );
2775            spawn_background_clean(root, Some(id));
2776            return;
2777        }
2778    }
2779
2780    let removed_ok = if is_res {
2781        std::fs::remove_dir_all(&wt_path).is_ok()
2782    } else {
2783        let rm_out = std::process::Command::new("git")
2784            .args(["worktree", "remove", wt_path.to_str().unwrap_or("")])
2785            .current_dir(root)
2786            .output();
2787        let _ = std::process::Command::new("git")
2788            .args(["worktree", "prune"])
2789            .current_dir(root)
2790            .output();
2791        rm_out.map(|o| o.status.success()).unwrap_or(false)
2792    };
2793
2794    if !removed_ok {
2795        if verdict_str == "accepted" || verdict_str == "fixed" {
2796            println!("worktree .wt/{id} kept until {branch_name} is merged");
2797        }
2798        spawn_background_clean(root, Some(id));
2799        return;
2800    }
2801
2802    if branch_exists {
2803        let is_merged = ctx.check_run_merged(id).is_some();
2804        if is_merged {
2805            let del_out = std::process::Command::new("git")
2806                .args(["branch", "-D", &branch_name])
2807                .current_dir(root)
2808                .output();
2809            if del_out.map(|o| o.status.success()).unwrap_or(false) {
2810                ctx.wip_branch_tips.remove(&branch_name);
2811                println!("removed .wt/{id}; branch {branch_name} deleted");
2812            } else {
2813                println!("removed .wt/{id}; branch {branch_name} kept");
2814            }
2815        } else {
2816            println!("removed .wt/{id}; branch {branch_name} kept");
2817        }
2818    } else {
2819        println!("removed .wt/{id}");
2820    }
2821
2822    spawn_background_clean(root, Some(id));
2823}