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    UnreadableStartRecord(String),
67    UnreadableVerdict(String),
68    UnreadableChildState(String),
69    Custom(String),
70}
71
72impl std::fmt::Display for KeptReason {
73    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
74        match self {
75            Self::UncommittedChanges => write!(f, "uncommitted changes"),
76            Self::Running => write!(f, "running"),
77            Self::NoVerdict => write!(f, "no verdict"),
78            Self::NotMergedYet => write!(f, "not merged yet"),
79            Self::NoReport => write!(f, "no report"),
80            Self::UnreadableSummary => write!(f, "unreadable summary"),
81            Self::InUse => write!(f, "in use by a running process"),
82            Self::CannotCheckInUse(err) => {
83                write!(f, "cannot tell whether it is in use: {err}")
84            }
85            Self::UsedRecently(d) => write!(f, "used in the last {d} days"),
86            Self::HoldsRuns(path) => write!(f, "holds runs: review them from {path}"),
87            Self::UnreadableStartRecord(reason) => write!(f, "unreadable start record: {reason}"),
88            Self::UnreadableVerdict(reason) => write!(f, "unreadable verdict: {reason}"),
89            Self::UnreadableChildState(reason) => write!(f, "unreadable child state: {reason}"),
90            Self::Custom(s) => write!(f, "{s}"),
91        }
92    }
93}
94
95fn read_verdict_file(path: &Path) -> Result<Option<String>, String> {
96    let content = match std::fs::read_to_string(path) {
97        Ok(content) => content,
98        Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(None),
99        Err(err) => return Err(format!("{}: {err}", path.display())),
100    };
101    let value: serde_json::Value =
102        serde_json::from_str(&content).map_err(|err| format!("{}: {err}", path.display()))?;
103    let obj = value
104        .as_object()
105        .ok_or_else(|| format!("{}: not a JSON object", path.display()))?;
106    match obj.get("verdict") {
107        Some(serde_json::Value::String(s)) if !s.is_empty() => Ok(Some(s.clone())),
108        Some(serde_json::Value::String(_)) => {
109            Err(format!("{}: empty verdict field", path.display()))
110        }
111        Some(_) => Err(format!("{}: verdict field is not a string", path.display())),
112        None => Err(format!("{}: missing verdict field", path.display())),
113    }
114}
115
116fn read_child_summary_verified(path: &Path) -> Result<bool, String> {
117    let content = match std::fs::read_to_string(path) {
118        Ok(content) => content,
119        Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(false),
120        Err(err) => return Err(format!("{}: {err}", path.display())),
121    };
122    let value: serde_json::Value =
123        serde_json::from_str(&content).map_err(|err| format!("{}: {err}", path.display()))?;
124    let obj = value
125        .as_object()
126        .ok_or_else(|| format!("{}: not a JSON object", path.display()))?;
127    match obj.get("outcome") {
128        Some(serde_json::Value::String(s)) => Ok(s == "verified"),
129        Some(_) => Err(format!("{}: outcome field is not a string", path.display())),
130        None => Err(format!("{}: missing outcome field", path.display())),
131    }
132}
133
134/// Recursively computes directory size in bytes without following symlinks.
135pub fn dir_size(path: &Path) -> u64 {
136    let mut total = 0;
137    let Ok(meta) = std::fs::symlink_metadata(path) else {
138        return 0;
139    };
140    if meta.file_type().is_symlink() {
141        return 0;
142    }
143    if meta.is_file() {
144        return meta.len();
145    }
146    if meta.is_dir() {
147        let Ok(entries) = std::fs::read_dir(path) else {
148            return 0;
149        };
150        for entry in entries.flatten() {
151            let Ok(ft) = entry.file_type() else {
152                continue;
153            };
154            if ft.is_symlink() {
155                continue;
156            } else if ft.is_dir() {
157                total += dir_size(&entry.path());
158            } else if ft.is_file() {
159                if let Ok(m) = entry.metadata() {
160                    total += m.len();
161                }
162            }
163        }
164    }
165    total
166}
167
168/// Formats byte count into human-readable representation: e.g. "812 MB", "12.3 GB".
169pub fn format_size(bytes: u64) -> String {
170    const KB: f64 = 1024.0;
171    const MB: f64 = 1024.0 * 1024.0;
172    const GB: f64 = 1024.0 * 1024.0 * 1024.0;
173    let b = bytes as f64;
174    let (val, unit) = if b >= GB {
175        (b / GB, "GB")
176    } else if b >= MB {
177        (b / MB, "MB")
178    } else if b >= KB {
179        (b / KB, "KB")
180    } else {
181        return format!("{bytes} B");
182    };
183
184    let s = if val >= 100.0 {
185        format!("{val:.0}")
186    } else {
187        let formatted = format!("{val:.1}");
188        formatted
189            .strip_suffix(".0")
190            .unwrap_or(&formatted)
191            .to_string()
192    };
193    format!("{s} {unit}")
194}
195
196/// Checks whether a process with the given PID is alive.
197pub fn is_pid_alive(pid: i64) -> bool {
198    if pid <= 0 {
199        return false;
200    }
201    let ret = unsafe { libc::kill(pid as libc::pid_t, 0) };
202    if ret == 0 {
203        true
204    } else {
205        std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
206    }
207}
208
209/// Finds the root repository (resolving the main checkout if inside a linked worktree).
210pub fn find_repo_root() -> Result<PathBuf, String> {
211    let out = std::process::Command::new("git")
212        .args([
213            "rev-parse",
214            "--path-format=absolute",
215            "--show-toplevel",
216            "--git-dir",
217            "--git-common-dir",
218        ])
219        .output()
220        .map_err(|e| format!("git not found: {e}"))?;
221    if !out.status.success() {
222        return Err("not a git repository".to_string());
223    }
224    let text = String::from_utf8_lossy(&out.stdout);
225    let mut lines = text.lines();
226    let (Some(toplevel), Some(git_dir), Some(common_dir)) =
227        (lines.next(), lines.next(), lines.next())
228    else {
229        return Err("not a git repository".to_string());
230    };
231    let root = PathBuf::from(toplevel.trim());
232    let git_dir = git_dir.trim();
233    let common_dir = common_dir.trim();
234    if git_dir != common_dir {
235        let common = PathBuf::from(common_dir);
236        let main = (|| -> Option<PathBuf> {
237            if common.file_name()? != ".git" {
238                return None;
239            }
240            let parent = common.parent()?;
241            let parent_canon = parent.canonicalize().ok()?;
242            let root_canon = root.canonicalize().ok()?;
243            if parent_canon == root_canon {
244                return None;
245            }
246            Some(parent.to_path_buf())
247        })();
248        main.ok_or_else(|| {
249            format!(
250                "cannot find main checkout for linked worktree {}",
251                root.display()
252            )
253        })
254    } else {
255        Ok(root)
256    }
257}
258
259/// Checks whether a run is a research run from its start file.
260pub fn is_research(root: &Path, id: &str) -> bool {
261    let start_path = root.join(".wt").join(format!("{id}.start.json"));
262    if let Ok(s) = std::fs::read_to_string(&start_path) {
263        if let Ok(val) = serde_json::from_str::<serde_json::Value>(&s) {
264            return val
265                .get("research")
266                .and_then(|r| r.as_bool())
267                .unwrap_or(false);
268        }
269    }
270    false
271}
272
273/// Checks whether a worktree has uncommitted changes via `git status --porcelain`.
274pub fn has_uncommitted_changes(wt_path: &Path) -> bool {
275    let out = std::process::Command::new("git")
276        .args([
277            "-C",
278            wt_path.to_str().unwrap_or(""),
279            "status",
280            "--porcelain",
281        ])
282        .output();
283    match out {
284        Ok(o) if o.status.success() => {
285            !o.stdout.is_empty() && !String::from_utf8_lossy(&o.stdout).trim().is_empty()
286        }
287        _ => true,
288    }
289}
290
291fn git_tree_sha(root: &Path, ref_name: &str) -> Option<String> {
292    let out = std::process::Command::new("git")
293        .args(["rev-parse", &format!("{ref_name}^{{tree}}")])
294        .current_dir(root)
295        .output()
296        .ok()?;
297    if out.status.success() {
298        Some(String::from_utf8_lossy(&out.stdout).trim().to_string())
299    } else {
300        None
301    }
302}
303
304fn is_cherry_merged_into_target(root: &Path, commit_sha: &str, target: &str) -> bool {
305    let cherry_out = std::process::Command::new("git")
306        .args(["cherry", target, commit_sha])
307        .current_dir(root)
308        .output();
309    if let Ok(o) = cherry_out {
310        if o.status.success() {
311            let s = String::from_utf8_lossy(&o.stdout);
312            let lines: Vec<&str> = s
313                .lines()
314                .map(|l| l.trim())
315                .filter(|l| !l.is_empty())
316                .collect();
317            if !lines.is_empty() && lines.iter().all(|l| l.starts_with('-')) {
318                return true;
319            }
320        }
321    }
322    false
323}
324
325fn is_merge_tree_merged_into_target(
326    root: &Path,
327    commit_sha: &str,
328    target: &str,
329    target_tree: Option<&str>,
330) -> bool {
331    let target_tree_sha = match target_tree {
332        Some(t) => Some(t.to_string()),
333        None => git_tree_sha(root, target),
334    };
335    if let Some(target_tree_sha) = target_tree_sha {
336        let merge_tree_out = std::process::Command::new("git")
337            .args(["merge-tree", "--write-tree", target, commit_sha])
338            .current_dir(root)
339            .output();
340        if let Ok(mt_o) = merge_tree_out {
341            if mt_o.status.success() {
342                let mt_stdout = String::from_utf8_lossy(&mt_o.stdout);
343                if let Some(first_line) = mt_stdout.lines().next() {
344                    if first_line.trim() == target_tree_sha {
345                        return true;
346                    }
347                }
348            }
349        }
350    }
351    false
352}
353
354fn parse_started_at(val: &serde_json::Value) -> Option<u64> {
355    let s = val.get("started_at")?;
356    if let Some(n) = s.as_u64() {
357        Some(n)
358    } else if let Some(n) = s.as_i64() {
359        if n >= 0 {
360            Some(n as u64)
361        } else {
362            None
363        }
364    } else if let Some(f) = s.as_f64() {
365        if f >= 0.0 {
366            Some(f as u64)
367        } else {
368            None
369        }
370    } else if let Some(st) = s.as_str() {
371        st.parse::<u64>().ok()
372    } else {
373        None
374    }
375}
376
377fn check_history_merged_with_base(
378    root: &Path,
379    tip_sha: &str,
380    target: &str,
381    merge_base: &str,
382    started_at: Option<&serde_json::Value>,
383) -> bool {
384    let diff_out = std::process::Command::new("git")
385        .args(["diff", "--name-only", merge_base, tip_sha])
386        .current_dir(root)
387        .output();
388    let Ok(diff_o) = diff_out else {
389        return false;
390    };
391    if !diff_o.status.success() {
392        return false;
393    }
394    let files: Vec<String> = String::from_utf8_lossy(&diff_o.stdout)
395        .lines()
396        .map(|l| l.trim().to_string())
397        .filter(|l| !l.is_empty())
398        .collect();
399
400    if files.is_empty() {
401        return false;
402    }
403
404    let since_arg = started_at
405        .and_then(|v| {
406            if let Some(n) = v.as_i64() {
407                if n >= 100_000_000 {
408                    Some(format!("--since={n}"))
409                } else {
410                    Some("--since=1970-01-01T00:00:00Z".to_string())
411                }
412            } else if let Some(n) = v.as_u64() {
413                if n >= 100_000_000 {
414                    Some(format!("--since={n}"))
415                } else {
416                    Some("--since=1970-01-01T00:00:00Z".to_string())
417                }
418            } else {
419                v.as_str().map(|s| format!("--since={s}"))
420            }
421        })
422        .unwrap_or_else(|| "--since=1970-01-01T00:00:00Z".to_string());
423
424    let mut cmd = std::process::Command::new("git");
425    cmd.args([
426        "rev-list",
427        "--first-parent",
428        &since_arg,
429        "-n",
430        "20",
431        target,
432        "--",
433    ]);
434    for f in &files {
435        cmd.arg(f);
436    }
437    cmd.current_dir(root);
438    let Ok(rev_o) = cmd.output() else {
439        return false;
440    };
441    if !rev_o.status.success() {
442        return false;
443    }
444
445    let commits: Vec<String> = String::from_utf8_lossy(&rev_o.stdout)
446        .lines()
447        .map(|l| l.trim().to_string())
448        .filter(|l| !l.is_empty())
449        .collect();
450
451    for c in commits {
452        let mt_out = std::process::Command::new("git")
453            .args(["merge-tree", "--write-tree", &c, tip_sha])
454            .current_dir(root)
455            .output();
456        let Ok(mt_o) = mt_out else {
457            continue;
458        };
459        if !mt_o.status.success() {
460            continue;
461        }
462        let mt_stdout = String::from_utf8_lossy(&mt_o.stdout);
463        let Some(first_line) = mt_stdout.lines().next() else {
464            continue;
465        };
466        let mt_tree = first_line.trim();
467
468        if let Some(c_tree) = git_tree_sha(root, &c) {
469            if mt_tree == c_tree {
470                return true;
471            }
472        }
473    }
474
475    false
476}
477
478/// Reads `.wt/<id>.start.json` from disk now.
479///
480/// A missing file is `Ok(None)`. A read error, or content that is not a JSON object
481/// (including an empty or half-written file), is an error naming the path and the reason.
482pub fn read_start_record(root: &Path, id: &str) -> Result<Option<serde_json::Value>, String> {
483    let path = root.join(".wt").join(format!("{id}.start.json"));
484    let content = match std::fs::read_to_string(&path) {
485        Ok(content) => content,
486        Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(None),
487        Err(err) => return Err(format!("{}: {err}", path.display())),
488    };
489    match serde_json::from_str::<serde_json::Value>(&content) {
490        Ok(value) if value.is_object() => Ok(Some(value)),
491        Ok(_) => Err(format!("{}: not a JSON object", path.display())),
492        Err(err) => Err(format!("{}: {err}", path.display())),
493    }
494}
495
496#[derive(Debug, Clone)]
497pub struct RefEntry {
498    pub objectname: String,
499    pub symref: Option<String>,
500    pub tree: Option<String>,
501}
502
503fn load_refs(root: &Path) -> (HashMap<String, RefEntry>, bool) {
504    let mut refs = HashMap::new();
505    let out = std::process::Command::new("git")
506        .args([
507            "for-each-ref",
508            "--format=%(refname)%09%(objectname)%09%(symref)%09%(tree)",
509            "refs/heads",
510            "refs/remotes/origin",
511        ])
512        .current_dir(root)
513        .output();
514    let Ok(o) = out else {
515        return (refs, false);
516    };
517    if !o.status.success() {
518        return (refs, false);
519    }
520    for line in String::from_utf8_lossy(&o.stdout).lines() {
521        let mut cols = line.split('\t');
522        let Some(refname) = cols.next() else {
523            continue;
524        };
525        let Some(objectname) = cols.next() else {
526            continue;
527        };
528        let symref = cols.next().unwrap_or("");
529        let tree = cols.next().unwrap_or("");
530        if refname.is_empty() || objectname.is_empty() {
531            continue;
532        }
533        refs.insert(
534            refname.to_string(),
535            RefEntry {
536                objectname: objectname.to_string(),
537                symref: if symref.is_empty() {
538                    None
539                } else {
540                    Some(symref.to_string())
541                },
542                tree: if tree.is_empty() {
543                    None
544                } else {
545                    Some(tree.to_string())
546                },
547            },
548        );
549    }
550    (refs, true)
551}
552
553fn lookup_ref<'b>(
554    refs: &'b HashMap<String, RefEntry>,
555    name: &str,
556) -> Option<(&'b str, &'b RefEntry)> {
557    if name.starts_with("refs/") {
558        return refs.get_key_value(name).map(|(k, v)| (k.as_str(), v));
559    }
560    let head_key = format!("refs/heads/{name}");
561    if let Some((k, v)) = refs.get_key_value(&head_key) {
562        return Some((k.as_str(), v));
563    }
564    let remote_key = format!("refs/remotes/{name}");
565    if let Some((k, v)) = refs.get_key_value(&remote_key) {
566        return Some((k.as_str(), v));
567    }
568    None
569}
570
571fn find_default_branch_from_refs(refs: &HashMap<String, RefEntry>) -> String {
572    if let Some(head_entry) = refs.get("refs/remotes/origin/HEAD") {
573        if let Some(ref symref) = head_entry.symref {
574            let target = symref.strip_prefix("refs/remotes/").unwrap_or(symref);
575            let branch_name = target.strip_prefix("origin/").unwrap_or(target);
576            if refs.contains_key(&format!("refs/heads/{branch_name}")) {
577                return branch_name.to_string();
578            }
579            if refs.contains_key(symref) || refs.contains_key(&format!("refs/remotes/{target}")) {
580                return target.to_string();
581            }
582            return branch_name.to_string();
583        }
584    }
585    if refs.contains_key("refs/heads/main") {
586        return "main".to_string();
587    }
588    if refs.contains_key("refs/heads/master") {
589        return "master".to_string();
590    }
591    "main".to_string()
592}
593
594/// Context for cleaning a repository, caching metadata to avoid redundant git calls and disk reads.
595pub struct CleanContext<'a> {
596    pub root: &'a Path,
597    pub start_files: HashMap<String, serde_json::Value>,
598    pub all_run_ids: Vec<String>,
599    pub refs: HashMap<String, RefEntry>,
600    pub refs_loaded: bool,
601    pub wip_branch_tips: HashMap<String, String>,
602    pub default_branch: String,
603    pub origin_default: Option<String>,
604    pub default_tree: Option<String>,
605    pub origin_default_tree: Option<String>,
606    pub wip_contains_cache: HashMap<String, Vec<String>>,
607    pub merged_cache: HashMap<String, Option<RemovalReason>>,
608    pub branch_contains_calls: usize,
609    pub cherry_pick_set: Option<HashSet<String>>,
610    pub rev_list_cache: HashMap<String, Vec<String>>,
611    pub ancestor_cache: HashMap<(String, String), bool>,
612    pub contains_target: HashSet<(String, String)>,
613    pub merge_base_cache: HashMap<(String, String), Option<String>>,
614    pub cherry_cache: HashMap<(String, String), bool>,
615    pub merge_tree_cache: HashMap<(String, String), bool>,
616}
617
618impl<'a> CleanContext<'a> {
619    pub fn new(root: &'a Path) -> Self {
620        let mut start_files = HashMap::new();
621        let mut all_run_ids = Vec::new();
622        let wt_dir = root.join(".wt");
623        if let Ok(entries) = std::fs::read_dir(&wt_dir) {
624            for entry in entries.flatten() {
625                let name = entry.file_name().to_string_lossy().to_string();
626                if let Some(id) = name.strip_suffix(".start.json") {
627                    all_run_ids.push(id.to_string());
628                    if let Ok(content) = std::fs::read_to_string(entry.path()) {
629                        if let Ok(val) = serde_json::from_str::<serde_json::Value>(&content) {
630                            start_files.insert(id.to_string(), val);
631                        }
632                    }
633                }
634            }
635        }
636        all_run_ids.sort();
637
638        let (refs, refs_loaded) = load_refs(root);
639
640        let mut wip_branch_tips = HashMap::new();
641        for (refname, entry) in &refs {
642            if let Some(short) = refname.strip_prefix("refs/heads/") {
643                if short.starts_with("wip/") {
644                    wip_branch_tips.insert(short.to_string(), entry.objectname.clone());
645                }
646            }
647        }
648
649        let default_branch = if refs_loaded {
650            find_default_branch_from_refs(&refs)
651        } else {
652            find_default_branch(root)
653        };
654        let name = default_branch
655            .strip_prefix("origin/")
656            .unwrap_or(&default_branch);
657        let remote = format!("origin/{name}");
658        let origin_default = if remote != default_branch
659            && if refs_loaded {
660                refs.contains_key(&format!("refs/remotes/{remote}"))
661            } else {
662                git_ok(root, &["rev-parse", "--verify", "--quiet", &remote])
663            } {
664            Some(remote)
665        } else {
666            None
667        };
668
669        let default_tree = if refs_loaded {
670            lookup_ref(&refs, &default_branch).and_then(|(_, e)| e.tree.clone())
671        } else {
672            git_tree_sha(root, &default_branch)
673        };
674        let origin_default_tree = origin_default.as_deref().and_then(|r| {
675            if refs_loaded {
676                lookup_ref(&refs, r).and_then(|(_, e)| e.tree.clone())
677            } else {
678                git_tree_sha(root, r)
679            }
680        });
681
682        let mut ancestor_cache = HashMap::new();
683        let mut contains_target = HashSet::new();
684
685        if refs_loaded {
686            let mut default_targets: Vec<String> = Vec::new();
687            if lookup_ref(&refs, &default_branch).is_some() {
688                default_targets.push(default_branch.clone());
689            }
690            if let Some(ref origin_def) = origin_default {
691                if lookup_ref(&refs, origin_def).is_some() {
692                    default_targets.push(origin_def.clone());
693                }
694            }
695
696            let mut seen_target_shas = HashSet::new();
697            for target in &default_targets {
698                let Some((_, target_entry)) = lookup_ref(&refs, target) else {
699                    continue;
700                };
701                let target_sha = target_entry.objectname.clone();
702                if !seen_target_shas.insert(target_sha.clone()) {
703                    continue;
704                }
705
706                let merged_out = std::process::Command::new("git")
707                    .args([
708                        "for-each-ref",
709                        &format!("--merged={target}"),
710                        "--format=%(refname:short)",
711                        "refs/heads",
712                    ])
713                    .current_dir(root)
714                    .output();
715                if let Ok(o) = merged_out {
716                    if o.status.success() {
717                        let merged_set: HashSet<String> = String::from_utf8_lossy(&o.stdout)
718                            .lines()
719                            .map(|l| l.trim().to_string())
720                            .filter(|l| !l.is_empty())
721                            .collect();
722                        for (refname, entry) in &refs {
723                            if let Some(short) = refname.strip_prefix("refs/heads/") {
724                                ancestor_cache.insert(
725                                    (entry.objectname.clone(), target_sha.clone()),
726                                    merged_set.contains(short),
727                                );
728                            }
729                        }
730                    }
731                }
732
733                let contains_out = std::process::Command::new("git")
734                    .args([
735                        "for-each-ref",
736                        &format!("--contains={target}"),
737                        "--format=%(refname:short)",
738                        "refs/heads",
739                    ])
740                    .current_dir(root)
741                    .output();
742                if let Ok(o) = contains_out {
743                    if o.status.success() {
744                        for line in String::from_utf8_lossy(&o.stdout).lines() {
745                            let short = line.trim();
746                            if short.is_empty() {
747                                continue;
748                            }
749                            if let Some(entry) = refs.get(&format!("refs/heads/{short}")) {
750                                contains_target
751                                    .insert((entry.objectname.clone(), target_sha.clone()));
752                            }
753                        }
754                    }
755                }
756            }
757        }
758
759        Self {
760            root,
761            start_files,
762            all_run_ids,
763            refs,
764            refs_loaded,
765            wip_branch_tips,
766            default_branch,
767            origin_default,
768            default_tree,
769            origin_default_tree,
770            wip_contains_cache: HashMap::new(),
771            merged_cache: HashMap::new(),
772            branch_contains_calls: 0,
773            cherry_pick_set: None,
774            rev_list_cache: HashMap::new(),
775            ancestor_cache,
776            contains_target,
777            merge_base_cache: HashMap::new(),
778            cherry_cache: HashMap::new(),
779            merge_tree_cache: HashMap::new(),
780        }
781    }
782
783    pub fn remove_branch(&mut self, branch_name: &str) {
784        self.wip_branch_tips.remove(branch_name);
785        self.refs.remove(&format!("refs/heads/{branch_name}"));
786    }
787
788    pub fn tree_sha(&self, ref_name: &str) -> Option<String> {
789        if let Some((_, entry)) = lookup_ref(&self.refs, ref_name) {
790            if entry.tree.is_some() {
791                return entry.tree.clone();
792            }
793        }
794        if self.refs_loaded
795            && (ref_name.starts_with("refs/heads/") || ref_name.starts_with("refs/remotes/origin/"))
796        {
797            return None;
798        }
799        git_tree_sha(self.root, ref_name)
800    }
801
802    fn ref_exists(&self, refname: &str) -> bool {
803        if lookup_ref(&self.refs, refname).is_some() {
804            return true;
805        }
806        if self.refs_loaded
807            && (refname.starts_with("refs/heads/") || refname.starts_with("refs/remotes/origin/"))
808        {
809            return false;
810        }
811        git_ok(self.root, &["rev-parse", "--verify", "--quiet", refname])
812    }
813
814    fn resolve_base_targets(&self, base: &str) -> Option<(String, Vec<String>)> {
815        resolve_base_targets_with(base, |cand| self.ref_exists(cand))
816    }
817
818    fn target_key(&self, target: &str) -> String {
819        lookup_ref(&self.refs, target)
820            .map(|(_, e)| e.objectname.clone())
821            .unwrap_or_else(|| target.to_string())
822    }
823
824    fn target_is_ancestor_of(&self, target: &str, commit_sha: &str) -> bool {
825        let key = (commit_sha.to_string(), self.target_key(target));
826        self.contains_target.contains(&key)
827    }
828
829    fn merge_base(&mut self, target: &str, commit_sha: &str) -> Option<String> {
830        let key = (self.target_key(target), commit_sha.to_string());
831        if let Some(cached) = self.merge_base_cache.get(&key) {
832            return cached.clone();
833        }
834        let mb_out = std::process::Command::new("git")
835            .args(["merge-base", target, commit_sha])
836            .current_dir(self.root)
837            .output();
838        let mb = match mb_out {
839            Ok(o) if o.status.success() => {
840                let s = String::from_utf8_lossy(&o.stdout).trim().to_string();
841                if s.is_empty() {
842                    None
843                } else {
844                    Some(s)
845                }
846            }
847            _ => None,
848        };
849        self.merge_base_cache.insert(key, mb.clone());
850        mb
851    }
852
853    fn compute_cherry_pick_set(&self) -> HashSet<String> {
854        let unremoved_ids = find_blyte_worktrees(self.root);
855        let candidate_ids: &[String] = if unremoved_ids.is_empty() {
856            &self.all_run_ids
857        } else {
858            &unremoved_ids
859        };
860
861        let mut min_started_at: Option<u64> = None;
862        let mut all_valid = true;
863
864        for id in candidate_ids {
865            let start_val = self.start_files.get(id);
866            let parsed = start_val.and_then(parse_started_at);
867            match parsed {
868                Some(ts) => {
869                    min_started_at = Some(min_started_at.map_or(ts, |m| m.min(ts)));
870                }
871                None => {
872                    all_valid = false;
873                }
874            }
875        }
876
877        let since_arg = if let (true, Some(min_ts)) = (all_valid, min_started_at) {
878            if min_ts >= 86_400 + 100_000_000 {
879                format!("--since={}", min_ts - 86_400)
880            } else {
881                "--since=1970-01-01T00:00:00Z".to_string()
882            }
883        } else {
884            "--since=1970-01-01T00:00:00Z".to_string()
885        };
886
887        let mut targets = Vec::new();
888        let mut seen = HashSet::new();
889
890        if lookup_ref(&self.refs, &self.default_branch).is_some()
891            || (!self.refs_loaded
892                && git_ok(
893                    self.root,
894                    &["rev-parse", "--verify", "--quiet", &self.default_branch],
895                ))
896        {
897            let key = lookup_ref(&self.refs, &self.default_branch)
898                .map(|(k, _)| k.to_string())
899                .unwrap_or_else(|| self.default_branch.clone());
900            if seen.insert(key) {
901                targets.push(self.default_branch.clone());
902            }
903        }
904
905        if let Some(ref origin_def) = self.origin_default {
906            if lookup_ref(&self.refs, origin_def).is_some()
907                || (!self.refs_loaded
908                    && git_ok(self.root, &["rev-parse", "--verify", "--quiet", origin_def]))
909            {
910                let key = lookup_ref(&self.refs, origin_def)
911                    .map(|(k, _)| k.to_string())
912                    .unwrap_or_else(|| origin_def.clone());
913                if seen.insert(key) {
914                    targets.push(origin_def.clone());
915                }
916            }
917        }
918
919        for id in &self.all_run_ids {
920            if let Some(base_str) = self
921                .start_files
922                .get(id)
923                .and_then(|s| s.get("base"))
924                .and_then(|b| b.as_str())
925            {
926                if let Some((_, base_targets)) = self.resolve_base_targets(base_str) {
927                    for bt in base_targets {
928                        let key = lookup_ref(&self.refs, &bt)
929                            .map(|(k, _)| k.to_string())
930                            .unwrap_or_else(|| bt.clone());
931                        if seen.insert(key) {
932                            targets.push(bt);
933                        }
934                    }
935                }
936            }
937        }
938
939        if targets.is_empty() {
940            return HashSet::new();
941        }
942
943        let mut cmd = std::process::Command::new("git");
944        cmd.args(["log", "--format=%B", &since_arg]);
945        for t in &targets {
946            cmd.arg(t);
947        }
948        cmd.current_dir(self.root);
949
950        let mut set = HashSet::new();
951        if let Ok(o) = cmd.output() {
952            if o.status.success() {
953                let text = String::from_utf8_lossy(&o.stdout);
954                for line in text.lines() {
955                    let trimmed = line.trim();
956                    if let Some(rest) = trimmed.strip_prefix("(cherry picked from commit ") {
957                        if let Some(sha) = rest.strip_suffix(')') {
958                            let sha = sha.trim();
959                            if is_commit_id(sha) {
960                                set.insert(sha.to_lowercase());
961                            }
962                        }
963                    }
964                }
965            }
966        }
967
968        set
969    }
970
971    pub fn get_cherry_pick_set(&mut self) -> &HashSet<String> {
972        if self.cherry_pick_set.is_none() {
973            let set = self.compute_cherry_pick_set();
974            self.cherry_pick_set = Some(set);
975        }
976        self.cherry_pick_set.as_ref().unwrap()
977    }
978
979    fn is_ancestor_of_target(&mut self, commit_sha: &str, target: &str) -> bool {
980        let key = (commit_sha.to_string(), self.target_key(target));
981        if let Some(&cached) = self.ancestor_cache.get(&key) {
982            return cached;
983        }
984        let is_anc = std::process::Command::new("git")
985            .args(["merge-base", "--is-ancestor", commit_sha, target])
986            .current_dir(self.root)
987            .output()
988            .map(|c| c.status.success())
989            .unwrap_or(false);
990        self.ancestor_cache.insert(key, is_anc);
991        is_anc
992    }
993
994    fn is_ancestor_of_default(&mut self, commit_sha: &str) -> bool {
995        let def = self.default_branch.clone();
996        if self.is_ancestor_of_target(commit_sha, &def) {
997            return true;
998        }
999        if let Some(origin_def) = self.origin_default.clone() {
1000            if self.is_ancestor_of_target(commit_sha, &origin_def) {
1001                return true;
1002            }
1003        }
1004        false
1005    }
1006
1007    fn get_run_commits_against_default(&mut self, tip_sha: &str) -> Vec<String> {
1008        if let Some(cached) = self.rev_list_cache.get(tip_sha) {
1009            return cached.clone();
1010        }
1011        let out = std::process::Command::new("git")
1012            .args(["rev-list", &format!("{}..{}", self.default_branch, tip_sha)])
1013            .current_dir(self.root)
1014            .output();
1015        let commits: Vec<String> = match out {
1016            Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout)
1017                .lines()
1018                .map(|l| l.trim().to_lowercase())
1019                .filter(|l| !l.is_empty())
1020                .collect(),
1021            _ => Vec::new(),
1022        };
1023        self.rev_list_cache
1024            .insert(tip_sha.to_string(), commits.clone());
1025        commits
1026    }
1027
1028    fn is_in_cherry_pick_record(&mut self, tip_sha: &str) -> bool {
1029        if self.get_cherry_pick_set().is_empty() {
1030            return false;
1031        }
1032        let commits = self.get_run_commits_against_default(tip_sha);
1033        if commits.is_empty() {
1034            return false;
1035        }
1036        let cherry_set = self.get_cherry_pick_set();
1037        commits.iter().all(|c| cherry_set.contains(c))
1038    }
1039
1040    pub fn get_branch_tip(&self, branch_name: &str) -> Option<String> {
1041        if let Some(sha) = self.wip_branch_tips.get(branch_name) {
1042            return Some(sha.clone());
1043        }
1044        if let Some(entry) = self.refs.get(&format!("refs/heads/{branch_name}")) {
1045            return Some(entry.objectname.clone());
1046        }
1047        if self.refs_loaded {
1048            return None;
1049        }
1050        get_branch_tip(self.root, branch_name)
1051    }
1052
1053    pub fn is_research_run(&self, id: &str) -> bool {
1054        self.start_files
1055            .get(id)
1056            .and_then(|v| v.get("research"))
1057            .and_then(|r| r.as_bool())
1058            .unwrap_or_else(|| is_research(self.root, id))
1059    }
1060
1061    pub fn get_wip_branches_containing(&mut self, tip_sha: &str) -> Vec<String> {
1062        if let Some(cached) = self.wip_contains_cache.get(tip_sha) {
1063            return cached.clone();
1064        }
1065
1066        self.branch_contains_calls += 1;
1067
1068        let out = std::process::Command::new("git")
1069            .args([
1070                "branch",
1071                "--list",
1072                "--format=%(refname:short)",
1073                "wip/*",
1074                "--contains",
1075                tip_sha,
1076            ])
1077            .current_dir(self.root)
1078            .output();
1079
1080        let mut branches = Vec::new();
1081        if let Ok(o) = out {
1082            if o.status.success() {
1083                for line in String::from_utf8_lossy(&o.stdout).lines() {
1084                    let trimmed = line.trim().trim_start_matches(['*', '+', ' ']).trim();
1085                    if !trimmed.is_empty() {
1086                        branches.push(trimmed.to_string());
1087                    }
1088                }
1089            }
1090        }
1091        self.wip_contains_cache
1092            .insert(tip_sha.to_string(), branches.clone());
1093        branches
1094    }
1095
1096    pub fn get_children_of(&mut self, id: &str, tip_sha: &str) -> Vec<String> {
1097        let mut children = Vec::new();
1098        let mut seen = HashSet::new();
1099
1100        for (candidate_id, start_val) in &self.start_files {
1101            if candidate_id == id {
1102                continue;
1103            }
1104            if let Some(base_str) = start_val.get("base").and_then(|v| v.as_str()) {
1105                let base_str = base_str.trim().trim_end_matches('/');
1106                let target1 = format!("wip/{id}");
1107                let target2 = format!("refs/heads/wip/{id}");
1108                if (base_str == target1 || base_str == target2) && seen.insert(candidate_id.clone())
1109                {
1110                    children.push(candidate_id.clone());
1111                }
1112            }
1113        }
1114
1115        let has_other_without_base = self.start_files.iter().any(|(candidate_id, val)| {
1116            candidate_id != id && val.get("base").is_none_or(|b| b.is_null())
1117        });
1118
1119        if !tip_sha.is_empty() && has_other_without_base {
1120            let tip_sha_owned = tip_sha.to_string();
1121            let containing_branches = self.get_wip_branches_containing(&tip_sha_owned);
1122            for b in containing_branches {
1123                let clean_b = b.strip_prefix("refs/heads/").unwrap_or(&b);
1124                if let Some(candidate_id) = clean_b.strip_prefix("wip/") {
1125                    if candidate_id == id {
1126                        continue;
1127                    }
1128                    if !self.start_files.contains_key(candidate_id) {
1129                        continue;
1130                    }
1131                    let has_base = self
1132                        .start_files
1133                        .get(candidate_id)
1134                        .and_then(|val| val.get("base"))
1135                        .is_some_and(|b| !b.is_null());
1136                    if !has_base && seen.insert(candidate_id.to_string()) {
1137                        children.push(candidate_id.to_string());
1138                    }
1139                }
1140            }
1141        }
1142
1143        children.sort();
1144        children
1145    }
1146
1147    pub fn is_child_run_merged(
1148        &mut self,
1149        child: &str,
1150        visited: &mut HashSet<String>,
1151    ) -> Result<bool, String> {
1152        if self.is_research_run(child) {
1153            return Ok(false);
1154        }
1155
1156        let branch_name = format!("wip/{child}");
1157        let tip = self.get_branch_tip(&branch_name);
1158
1159        if tip.is_none() {
1160            let verdict_path = self.root.join(".wt").join(format!("{child}.verdict.json"));
1161            let (has_accepted_verdict, is_redone) = match read_verdict_file(&verdict_path)? {
1162                Some(v) => (v == "accepted" || v == "fixed", v == "redone"),
1163                None => (false, false),
1164            };
1165
1166            if is_redone {
1167                return Ok(false);
1168            }
1169
1170            let summary_path = self.root.join(".wt").join(format!("{child}.json"));
1171            let is_verified = read_child_summary_verified(&summary_path)?;
1172
1173            let wt_gone = !self.root.join(".wt").join(child).is_dir();
1174
1175            return Ok(has_accepted_verdict || (is_verified && wt_gone));
1176        }
1177
1178        Ok(self.check_run_merged_internal(child, visited)?.is_some())
1179    }
1180
1181    pub fn check_run_merged(&mut self, id: &str) -> Result<Option<RemovalReason>, String> {
1182        let mut visited = HashSet::new();
1183        self.check_run_merged_internal(id, &mut visited)
1184    }
1185
1186    fn check_run_merged_internal(
1187        &mut self,
1188        id: &str,
1189        visited: &mut HashSet<String>,
1190    ) -> Result<Option<RemovalReason>, String> {
1191        if visited.contains(id) {
1192            return Ok(None);
1193        }
1194
1195        if let Some(cached) = self.merged_cache.get(id) {
1196            return Ok(cached.clone());
1197        }
1198
1199        visited.insert(id.to_string());
1200
1201        let branch_name = format!("wip/{id}");
1202        let tip_sha = self.get_branch_tip(&branch_name);
1203
1204        let result = self.decide_run_merged(id, tip_sha.as_deref(), visited);
1205
1206        visited.remove(id);
1207
1208        if let Ok(ref val) = result {
1209            self.merged_cache.insert(id.to_string(), val.clone());
1210        }
1211        result
1212    }
1213
1214    fn check_history_merged(
1215        &mut self,
1216        tip_sha: &str,
1217        target: &str,
1218        started_at: Option<&serde_json::Value>,
1219    ) -> bool {
1220        if self.target_is_ancestor_of(target, tip_sha) {
1221            return false;
1222        }
1223        let Some(merge_base) = self.merge_base(target, tip_sha) else {
1224            return false;
1225        };
1226        check_history_merged_with_base(self.root, tip_sha, target, &merge_base, started_at)
1227    }
1228
1229    fn is_squash_merged_into_target(&mut self, commit_sha: &str, target: &str) -> bool {
1230        if self.target_is_ancestor_of(target, commit_sha) {
1231            return false;
1232        }
1233        let Some(merge_base) = self.merge_base(target, commit_sha) else {
1234            return false;
1235        };
1236        is_squash_merged_with_base(self.root, commit_sha, target, &merge_base)
1237    }
1238
1239    fn is_cherry_merged_into_target(&mut self, commit_sha: &str, target: &str) -> bool {
1240        let key = (commit_sha.to_string(), self.target_key(target));
1241        if let Some(&cached) = self.cherry_cache.get(&key) {
1242            return cached;
1243        }
1244        let merged = is_cherry_merged_into_target(self.root, commit_sha, target);
1245        self.cherry_cache.insert(key, merged);
1246        merged
1247    }
1248
1249    fn is_merge_tree_merged_into_target(
1250        &mut self,
1251        commit_sha: &str,
1252        target: &str,
1253        target_tree: Option<&str>,
1254    ) -> bool {
1255        let key = (commit_sha.to_string(), self.target_key(target));
1256        if let Some(&cached) = self.merge_tree_cache.get(&key) {
1257            return cached;
1258        }
1259        let resolved_tree = match target_tree {
1260            Some(t) => Some(t.to_string()),
1261            None => self.tree_sha(target),
1262        };
1263        let merged = match resolved_tree.as_deref() {
1264            Some(tree) => {
1265                is_merge_tree_merged_into_target(self.root, commit_sha, target, Some(tree))
1266            }
1267            None => false,
1268        };
1269        self.merge_tree_cache.insert(key, merged);
1270        merged
1271    }
1272
1273    fn merged_into(&mut self, commit_sha: &str, target: &str) -> bool {
1274        if self.is_ancestor_of_target(commit_sha, target) {
1275            return true;
1276        }
1277        if self.is_cherry_merged_into_target(commit_sha, target) {
1278            return true;
1279        }
1280        if self.is_merge_tree_merged_into_target(commit_sha, target, None) {
1281            return true;
1282        }
1283        if self.is_squash_merged_into_target(commit_sha, target) {
1284            return true;
1285        }
1286        false
1287    }
1288
1289    pub fn is_commit_merged_with_targets(
1290        &mut self,
1291        commit_sha: &str,
1292        extra_targets: &[&str],
1293    ) -> bool {
1294        let def = self.default_branch.clone();
1295        if self.merged_into(commit_sha, &def) {
1296            return true;
1297        }
1298        if let Some(origin_def) = self.origin_default.clone() {
1299            if self.merged_into(commit_sha, &origin_def) {
1300                return true;
1301            }
1302        }
1303        for &extra in extra_targets {
1304            if self.ref_exists(extra) && self.merged_into(commit_sha, extra) {
1305                return true;
1306            }
1307        }
1308        false
1309    }
1310
1311    pub fn is_commit_merged(&mut self, commit_sha: &str) -> bool {
1312        self.is_commit_merged_with_targets(commit_sha, &[])
1313    }
1314
1315    pub fn is_branch_merged_with_targets(
1316        &mut self,
1317        branch_name: &str,
1318        extra_targets: &[&str],
1319    ) -> bool {
1320        let Some(tip) = self.get_branch_tip(branch_name) else {
1321            return false;
1322        };
1323        self.is_commit_merged_with_targets(&tip, extra_targets)
1324    }
1325
1326    pub fn is_branch_merged_checked(&mut self, branch_name: &str) -> Result<bool, String> {
1327        if let Some(id) = branch_name.strip_prefix("wip/") {
1328            Ok(self.check_run_merged(id)?.is_some())
1329        } else {
1330            Ok(self.is_branch_merged_with_targets(branch_name, &[]))
1331        }
1332    }
1333
1334    pub fn is_branch_merged(&mut self, branch_name: &str) -> bool {
1335        match self.is_branch_merged_checked(branch_name) {
1336            Ok(merged) => merged,
1337            Err(err) => {
1338                eprintln!("error: {err}");
1339                false
1340            }
1341        }
1342    }
1343
1344    fn decide_run_merged(
1345        &mut self,
1346        id: &str,
1347        tip_sha: Option<&str>,
1348        visited: &mut HashSet<String>,
1349    ) -> Result<Option<RemovalReason>, String> {
1350        let base_opt = self.start_files.get(id).and_then(|s| {
1351            s.get("base")
1352                .and_then(|b| b.as_str())
1353                .map(|b| b.to_string())
1354        });
1355        let base_targets = base_opt
1356            .as_deref()
1357            .and_then(|b| self.resolve_base_targets(b));
1358        let started_at = self
1359            .start_files
1360            .get(id)
1361            .and_then(|s| s.get("started_at"))
1362            .cloned();
1363
1364        if let Some(tip_sha) = tip_sha {
1365            if self.is_ancestor_of_default(tip_sha) {
1366                return Ok(Some(RemovalReason::Merged));
1367            }
1368
1369            if self.is_in_cherry_pick_record(tip_sha) {
1370                return Ok(Some(RemovalReason::Merged));
1371            }
1372
1373            if let Some((ref display_name, ref targets)) = base_targets {
1374                for target in targets {
1375                    if self.is_ancestor_of_target(tip_sha, target) {
1376                        return Ok(Some(RemovalReason::MergedInto(display_name.clone())));
1377                    }
1378                    if self.is_cherry_merged_into_target(tip_sha, target) {
1379                        return Ok(Some(RemovalReason::MergedInto(display_name.clone())));
1380                    }
1381                    if self.is_merge_tree_merged_into_target(tip_sha, target, None) {
1382                        return Ok(Some(RemovalReason::MergedInto(display_name.clone())));
1383                    }
1384                }
1385            }
1386        }
1387
1388        let children = self.get_children_of(id, tip_sha.unwrap_or(""));
1389        for child in children {
1390            if visited.contains(&child) {
1391                continue;
1392            }
1393            if self.is_child_run_merged(&child, visited)? {
1394                return Ok(Some(RemovalReason::MergedThrough(child)));
1395            }
1396        }
1397
1398        if let Some(tip_sha) = tip_sha {
1399            let def = self.default_branch.clone();
1400            if self.is_cherry_merged_into_target(tip_sha, &def) {
1401                return Ok(Some(RemovalReason::Merged));
1402            }
1403            if let Some(origin_def) = self.origin_default.clone() {
1404                if self.is_cherry_merged_into_target(tip_sha, &origin_def) {
1405                    return Ok(Some(RemovalReason::Merged));
1406                }
1407            }
1408
1409            let def_tree = self.default_tree.clone();
1410            if self.is_merge_tree_merged_into_target(tip_sha, &def, def_tree.as_deref()) {
1411                return Ok(Some(RemovalReason::Merged));
1412            }
1413            if let Some(origin_def) = self.origin_default.clone() {
1414                let origin_tree = self.origin_default_tree.clone();
1415                if self.is_merge_tree_merged_into_target(
1416                    tip_sha,
1417                    &origin_def,
1418                    origin_tree.as_deref(),
1419                ) {
1420                    return Ok(Some(RemovalReason::Merged));
1421                }
1422            }
1423
1424            if self.check_history_merged(tip_sha, &def, started_at.as_ref()) {
1425                return Ok(Some(RemovalReason::Merged));
1426            }
1427            if let Some(origin_def) = self.origin_default.clone() {
1428                if self.check_history_merged(tip_sha, &origin_def, started_at.as_ref()) {
1429                    return Ok(Some(RemovalReason::Merged));
1430                }
1431            }
1432            if let Some((ref display_name, ref targets)) = base_targets {
1433                for target in targets {
1434                    if self.check_history_merged(tip_sha, target, started_at.as_ref()) {
1435                        return Ok(Some(RemovalReason::MergedInto(display_name.clone())));
1436                    }
1437                }
1438            }
1439
1440            if let Some(reason) = self.squash_merged_reason(tip_sha, &base_targets) {
1441                return Ok(Some(reason));
1442            }
1443        }
1444
1445        Ok(None)
1446    }
1447
1448    fn squash_merged_reason(
1449        &mut self,
1450        tip_sha: &str,
1451        base_targets: &Option<(String, Vec<String>)>,
1452    ) -> Option<RemovalReason> {
1453        let def = self.default_branch.clone();
1454        if self.is_squash_merged_into_target(tip_sha, &def) {
1455            return Some(RemovalReason::Merged);
1456        }
1457        if let Some(origin_def) = self.origin_default.clone() {
1458            if self.is_squash_merged_into_target(tip_sha, &origin_def) {
1459                return Some(RemovalReason::Merged);
1460            }
1461        }
1462        if let Some((ref display_name, ref targets)) = base_targets {
1463            for target in targets {
1464                if self.is_squash_merged_into_target(tip_sha, target) {
1465                    return Some(RemovalReason::MergedInto(display_name.clone()));
1466                }
1467            }
1468        }
1469        None
1470    }
1471
1472    pub fn find_merged_followup(&mut self, id: &str) -> Result<Option<String>, String> {
1473        let branch_name = format!("wip/{id}");
1474        let tip_sha = self.get_branch_tip(&branch_name);
1475        let mut visited = HashSet::new();
1476        visited.insert(id.to_string());
1477        let children = self.get_children_of(id, tip_sha.as_deref().unwrap_or(""));
1478        for child in children {
1479            if self.is_child_run_merged(&child, &mut visited)? {
1480                return Ok(Some(child));
1481            }
1482        }
1483        Ok(None)
1484    }
1485
1486    pub fn check_removable(
1487        &mut self,
1488        id: &str,
1489        older_than_days: u64,
1490    ) -> Result<RemovalReason, KeptReason> {
1491        let wt_dir = self.root.join(".wt");
1492        let summary_path = wt_dir.join(format!("{id}.json"));
1493        let verdict_path = wt_dir.join(format!("{id}.verdict.json"));
1494        let report_path = wt_dir.join(format!("{id}.report.md"));
1495
1496        match read_start_record(self.root, id) {
1497            Err(reason) => return Err(KeptReason::UnreadableStartRecord(reason)),
1498            Ok(Some(value)) => {
1499                self.start_files.insert(id.to_string(), value);
1500            }
1501            Ok(None) => {
1502                self.start_files.remove(id);
1503            }
1504        }
1505        let start_json = self.start_files.get(id);
1506        let summary_exists = summary_path.is_file();
1507
1508        // Check if run is finished: no live process (pid not running) or a summary from this run exists.
1509        if let Some(start) = start_json {
1510            if let Some(pid) = start.get("pid").and_then(|p| p.as_i64()) {
1511                if is_pid_alive(pid) {
1512                    if !summary_exists {
1513                        return Err(KeptReason::Running);
1514                    }
1515                    let Some(started_at) = parse_started_at(start) else {
1516                        return Err(KeptReason::Running);
1517                    };
1518                    let summary_mtime = std::fs::metadata(&summary_path)
1519                        .ok()
1520                        .and_then(|m| m.modified().ok())
1521                        .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
1522                        .map(|d| d.as_secs());
1523                    if summary_mtime.is_none_or(|mtime| mtime < started_at) {
1524                        return Err(KeptReason::Running);
1525                    }
1526                }
1527            }
1528        }
1529
1530        let is_res = self.is_research_run(id);
1531
1532        // Rule 2: Discarded (the verdict is redone, or the outcome is no_changes)
1533        let verdict_str = match read_verdict_file(&verdict_path) {
1534            Ok(Some(v)) => v,
1535            Ok(None) => String::new(),
1536            Err(err) => return Err(KeptReason::UnreadableVerdict(err)),
1537        };
1538
1539        if verdict_str == "redone" {
1540            return Ok(RemovalReason::Verdict("redone".to_string()));
1541        }
1542
1543        if summary_exists {
1544            if let Ok(summary_str) = std::fs::read_to_string(&summary_path) {
1545                if let Ok(val) = serde_json::from_str::<serde_json::Value>(&summary_str) {
1546                    if val.get("outcome").and_then(|o| o.as_str()) == Some("no_changes") {
1547                        return Ok(RemovalReason::NoChanges);
1548                    }
1549                }
1550            }
1551        }
1552
1553        // Rule 3: Research run and its report was copied out (.wt/<id>.report.md exists)
1554        if is_res && report_path.is_file() {
1555            return Ok(RemovalReason::ResearchReport);
1556        }
1557
1558        if is_res {
1559            let wt_report_path = wt_dir.join(id).join("report.md");
1560            if wt_report_path.is_file() && !report_path.is_file() {
1561                return Ok(RemovalReason::ResearchReportInWorktree);
1562            }
1563            if summary_exists {
1564                let outcome = std::fs::read_to_string(&summary_path)
1565                    .ok()
1566                    .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
1567                    .and_then(|v| {
1568                        v.get("outcome")
1569                            .and_then(|o| o.as_str())
1570                            .filter(|s| !s.is_empty())
1571                            .map(|s| s.to_string())
1572                    });
1573                return match outcome {
1574                    Some(outcome) => Ok(RemovalReason::ResearchEndedWithoutReport(outcome)),
1575                    None => Err(KeptReason::UnreadableSummary),
1576                };
1577            }
1578            let start_path = wt_dir.join(format!("{id}.start.json"));
1579            if let Ok(meta) = std::fs::metadata(&start_path) {
1580                if let Ok(mtime) = meta.modified() {
1581                    let age = std::time::SystemTime::now()
1582                        .duration_since(mtime)
1583                        .unwrap_or(std::time::Duration::ZERO);
1584                    if age >= std::time::Duration::from_secs(older_than_days.saturating_mul(86400))
1585                    {
1586                        return Ok(RemovalReason::ResearchStoppedWithoutSummary(
1587                            older_than_days,
1588                        ));
1589                    }
1590                }
1591            }
1592        }
1593
1594        // Rule 1: Merged (its work is on the default branch or base branch or follow-up)
1595        if !is_res {
1596            match self.check_run_merged(id) {
1597                Ok(Some(reason)) => return Ok(reason),
1598                Ok(None) => {}
1599                Err(err) => return Err(KeptReason::UnreadableChildState(err)),
1600            }
1601        }
1602
1603        // Rule 4: Finished more than older_than days ago, by the summary file's mtime
1604        if summary_exists {
1605            if let Ok(meta) = std::fs::metadata(&summary_path) {
1606                if let Ok(mtime) = meta.modified() {
1607                    let age = std::time::SystemTime::now()
1608                        .duration_since(mtime)
1609                        .unwrap_or(std::time::Duration::ZERO);
1610                    if age >= std::time::Duration::from_secs(older_than_days.saturating_mul(86400))
1611                    {
1612                        return Ok(RemovalReason::OlderThan(older_than_days));
1613                    }
1614                }
1615            }
1616        }
1617
1618        // A verdict of accepted or fixed on its own no longer makes a worktree removable
1619        if !verdict_str.is_empty() {
1620            return Err(KeptReason::NotMergedYet);
1621        }
1622
1623        if is_res {
1624            Err(KeptReason::NoReport)
1625        } else {
1626            Err(KeptReason::NoVerdict)
1627        }
1628    }
1629}
1630
1631/// Evaluates whether a worktree is removable according to the clean rules.
1632pub fn check_removable(
1633    root: &Path,
1634    id: &str,
1635    older_than_days: u64,
1636) -> Result<RemovalReason, KeptReason> {
1637    let mut ctx = CleanContext::new(root);
1638    ctx.check_removable(id, older_than_days)
1639}
1640
1641/// Identifies the default branch (origin/HEAD's target, else main, else master).
1642pub fn find_default_branch(root: &Path) -> String {
1643    let sym_out = std::process::Command::new("git")
1644        .args(["symbolic-ref", "--short", "refs/remotes/origin/HEAD"])
1645        .current_dir(root)
1646        .output();
1647    if let Ok(o) = sym_out {
1648        if o.status.success() {
1649            let target = String::from_utf8_lossy(&o.stdout);
1650            let target = target.trim();
1651            let branch_name = target.strip_prefix("origin/").unwrap_or(target);
1652            let local_check = std::process::Command::new("git")
1653                .args([
1654                    "rev-parse",
1655                    "--verify",
1656                    &format!("refs/heads/{branch_name}"),
1657                ])
1658                .current_dir(root)
1659                .output();
1660            if local_check.map(|c| c.status.success()).unwrap_or(false) {
1661                return branch_name.to_string();
1662            }
1663            let remote_check = std::process::Command::new("git")
1664                .args(["rev-parse", "--verify", target])
1665                .current_dir(root)
1666                .output();
1667            if remote_check.map(|c| c.status.success()).unwrap_or(false) {
1668                return target.to_string();
1669            }
1670            return branch_name.to_string();
1671        }
1672    }
1673
1674    let main_check = std::process::Command::new("git")
1675        .args(["rev-parse", "--verify", "refs/heads/main"])
1676        .current_dir(root)
1677        .output();
1678    if main_check.map(|c| c.status.success()).unwrap_or(false) {
1679        return "main".to_string();
1680    }
1681
1682    let master_check = std::process::Command::new("git")
1683        .args(["rev-parse", "--verify", "refs/heads/master"])
1684        .current_dir(root)
1685        .output();
1686    if master_check.map(|c| c.status.success()).unwrap_or(false) {
1687        return "master".to_string();
1688    }
1689
1690    "main".to_string()
1691}
1692
1693/// Determines if a string is a commit SHA (hex-only, length 7 to 64).
1694fn is_commit_id(s: &str) -> bool {
1695    (s.len() >= 7 && s.len() <= 64) && s.chars().all(|c| c.is_ascii_hexdigit())
1696}
1697
1698fn resolve_base_targets_with<F>(base: &str, mut ref_exists: F) -> Option<(String, Vec<String>)>
1699where
1700    F: FnMut(&str) -> bool,
1701{
1702    let base = base.trim();
1703    if base.is_empty() {
1704        return None;
1705    }
1706
1707    if base == "HEAD"
1708        || base.starts_with("HEAD~")
1709        || base.starts_with("HEAD^")
1710        || base.starts_with("HEAD@")
1711        || base.starts_with("HEAD:")
1712    {
1713        return None;
1714    }
1715
1716    if base == "FETCH_HEAD" || base == "ORIG_HEAD" || base == "MERGE_HEAD" {
1717        return None;
1718    }
1719
1720    if is_commit_id(base) {
1721        return None;
1722    }
1723
1724    let clean = if let Some(stripped) = base.strip_prefix("refs/heads/") {
1725        stripped
1726    } else if let Some(stripped) = base.strip_prefix("refs/remotes/") {
1727        stripped
1728    } else {
1729        base
1730    };
1731
1732    let is_wip = clean == "wip"
1733        || clean.starts_with("wip/")
1734        || clean == "origin/wip"
1735        || clean.starts_with("origin/wip/");
1736    if is_wip {
1737        return None;
1738    }
1739
1740    let (display_name, candidates) = if let Some(without_origin) = clean.strip_prefix("origin/") {
1741        if without_origin.is_empty()
1742            || without_origin == "wip"
1743            || without_origin.starts_with("wip/")
1744            || without_origin == "HEAD"
1745            || without_origin.starts_with("HEAD~")
1746            || without_origin.starts_with("HEAD^")
1747            || is_commit_id(without_origin)
1748        {
1749            return None;
1750        }
1751        let cand1 = format!("refs/remotes/{clean}");
1752        let cand2 = format!("refs/heads/{without_origin}");
1753        (without_origin.to_string(), vec![cand1, cand2])
1754    } else {
1755        let cand1 = format!("refs/heads/{clean}");
1756        let cand2 = format!("refs/remotes/origin/{clean}");
1757        (clean.to_string(), vec![cand1, cand2])
1758    };
1759
1760    let mut resolved = Vec::new();
1761    for cand in candidates {
1762        if ref_exists(&cand) {
1763            resolved.push(cand);
1764        }
1765    }
1766
1767    if resolved.is_empty() {
1768        None
1769    } else {
1770        Some((display_name, resolved))
1771    }
1772}
1773
1774/// Resolves candidate git refs for a run's base branch.
1775/// Returns (display_name, targets) if `base` is a branch name that resolves.
1776/// Returns None if `base` is not a branch name (e.g. HEAD, commit id, wip/ branch)
1777/// or if none of the candidate refs resolve in git.
1778pub fn resolve_base_targets(root: &Path, base: &str) -> Option<(String, Vec<String>)> {
1779    resolve_base_targets_with(base, |cand| {
1780        git_ok(root, &["rev-parse", "--verify", "--quiet", cand])
1781    })
1782}
1783
1784/// Reads `base` from `.wt/<id>.start.json` if present.
1785pub fn read_run_base(root: &Path, id: &str) -> Option<String> {
1786    let start_path = root.join(".wt").join(format!("{id}.start.json"));
1787    std::fs::read_to_string(&start_path)
1788        .ok()
1789        .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
1790        .and_then(|v| {
1791            v.get("base")
1792                .and_then(|b| b.as_str())
1793                .map(|s| s.to_string())
1794        })
1795}
1796
1797/// Returns the commit SHA at the tip of `branch_name` if it exists.
1798pub fn get_branch_tip(root: &Path, branch_name: &str) -> Option<String> {
1799    let check = std::process::Command::new("git")
1800        .args([
1801            "rev-parse",
1802            "--verify",
1803            &format!("refs/heads/{branch_name}"),
1804        ])
1805        .current_dir(root)
1806        .output()
1807        .ok()?;
1808    if !check.status.success() {
1809        return None;
1810    }
1811
1812    let tip_out = std::process::Command::new("git")
1813        .args(["rev-parse", &format!("refs/heads/{branch_name}")])
1814        .current_dir(root)
1815        .output()
1816        .ok()?;
1817    if tip_out.status.success() {
1818        Some(String::from_utf8_lossy(&tip_out.stdout).trim().to_string())
1819    } else {
1820        None
1821    }
1822}
1823
1824/// Checks whether a branch's work is on the default branch when any of:
1825/// - `git merge-base --is-ancestor <tip> <default>` succeeds;
1826/// - every commit `git cherry <default> <branch>` lists is marked `-`;
1827/// - merging it would change nothing: `git merge-tree --write-tree <default> <branch>` exits 0
1828///   and the tree id it prints (first line) equals `git rev-parse <default>^{tree}`;
1829/// - 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).
1830pub fn is_branch_merged(root: &Path, branch_name: &str) -> bool {
1831    let mut ctx = CleanContext::new(root);
1832    ctx.is_branch_merged(branch_name)
1833}
1834
1835/// Checks whether a branch's work is on the default branch or any of the extra target refs.
1836pub fn is_branch_merged_with_targets(
1837    root: &Path,
1838    branch_name: &str,
1839    extra_targets: &[&str],
1840) -> bool {
1841    let mut ctx = CleanContext::new(root);
1842    ctx.is_branch_merged_with_targets(branch_name, extra_targets)
1843}
1844
1845/// Checks whether a branch's work is on the default branch or any of the extra target refs.
1846pub fn is_branch_merged_with_extra_targets(
1847    root: &Path,
1848    branch_name: &str,
1849    extra_targets: &[&str],
1850) -> bool {
1851    is_branch_merged_with_targets(root, branch_name, extra_targets)
1852}
1853
1854/// Checks whether a commit's work is on the default branch when any of:
1855/// - `git merge-base --is-ancestor <commit> <default>` succeeds;
1856/// - every commit `git cherry <default> <commit>` lists is marked `-`;
1857/// - merging it would change nothing: `git merge-tree --write-tree <default> <commit>` exits 0
1858///   and the tree id it prints equals `git rev-parse <default>^{tree}`.
1859pub fn is_commit_merged(root: &Path, commit_sha: &str) -> bool {
1860    let mut ctx = CleanContext::new(root);
1861    ctx.is_commit_merged(commit_sha)
1862}
1863
1864/// Checks whether a commit's work is on the default branch or any of the extra target refs.
1865pub fn is_commit_merged_with_targets(
1866    root: &Path,
1867    commit_sha: &str,
1868    extra_targets: &[&str],
1869) -> bool {
1870    let mut ctx = CleanContext::new(root);
1871    ctx.is_commit_merged_with_targets(commit_sha, extra_targets)
1872}
1873
1874fn git_ok(root: &Path, args: &[&str]) -> bool {
1875    std::process::Command::new("git")
1876        .args(args)
1877        .current_dir(root)
1878        .output()
1879        .map(|o| o.status.success())
1880        .unwrap_or(false)
1881}
1882
1883fn is_squash_merged_with_base(root: &Path, commit_sha: &str, target: &str, base: &str) -> bool {
1884    let subj_out = std::process::Command::new("git")
1885        .args([
1886            "log",
1887            "--no-merges",
1888            "--format=%s",
1889            &format!("{target}..{commit_sha}"),
1890        ])
1891        .current_dir(root)
1892        .output();
1893    let Ok(subj_o) = subj_out else {
1894        return false;
1895    };
1896    if !subj_o.status.success() {
1897        return false;
1898    }
1899    let subj_stdout = String::from_utf8_lossy(&subj_o.stdout);
1900    let subjects: Vec<&str> = subj_stdout
1901        .lines()
1902        .map(|l| l.trim())
1903        .filter(|l| !l.is_empty())
1904        .collect();
1905    if subjects.is_empty() {
1906        return false;
1907    }
1908
1909    let hay_out = std::process::Command::new("git")
1910        .args(["log", "--format=%B", &format!("{base}..{target}")])
1911        .current_dir(root)
1912        .output();
1913    let Ok(hay_o) = hay_out else {
1914        return false;
1915    };
1916    if !hay_o.status.success() {
1917        return false;
1918    }
1919    let hay_stdout = String::from_utf8_lossy(&hay_o.stdout);
1920    let mut haystack_lines = HashSet::new();
1921    for line in hay_stdout.lines() {
1922        let trimmed = line.trim();
1923        if trimmed.is_empty() {
1924            continue;
1925        }
1926        haystack_lines.insert(trimmed.to_string());
1927        if let Some(stripped) = trimmed
1928            .strip_prefix("* ")
1929            .or_else(|| trimmed.strip_prefix("- "))
1930        {
1931            let stripped = stripped.trim();
1932            if !stripped.is_empty() {
1933                haystack_lines.insert(stripped.to_string());
1934            }
1935        }
1936    }
1937
1938    subjects.iter().all(|s| haystack_lines.contains(*s))
1939}
1940
1941/// Lists all run IDs that have a corresponding `.wt/<id>.start.json`.
1942pub fn list_all_run_ids(root: &Path) -> Vec<String> {
1943    let wt_dir = root.join(".wt");
1944    let mut ids = Vec::new();
1945    if let Ok(entries) = std::fs::read_dir(&wt_dir) {
1946        for entry in entries.flatten() {
1947            let name = entry.file_name().to_string_lossy().to_string();
1948            if let Some(id) = name.strip_suffix(".start.json") {
1949                ids.push(id.to_string());
1950            }
1951        }
1952    }
1953    ids.sort();
1954    ids
1955}
1956
1957/// Finds a follow-up run that makes `<id>` merged.
1958pub fn find_merged_followup(root: &Path, id: &str) -> Result<Option<String>, String> {
1959    let mut ctx = CleanContext::new(root);
1960    ctx.find_merged_followup(id)
1961}
1962
1963/// Lists all `.wt/<id>` directories that have a corresponding `.wt/<id>.start.json`.
1964pub fn find_blyte_worktrees(root: &Path) -> Vec<String> {
1965    let wt_dir = root.join(".wt");
1966    if !wt_dir.is_dir() {
1967        return Vec::new();
1968    }
1969    let mut ids = Vec::new();
1970    if let Ok(entries) = std::fs::read_dir(&wt_dir) {
1971        for entry in entries.flatten() {
1972            if let Ok(ft) = entry.file_type() {
1973                if ft.is_dir() {
1974                    let name = entry.file_name().to_string_lossy().to_string();
1975                    let start_file = wt_dir.join(format!("{name}.start.json"));
1976                    if start_file.is_file() {
1977                        ids.push(name);
1978                    }
1979                }
1980            }
1981        }
1982    }
1983    ids.sort();
1984    ids
1985}
1986
1987#[derive(Debug, Default)]
1988pub struct CleanRepoStats {
1989    pub removed_worktrees: usize,
1990    pub freed_bytes: u64,
1991    pub had_errors: bool,
1992}
1993
1994/// Default idle threshold in days for session worktrees.
1995pub const DEFAULT_SESSION_IDLE_DAYS: u64 = 7;
1996
1997/// Parses `lsof -a -d cwd -Fn` output into a list of working directory paths.
1998pub fn parse_lsof_cwd_output(stdout: &str) -> Vec<PathBuf> {
1999    stdout
2000        .lines()
2001        .filter_map(|line| line.strip_prefix('n'))
2002        .filter(|path| !path.is_empty())
2003        .map(PathBuf::from)
2004        .collect()
2005}
2006
2007/// Lists the current working directories of all running processes via `lsof -a -d cwd -Fn`.
2008pub fn list_running_process_cwds() -> Result<Vec<PathBuf>, String> {
2009    let out = std::process::Command::new("lsof")
2010        .args(["-a", "-d", "cwd", "-Fn"])
2011        .output()
2012        .map_err(|e| e.to_string())?;
2013    // A failed lsof may have listed only some processes, so its output is not trusted.
2014    if !out.status.success() {
2015        let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string();
2016        if stderr.is_empty() {
2017            return Err(format!("lsof exited with {}", out.status));
2018        }
2019        return Err(format!("lsof exited with {}: {stderr}", out.status));
2020    }
2021    let paths = parse_lsof_cwd_output(&String::from_utf8_lossy(&out.stdout));
2022    if paths.is_empty() {
2023        return Err("lsof listed no working directories".to_string());
2024    }
2025    Ok(paths)
2026}
2027
2028/// Returns true if `wt_path` is a session worktree of `root`:
2029/// - directly under `<root>/.wt/` with no `<root>/.wt/<name>.start.json`, or
2030/// - under `<root>/.claude/worktrees/` (excluding any nested `.wt` run worktrees).
2031pub fn is_session_worktree(root: &Path, wt_path: &Path) -> bool {
2032    let root_canon = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
2033    let wt_canon = wt_path
2034        .canonicalize()
2035        .unwrap_or_else(|_| wt_path.to_path_buf());
2036    let Some(wt_parent) = wt_canon.parent() else {
2037        return false;
2038    };
2039    let Some(wt_name) = wt_canon.file_name().and_then(|n| n.to_str()) else {
2040        return false;
2041    };
2042
2043    let wt_dir_canon = root_canon
2044        .join(".wt")
2045        .canonicalize()
2046        .unwrap_or_else(|_| root_canon.join(".wt"));
2047    if wt_parent == wt_dir_canon {
2048        let start_file = wt_dir_canon.join(format!("{wt_name}.start.json"));
2049        return !start_file.is_file();
2050    }
2051
2052    let claude_wt_dir_canon = root_canon
2053        .join(".claude")
2054        .join("worktrees")
2055        .canonicalize()
2056        .unwrap_or_else(|_| root_canon.join(".claude").join("worktrees"));
2057    if let Ok(rel) = wt_canon.strip_prefix(&claude_wt_dir_canon) {
2058        if !rel.as_os_str().is_empty() && !has_wt_component(rel) {
2059            return true;
2060        }
2061    }
2062
2063    false
2064}
2065
2066/// Returns true if `<wt_path>/.wt/` contains any `*.start.json` file.
2067pub fn has_dispatched_runs(wt_path: &Path) -> bool {
2068    let wt_dir = wt_path.join(".wt");
2069    let Ok(entries) = std::fs::read_dir(&wt_dir) else {
2070        return false;
2071    };
2072    for entry in entries.flatten() {
2073        let name = entry.file_name();
2074        if name.to_string_lossy().ends_with(".start.json")
2075            && entry.file_type().map(|ft| ft.is_file()).unwrap_or(false)
2076        {
2077            return true;
2078        }
2079    }
2080    false
2081}
2082
2083/// Returns true if any process working directory in `cwds` is `wt_path` or a subdirectory of it.
2084/// Compares canonical paths.
2085pub fn is_worktree_in_use(wt_path: &Path, cwds: &[PathBuf]) -> bool {
2086    let wt_canon = wt_path
2087        .canonicalize()
2088        .unwrap_or_else(|_| wt_path.to_path_buf());
2089    cwds.iter().any(|cwd| {
2090        let cwd_canon = cwd.canonicalize().unwrap_or_else(|_| cwd.clone());
2091        cwd_canon.starts_with(&wt_canon)
2092    })
2093}
2094
2095/// Returns whether `index` and `HEAD` in the worktree's git admin directory
2096/// (`git -C <wt> rev-parse --absolute-git-dir`) are both more than `idle_days` days old.
2097/// Errors name what could not be read.
2098pub fn is_worktree_idle(wt_path: &Path, idle_days: u64) -> Result<bool, String> {
2099    let o = std::process::Command::new("git")
2100        .arg("-C")
2101        .arg(wt_path.as_os_str())
2102        .args(["rev-parse", "--absolute-git-dir"])
2103        .output()
2104        .map_err(|e| format!("cannot run git: {e}"))?;
2105    if !o.status.success() {
2106        return Err(format!(
2107            "git rev-parse --absolute-git-dir failed: {}",
2108            String::from_utf8_lossy(&o.stderr).trim()
2109        ));
2110    }
2111    let git_dir_str = String::from_utf8_lossy(&o.stdout).trim().to_string();
2112    if git_dir_str.is_empty() {
2113        return Err("git rev-parse --absolute-git-dir printed nothing".to_string());
2114    }
2115    let git_dir = PathBuf::from(git_dir_str);
2116    let now = std::time::SystemTime::now();
2117    let threshold = std::time::Duration::from_secs(idle_days.saturating_mul(86400));
2118    for name in ["index", "HEAD"] {
2119        let p = git_dir.join(name);
2120        let mtime = std::fs::metadata(&p)
2121            .and_then(|m| m.modified())
2122            .map_err(|e| format!("cannot read the time of {}: {e}", p.display()))?;
2123        let age = now
2124            .duration_since(mtime)
2125            .unwrap_or(std::time::Duration::ZERO);
2126        if idle_days > 0 && age <= threshold {
2127            return Ok(false);
2128        }
2129    }
2130    Ok(true)
2131}
2132
2133fn check_session_worktree_removable_with_ctx(
2134    ctx: &mut CleanContext<'_>,
2135    wt: &GitWorktreeInfo,
2136    cwds: &Result<Vec<PathBuf>, String>,
2137    idle_days: u64,
2138) -> Result<RemovalReason, KeptReason> {
2139    let is_merged = if let Some(ref branch) = wt.branch {
2140        ctx.is_branch_merged_checked(branch)
2141            .map_err(KeptReason::UnreadableChildState)?
2142    } else if let Some(ref sha) = wt.head_sha {
2143        ctx.is_commit_merged(sha)
2144    } else {
2145        false
2146    };
2147    if !is_merged {
2148        return Err(KeptReason::NotMergedYet);
2149    }
2150
2151    if has_dispatched_runs(&wt.path) {
2152        let display_path = display_worktree_path(&wt.path, ctx.root);
2153        return Err(KeptReason::HoldsRuns(display_path));
2154    }
2155
2156    if !is_worktree_clean(&wt.path) {
2157        return Err(KeptReason::UncommittedChanges);
2158    }
2159
2160    match cwds {
2161        Ok(list) => {
2162            if is_worktree_in_use(&wt.path, list) {
2163                return Err(KeptReason::InUse);
2164            }
2165        }
2166        Err(err) => {
2167            return Err(KeptReason::CannotCheckInUse(err.clone()));
2168        }
2169    }
2170
2171    match is_worktree_idle(&wt.path, idle_days) {
2172        Ok(true) => {}
2173        Ok(false) => return Err(KeptReason::UsedRecently(idle_days)),
2174        Err(e) => {
2175            return Err(KeptReason::Custom(format!(
2176                "cannot tell when it was last used: {e}"
2177            )))
2178        }
2179    }
2180
2181    let branch_label = wt.branch.clone().unwrap_or_else(|| {
2182        wt.head_sha
2183            .as_deref()
2184            .map(|s| s[..s.len().min(7)].to_string())
2185            .unwrap_or_else(|| "detached".to_string())
2186    });
2187    Ok(RemovalReason::SessionMerged(branch_label))
2188}
2189
2190/// Evaluates whether a session worktree is removable.
2191pub fn check_session_worktree_removable(
2192    root: &Path,
2193    wt: &GitWorktreeInfo,
2194    cwds: &Result<Vec<PathBuf>, String>,
2195    idle_days: u64,
2196) -> Result<RemovalReason, KeptReason> {
2197    let mut ctx = CleanContext::new(root);
2198    check_session_worktree_removable_with_ctx(&mut ctx, wt, cwds, idle_days)
2199}
2200
2201fn branch_checked_out_elsewhere(
2202    worktrees: &[GitWorktreeInfo],
2203    removed_wt_paths: &HashSet<PathBuf>,
2204    current_wt_canon: &Path,
2205    branch_name: &str,
2206) -> bool {
2207    for wt in worktrees {
2208        if !wt.path.exists() {
2209            continue;
2210        }
2211        let wt_canon = wt
2212            .path
2213            .canonicalize()
2214            .unwrap_or_else(|_| wt.path.to_path_buf());
2215        if wt_canon == current_wt_canon || removed_wt_paths.contains(&wt_canon) {
2216            continue;
2217        }
2218        if wt.branch.as_deref() == Some(branch_name) {
2219            return true;
2220        }
2221    }
2222    false
2223}
2224
2225/// Cleans one repository.
2226pub fn clean_repo(
2227    root: &Path,
2228    older_than_days: u64,
2229    dry_run: bool,
2230    skip_id: Option<&str>,
2231    quiet: bool,
2232) -> CleanRepoStats {
2233    clean_repo_with_options(
2234        root,
2235        older_than_days,
2236        dry_run,
2237        skip_id,
2238        quiet,
2239        DEFAULT_SESSION_IDLE_DAYS,
2240        None,
2241    )
2242}
2243
2244/// Cleans one repository with configurable session worktree idle threshold and process cwd list.
2245pub fn clean_repo_with_options(
2246    root: &Path,
2247    older_than_days: u64,
2248    dry_run: bool,
2249    skip_id: Option<&str>,
2250    quiet: bool,
2251    session_idle_days: u64,
2252    process_cwds: Option<Result<Vec<PathBuf>, String>>,
2253) -> CleanRepoStats {
2254    let mut removed_worktrees = 0;
2255    let mut freed_bytes = 0;
2256    let mut had_errors = false;
2257    let mut needs_worktree_prune = false;
2258
2259    let mut ctx = CleanContext::new(root);
2260    let is_linked = is_linked_worktree(root);
2261    let all_worktrees = if !is_linked {
2262        parse_worktree_list(root)
2263    } else {
2264        Vec::new()
2265    };
2266
2267    let ids = find_blyte_worktrees(root);
2268    for id in ids {
2269        if skip_id == Some(&id) {
2270            continue;
2271        }
2272
2273        let wt_path = root.join(".wt").join(&id);
2274        match ctx.check_removable(&id, older_than_days) {
2275            Err(kept_reason) => {
2276                if matches!(
2277                    kept_reason,
2278                    KeptReason::UnreadableVerdict(_) | KeptReason::UnreadableChildState(_)
2279                ) {
2280                    eprintln!("error: {kept_reason}");
2281                    had_errors = true;
2282                }
2283                if !quiet {
2284                    println!("kept .wt/{id} ({kept_reason})");
2285                }
2286            }
2287            Ok(removal_reason) => {
2288                let is_res = ctx.is_research_run(&id);
2289                if !is_res && has_uncommitted_changes(&wt_path) {
2290                    if !quiet {
2291                        println!("kept .wt/{id} (uncommitted changes)");
2292                    }
2293                    continue;
2294                }
2295
2296                let size = dir_size(&wt_path);
2297                let branch_name = format!("wip/{id}");
2298                let branch_exists = ctx.get_branch_tip(&branch_name).is_some();
2299                let is_merged = if !branch_exists {
2300                    false
2301                } else if matches!(
2302                    removal_reason,
2303                    RemovalReason::Merged
2304                        | RemovalReason::MergedInto(_)
2305                        | RemovalReason::MergedThrough(_)
2306                ) {
2307                    true
2308                } else {
2309                    match ctx.check_run_merged(&id) {
2310                        Ok(Some(_)) => true,
2311                        Ok(None) => false,
2312                        Err(err) => {
2313                            eprintln!("error: {err}");
2314                            had_errors = true;
2315                            if !quiet {
2316                                println!("kept .wt/{id} (unreadable child state: {err})");
2317                            }
2318                            continue;
2319                        }
2320                    }
2321                };
2322
2323                if dry_run {
2324                    if !quiet {
2325                        println!(
2326                            "would remove .wt/{id} ({removal_reason}, {})",
2327                            format_size(size)
2328                        );
2329                        if is_merged {
2330                            println!("would delete branch {branch_name} (merged)");
2331                        }
2332                    }
2333                    freed_bytes += size;
2334                    removed_worktrees += 1;
2335                } else {
2336                    if removal_reason == RemovalReason::ResearchReportInWorktree {
2337                        let src = wt_path.join("report.md");
2338                        let dst = root.join(".wt").join(format!("{id}.report.md"));
2339                        if let Err(err) = std::fs::copy(&src, &dst) {
2340                            eprintln!(
2341                                "error: could not copy {} to {}: {err}",
2342                                src.display(),
2343                                dst.display()
2344                            );
2345                            if !quiet {
2346                                println!("kept .wt/{id} (report copy failed)");
2347                            }
2348                            continue;
2349                        }
2350                    }
2351
2352                    if let Err(reason) = ctx.check_removable(&id, older_than_days) {
2353                        if matches!(
2354                            reason,
2355                            KeptReason::UnreadableVerdict(_) | KeptReason::UnreadableChildState(_)
2356                        ) {
2357                            eprintln!("error: {reason}");
2358                            had_errors = true;
2359                        }
2360                        if !quiet {
2361                            println!("kept .wt/{id} ({reason})");
2362                        }
2363                        continue;
2364                    }
2365
2366                    let had_prior_record = crate::removal_record::path(root, &id).exists();
2367                    if let Err(err) =
2368                        crate::removal_record::record_removal(root, &id, &removal_reason)
2369                    {
2370                        eprintln!("error: could not write removal record for {id}: {err}");
2371                        had_errors = true;
2372                        if !quiet {
2373                            println!("kept .wt/{id} (removal record write failed)");
2374                        }
2375                        continue;
2376                    }
2377
2378                    let removed_ok = if is_res {
2379                        std::fs::remove_dir_all(&wt_path).is_ok()
2380                    } else {
2381                        let rm_out = std::process::Command::new("git")
2382                            .args(["worktree", "remove", wt_path.to_str().unwrap_or("")])
2383                            .current_dir(root)
2384                            .output();
2385                        needs_worktree_prune = true;
2386                        rm_out.map(|o| o.status.success()).unwrap_or(false)
2387                    };
2388
2389                    if removed_ok {
2390                        freed_bytes += size;
2391                        removed_worktrees += 1;
2392                        if !quiet {
2393                            println!("removed .wt/{id} ({removal_reason}, {})", format_size(size));
2394                        }
2395                        if is_merged {
2396                            let del_out = std::process::Command::new("git")
2397                                .args(["branch", "-D", &branch_name])
2398                                .current_dir(root)
2399                                .output();
2400                            if del_out.map(|o| o.status.success()).unwrap_or(false) {
2401                                ctx.remove_branch(&branch_name);
2402                                if !quiet {
2403                                    println!("deleted branch {branch_name} (merged)");
2404                                }
2405                            }
2406                        }
2407                    } else {
2408                        if !had_prior_record {
2409                            let _ = std::fs::remove_file(crate::removal_record::path(root, &id));
2410                        }
2411                        if !quiet {
2412                            println!("kept .wt/{id} (worktree remove failed)");
2413                        }
2414                    }
2415                }
2416            }
2417        }
2418    }
2419
2420    if !is_linked {
2421        let root_canon = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
2422        let main_canon = all_worktrees
2423            .first()
2424            .map(|wt| wt.path.canonicalize().unwrap_or_else(|_| wt.path.clone()));
2425
2426        let mut session_indices: Vec<(String, usize)> = all_worktrees
2427            .iter()
2428            .enumerate()
2429            .skip(1)
2430            .filter_map(|(idx, wt)| {
2431                if wt.is_bare || !wt.path.exists() {
2432                    return None;
2433                }
2434                let wt_canon = wt.path.canonicalize().unwrap_or_else(|_| wt.path.clone());
2435                if wt_canon == root_canon || Some(&wt_canon) == main_canon.as_ref() {
2436                    return None;
2437                }
2438                if !is_session_worktree(root, &wt.path) {
2439                    return None;
2440                }
2441                Some((display_worktree_path(&wt.path, root), idx))
2442            })
2443            .collect();
2444        session_indices.sort_by(|a, b| a.0.cmp(&b.0));
2445
2446        if !session_indices.is_empty() {
2447            let cwds = process_cwds.unwrap_or_else(list_running_process_cwds);
2448            let mut removed_wt_paths = HashSet::new();
2449
2450            for (display_path, idx) in session_indices {
2451                let wt = &all_worktrees[idx];
2452                let wt_canon = wt.path.canonicalize().unwrap_or_else(|_| wt.path.clone());
2453                match check_session_worktree_removable_with_ctx(
2454                    &mut ctx,
2455                    wt,
2456                    &cwds,
2457                    session_idle_days,
2458                ) {
2459                    Err(kept_reason) => {
2460                        if matches!(
2461                            kept_reason,
2462                            KeptReason::UnreadableVerdict(_) | KeptReason::UnreadableChildState(_)
2463                        ) {
2464                            eprintln!("error: {kept_reason}");
2465                            had_errors = true;
2466                        }
2467                        if !quiet {
2468                            println!("kept {display_path} ({kept_reason})");
2469                        }
2470                    }
2471                    Ok(removal_reason) => {
2472                        let size = dir_size(&wt.path);
2473                        if dry_run {
2474                            removed_wt_paths.insert(wt_canon.clone());
2475                            if !quiet {
2476                                println!(
2477                                    "would remove {display_path} ({removal_reason}, {})",
2478                                    format_size(size)
2479                                );
2480                                if let Some(ref branch_name) = wt.branch {
2481                                    if !branch_checked_out_elsewhere(
2482                                        &all_worktrees,
2483                                        &removed_wt_paths,
2484                                        &wt_canon,
2485                                        branch_name,
2486                                    ) && ctx.get_branch_tip(branch_name).is_some()
2487                                    {
2488                                        println!("would delete branch {branch_name} (merged)");
2489                                    }
2490                                }
2491                            }
2492                            freed_bytes += size;
2493                            removed_worktrees += 1;
2494                        } else {
2495                            let rm_out = std::process::Command::new("git")
2496                                .arg("worktree")
2497                                .arg("remove")
2498                                .arg(&wt.path)
2499                                .current_dir(root)
2500                                .output();
2501                            match rm_out {
2502                                Ok(o) if o.status.success() => {
2503                                    needs_worktree_prune = true;
2504                                    removed_wt_paths.insert(wt_canon.clone());
2505                                    freed_bytes += size;
2506                                    removed_worktrees += 1;
2507                                    if !quiet {
2508                                        println!(
2509                                            "removed {display_path} ({removal_reason}, {})",
2510                                            format_size(size)
2511                                        );
2512                                    }
2513                                    if let Some(ref branch_name) = wt.branch {
2514                                        if !branch_checked_out_elsewhere(
2515                                            &all_worktrees,
2516                                            &removed_wt_paths,
2517                                            &wt_canon,
2518                                            branch_name,
2519                                        ) && ctx.get_branch_tip(branch_name).is_some()
2520                                        {
2521                                            let del_out = std::process::Command::new("git")
2522                                                .args(["branch", "-D", branch_name])
2523                                                .current_dir(root)
2524                                                .output();
2525                                            match del_out {
2526                                                Ok(o) if o.status.success() => {
2527                                                    ctx.remove_branch(branch_name);
2528                                                    if !quiet {
2529                                                        println!(
2530                                                            "deleted branch {branch_name} (merged)"
2531                                                        );
2532                                                    }
2533                                                }
2534                                                Ok(o) => {
2535                                                    eprintln!(
2536                                                        "error: could not delete branch {branch_name}: {}",
2537                                                        String::from_utf8_lossy(&o.stderr).trim()
2538                                                    );
2539                                                    had_errors = true;
2540                                                }
2541                                                Err(e) => {
2542                                                    eprintln!(
2543                                                        "error: could not delete branch {branch_name}: {e}"
2544                                                    );
2545                                                    had_errors = true;
2546                                                }
2547                                            }
2548                                        }
2549                                    }
2550                                }
2551                                Ok(o) => {
2552                                    let stderr =
2553                                        String::from_utf8_lossy(&o.stderr).trim().to_string();
2554                                    let stdout =
2555                                        String::from_utf8_lossy(&o.stdout).trim().to_string();
2556                                    let msg = if !stderr.is_empty() {
2557                                        stderr
2558                                    } else if !stdout.is_empty() {
2559                                        stdout
2560                                    } else {
2561                                        format!("exit status {}", o.status)
2562                                    };
2563                                    eprintln!("error: could not remove {display_path}: {msg}");
2564                                    had_errors = true;
2565                                }
2566                                Err(e) => {
2567                                    eprintln!("error: could not remove {display_path}: {e}");
2568                                    had_errors = true;
2569                                }
2570                            }
2571                        }
2572                    }
2573                }
2574            }
2575        }
2576    }
2577
2578    if needs_worktree_prune {
2579        let _ = std::process::Command::new("git")
2580            .args(["worktree", "prune"])
2581            .current_dir(root)
2582            .output();
2583    }
2584
2585    if !quiet && !is_linked {
2586        report_other_worktrees_with_ctx(root, &mut ctx, &all_worktrees);
2587    }
2588
2589    if !is_linked
2590        && run_clean_surfaces_at(
2591            root,
2592            older_than_days,
2593            dry_run,
2594            quiet,
2595            std::time::SystemTime::now(),
2596        )
2597    {
2598        had_errors = true;
2599    }
2600
2601    CleanRepoStats {
2602        removed_worktrees,
2603        freed_bytes,
2604        had_errors,
2605    }
2606}
2607
2608fn unix_secs_from_system_time(now: std::time::SystemTime) -> Result<u64, String> {
2609    now.duration_since(std::time::UNIX_EPOCH)
2610        .map(|d| d.as_secs())
2611        .map_err(|e| format!("system clock is before UNIX_EPOCH: {e}"))
2612}
2613
2614fn run_clean_surfaces_at(
2615    root: &Path,
2616    older_than_days: u64,
2617    dry_run: bool,
2618    quiet: bool,
2619    now: std::time::SystemTime,
2620) -> bool {
2621    match unix_secs_from_system_time(now)
2622        .and_then(|now_secs| clean_surfaces(root, older_than_days, dry_run, now_secs))
2623    {
2624        Ok(lines) => {
2625            if !quiet {
2626                for line in lines {
2627                    println!("{line}");
2628                }
2629            }
2630            false
2631        }
2632        Err(err) => {
2633            eprintln!("blyte: {err}");
2634            true
2635        }
2636    }
2637}
2638
2639const LEGACY_SURFACE_PROBE_TIMEOUT: std::time::Duration = std::time::Duration::from_millis(300);
2640
2641#[derive(serde::Deserialize)]
2642struct LegacySurfaceFile {
2643    port: u16,
2644    session_id: String,
2645}
2646
2647fn is_legacy_surface_running(port: u16, expected_session_id: &str) -> bool {
2648    if port == 0 {
2649        return false;
2650    }
2651    let agent = ureq::AgentBuilder::new()
2652        .timeout_connect(LEGACY_SURFACE_PROBE_TIMEOUT)
2653        .timeout_read(LEGACY_SURFACE_PROBE_TIMEOUT)
2654        .timeout_write(LEGACY_SURFACE_PROBE_TIMEOUT)
2655        .timeout(LEGACY_SURFACE_PROBE_TIMEOUT)
2656        .redirects(0)
2657        .build();
2658    let url = format!("http://127.0.0.1:{port}/api/health");
2659    let resp = match agent.get(&url).call() {
2660        Ok(r) => r,
2661        Err(_) => return false,
2662    };
2663    if resp.status() != 200 {
2664        return false;
2665    }
2666    let val: serde_json::Value = match resp.into_json() {
2667        Ok(v) => v,
2668        Err(_) => return false,
2669    };
2670    val.get("session_id").and_then(|v| v.as_str()) == Some(expected_session_id)
2671}
2672
2673fn path_present(path: &Path) -> Result<bool, String> {
2674    match std::fs::symlink_metadata(path) {
2675        Ok(_) => Ok(true),
2676        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
2677        Err(e) => Err(format!("failed to inspect {}: {e}", path.display())),
2678    }
2679}
2680
2681fn remove_file_if_present(
2682    path: &Path,
2683    label: &str,
2684    dry_run: bool,
2685    lines: &mut Vec<String>,
2686) -> Result<(), String> {
2687    if !path_present(path)? {
2688        return Ok(());
2689    }
2690    let verb = if dry_run { "would remove" } else { "removed" };
2691    if !dry_run {
2692        std::fs::remove_file(path)
2693            .map_err(|e| format!("failed to remove {}: {e}", path.display()))?;
2694    }
2695    lines.push(format!("{verb} {label}"));
2696    Ok(())
2697}
2698
2699fn remove_dir_if_present(
2700    path: &Path,
2701    label: &str,
2702    dry_run: bool,
2703    lines: &mut Vec<String>,
2704) -> Result<(), String> {
2705    if !path_present(path)? {
2706        return Ok(());
2707    }
2708    let verb = if dry_run { "would remove" } else { "removed" };
2709    if !dry_run {
2710        std::fs::remove_dir_all(path)
2711            .map_err(|e| format!("failed to remove {}: {e}", path.display()))?;
2712    }
2713    lines.push(format!("{verb} {label}"));
2714    Ok(())
2715}
2716
2717fn newest_file_mtime_in(
2718    dir: &Path,
2719    newest: &mut Option<std::time::SystemTime>,
2720) -> Result<(), String> {
2721    let entries = std::fs::read_dir(dir)
2722        .map_err(|e| format!("failed to read directory {}: {e}", dir.display()))?;
2723    for entry in entries {
2724        let entry =
2725            entry.map_err(|e| format!("failed to read directory {}: {e}", dir.display()))?;
2726        let path = entry.path();
2727        let meta = std::fs::symlink_metadata(&path)
2728            .map_err(|e| format!("failed to inspect {}: {e}", path.display()))?;
2729        if meta.is_dir() {
2730            newest_file_mtime_in(&path, newest)?;
2731        } else {
2732            let mtime = meta
2733                .modified()
2734                .map_err(|e| format!("failed to read modified time of {}: {e}", path.display()))?;
2735            if newest.is_none_or(|cur| mtime > cur) {
2736                *newest = Some(mtime);
2737            }
2738        }
2739    }
2740    Ok(())
2741}
2742
2743fn newest_file_mtime(dir: &Path) -> Result<std::time::SystemTime, String> {
2744    let mut newest = None;
2745    newest_file_mtime_in(dir, &mut newest)?;
2746    newest.ok_or_else(|| format!("surface directory {} contains no files", dir.display()))
2747}
2748
2749/// Returns one line per thing removed (or, with dry_run, that would be removed).
2750pub fn clean_surfaces(
2751    main_checkout: &Path,
2752    older_than_days: u64,
2753    dry_run: bool,
2754    now_secs: u64,
2755) -> Result<Vec<String>, String> {
2756    let mut lines = Vec::new();
2757    let wt_dir = main_checkout.join(".wt");
2758    let old_surface_path = wt_dir.join("surface.json");
2759    let old_sessions_dir = wt_dir.join("sessions");
2760
2761    match std::fs::read_to_string(&old_surface_path) {
2762        Ok(raw) => {
2763            let info: LegacySurfaceFile = serde_json::from_str(&raw)
2764                .map_err(|e| format!("failed to parse {}: {e}", old_surface_path.display()))?;
2765            if !is_legacy_surface_running(info.port, &info.session_id) {
2766                let token_path = blyte_agent::sandbox::surface_token_path(main_checkout)?;
2767                let token_label = token_path.display().to_string();
2768                remove_file_if_present(&old_surface_path, ".wt/surface.json", dry_run, &mut lines)?;
2769                remove_dir_if_present(&old_sessions_dir, ".wt/sessions/", dry_run, &mut lines)?;
2770                remove_file_if_present(&token_path, &token_label, dry_run, &mut lines)?;
2771            }
2772        }
2773        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
2774            remove_dir_if_present(&old_sessions_dir, ".wt/sessions/", dry_run, &mut lines)?;
2775        }
2776        Err(e) => {
2777            return Err(format!(
2778                "failed to read {}: {e}",
2779                old_surface_path.display()
2780            ));
2781        }
2782    }
2783
2784    let records = crate::surface_dir::list_records(main_checkout)?;
2785    let now = std::time::UNIX_EPOCH + std::time::Duration::from_secs(now_secs);
2786    let max_age = std::time::Duration::from_secs(older_than_days.saturating_mul(86_400));
2787
2788    for record in records {
2789        if crate::surface_dir::is_running(&record) {
2790            continue;
2791        }
2792        let dir = crate::surface_dir::surface_dir(main_checkout, &record.id);
2793        let newest = newest_file_mtime(&dir)?;
2794        let is_older = match now.duration_since(newest) {
2795            Ok(age) => age > max_age,
2796            Err(_) => false,
2797        };
2798        if !is_older {
2799            continue;
2800        }
2801        let token_path = blyte_agent::sandbox::surface_token_path_for_id(&record.id)?;
2802        let dir_label = format!(".wt/surfaces/{}", record.id);
2803        let token_label = token_path.display().to_string();
2804        remove_dir_if_present(&dir, &dir_label, dry_run, &mut lines)?;
2805        remove_file_if_present(&token_path, &token_label, dry_run, &mut lines)?;
2806    }
2807
2808    Ok(lines)
2809}
2810
2811#[derive(Debug)]
2812pub struct GitWorktreeInfo {
2813    pub path: PathBuf,
2814    pub head_sha: Option<String>,
2815    pub branch: Option<String>,
2816    pub is_detached: bool,
2817    pub is_bare: bool,
2818}
2819
2820/// Parses git worktrees from `git worktree list --porcelain`.
2821pub fn parse_worktree_list(root: &Path) -> Vec<GitWorktreeInfo> {
2822    let out = std::process::Command::new("git")
2823        .args(["worktree", "list", "--porcelain"])
2824        .current_dir(root)
2825        .output();
2826    let Ok(o) = out else {
2827        return Vec::new();
2828    };
2829    if !o.status.success() {
2830        return Vec::new();
2831    }
2832    let text = String::from_utf8_lossy(&o.stdout);
2833
2834    let mut list = Vec::new();
2835    let mut cur_path: Option<PathBuf> = None;
2836    let mut cur_head: Option<String> = None;
2837    let mut cur_branch: Option<String> = None;
2838    let mut cur_detached = false;
2839    let mut cur_bare = false;
2840
2841    let mut finish_entry = |path: &mut Option<PathBuf>,
2842                            head: &mut Option<String>,
2843                            branch: &mut Option<String>,
2844                            detached: &mut bool,
2845                            bare: &mut bool| {
2846        if let Some(p) = path.take() {
2847            list.push(GitWorktreeInfo {
2848                path: p,
2849                head_sha: head.take(),
2850                branch: branch.take(),
2851                is_detached: *detached,
2852                is_bare: *bare,
2853            });
2854            *detached = false;
2855            *bare = false;
2856        }
2857    };
2858
2859    for line in text.lines() {
2860        let line = line.trim();
2861        if line.is_empty() {
2862            finish_entry(
2863                &mut cur_path,
2864                &mut cur_head,
2865                &mut cur_branch,
2866                &mut cur_detached,
2867                &mut cur_bare,
2868            );
2869        } else if let Some(p) = line.strip_prefix("worktree ") {
2870            finish_entry(
2871                &mut cur_path,
2872                &mut cur_head,
2873                &mut cur_branch,
2874                &mut cur_detached,
2875                &mut cur_bare,
2876            );
2877            cur_path = Some(PathBuf::from(p.trim()));
2878        } else if let Some(h) = line.strip_prefix("HEAD ") {
2879            cur_head = Some(h.trim().to_string());
2880        } else if let Some(b) = line.strip_prefix("branch ") {
2881            let b_str = b.trim();
2882            let b_name = b_str.strip_prefix("refs/heads/").unwrap_or(b_str);
2883            cur_branch = Some(b_name.to_string());
2884        } else if line == "detached" {
2885            cur_detached = true;
2886        } else if line == "bare" {
2887            cur_bare = true;
2888        }
2889    }
2890    finish_entry(
2891        &mut cur_path,
2892        &mut cur_head,
2893        &mut cur_branch,
2894        &mut cur_detached,
2895        &mut cur_bare,
2896    );
2897    list
2898}
2899
2900/// Formats a worktree path for display and for git CLI commands:
2901/// relative to `root` if inside `root` or a sibling (same parent directory);
2902/// otherwise absolute.
2903pub fn display_worktree_path(target: &Path, root: &Path) -> String {
2904    let target_canon = target
2905        .canonicalize()
2906        .unwrap_or_else(|_| target.to_path_buf());
2907    let root_canon = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
2908
2909    // Inside the repository root
2910    if let Ok(rel) = target_canon.strip_prefix(&root_canon) {
2911        if !rel.as_os_str().is_empty() {
2912            return rel.to_string_lossy().replace('\\', "/");
2913        }
2914    }
2915
2916    // Sibling (same parent directory, e.g. ../app--side)
2917    if target_canon != root_canon {
2918        if let (Some(root_parent), Some(target_parent)) =
2919            (root_canon.parent(), target_canon.parent())
2920        {
2921            if root_parent == target_parent {
2922                if let Some(file_name) = target_canon.file_name() {
2923                    let rel = Path::new("..").join(file_name);
2924                    return rel.to_string_lossy().replace('\\', "/");
2925                }
2926            }
2927        }
2928    }
2929
2930    // Otherwise show the absolute path
2931    target_canon.to_string_lossy().replace('\\', "/")
2932}
2933
2934/// Returns true if `root` is a linked worktree (its git-dir differs from its git-common-dir).
2935pub fn is_linked_worktree(root: &Path) -> bool {
2936    let out = std::process::Command::new("git")
2937        .args([
2938            "rev-parse",
2939            "--path-format=absolute",
2940            "--git-dir",
2941            "--git-common-dir",
2942        ])
2943        .current_dir(root)
2944        .output();
2945    match out {
2946        Ok(o) if o.status.success() => {
2947            let text = String::from_utf8_lossy(&o.stdout);
2948            let mut lines = text.lines();
2949            let (Some(gd_str), Some(cd_str)) = (lines.next(), lines.next()) else {
2950                return false;
2951            };
2952            let gd_str = gd_str.trim();
2953            let cd_str = cd_str.trim();
2954            if gd_str == cd_str {
2955                return false;
2956            }
2957            let gd_path = PathBuf::from(gd_str);
2958            let cd_path = PathBuf::from(cd_str);
2959            let gd_canon = gd_path.canonicalize().unwrap_or(gd_path);
2960            let cd_canon = cd_path.canonicalize().unwrap_or(cd_path);
2961            gd_canon != cd_canon
2962        }
2963        _ => false,
2964    }
2965}
2966
2967/// Returns true if any path component is `.wt`.
2968pub fn has_wt_component(path: &Path) -> bool {
2969    path.components().any(|c| c.as_os_str() == ".wt")
2970}
2971
2972/// Checks whether a worktree's working tree is clean:
2973/// `git status --porcelain` lists nothing other than `.DS_Store` files, at any depth.
2974pub fn is_worktree_clean(wt_path: &Path) -> bool {
2975    let out = std::process::Command::new("git")
2976        .arg("--no-optional-locks")
2977        .arg("-C")
2978        .arg(wt_path.as_os_str())
2979        .args(["status", "--porcelain", "-u"])
2980        .output();
2981    match out {
2982        Ok(o) if o.status.success() => {
2983            let stdout = String::from_utf8_lossy(&o.stdout);
2984            for line in stdout.lines() {
2985                let trimmed = line.trim();
2986                if trimmed.is_empty() {
2987                    continue;
2988                }
2989                if line.len() < 3 {
2990                    return false;
2991                }
2992                let mut path_part = line[3..].trim();
2993                if let Some((_, new_path)) = path_part.split_once(" -> ") {
2994                    path_part = new_path.trim();
2995                }
2996                let unquoted = path_part
2997                    .strip_prefix('"')
2998                    .and_then(|p| p.strip_suffix('"'))
2999                    .unwrap_or(path_part);
3000                if Path::new(unquoted).file_name() != Some(std::ffi::OsStr::new(".DS_Store")) {
3001                    return false;
3002                }
3003            }
3004            true
3005        }
3006        _ => false,
3007    }
3008}
3009
3010fn report_other_worktrees_with_ctx(
3011    root: &Path,
3012    ctx: &mut CleanContext<'_>,
3013    worktrees: &[GitWorktreeInfo],
3014) {
3015    let root_canon = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
3016    let main_canon = worktrees
3017        .first()
3018        .map(|wt| wt.path.canonicalize().unwrap_or_else(|_| wt.path.clone()));
3019
3020    let mut other_count = 0;
3021    let mut other_bytes = 0;
3022
3023    for (idx, wt) in worktrees.iter().enumerate() {
3024        if idx == 0 {
3025            continue;
3026        }
3027        if wt.is_bare {
3028            continue;
3029        }
3030        if !wt.path.exists() {
3031            continue;
3032        }
3033
3034        let wt_canon = wt.path.canonicalize().unwrap_or_else(|_| wt.path.clone());
3035        if wt_canon == root_canon || wt.path == root {
3036            continue;
3037        }
3038        if Some(&wt_canon) == main_canon.as_ref() {
3039            continue;
3040        }
3041        if has_wt_component(&wt.path)
3042            || has_wt_component(&wt_canon)
3043            || is_session_worktree(root, &wt.path)
3044        {
3045            continue;
3046        }
3047
3048        let is_merged = if let Some(ref branch) = wt.branch {
3049            match ctx.is_branch_merged_checked(branch) {
3050                Ok(merged) => merged,
3051                Err(err) => {
3052                    eprintln!("error: {err}");
3053                    false
3054                }
3055            }
3056        } else if let Some(ref sha) = wt.head_sha {
3057            ctx.is_commit_merged(sha)
3058        } else {
3059            false
3060        };
3061
3062        if !is_merged {
3063            continue;
3064        }
3065
3066        if !is_worktree_clean(&wt.path) {
3067            continue;
3068        }
3069
3070        let size = dir_size(&wt.path);
3071        let path_str = display_worktree_path(&wt.path, root);
3072        let branch_label = wt.branch.as_deref().unwrap_or_else(|| {
3073            wt.head_sha
3074                .as_deref()
3075                .map(|s| &s[..s.len().min(7)])
3076                .unwrap_or("detached")
3077        });
3078
3079        println!(
3080            "merged worktree {path_str} ({branch_label}, {}): git worktree remove {path_str}",
3081            format_size(size)
3082        );
3083
3084        other_count += 1;
3085        other_bytes += size;
3086    }
3087
3088    if other_count > 0 {
3089        println!(
3090            "{other_count} other worktrees are merged and clean ({}); remove them with the commands above",
3091            format_size(other_bytes)
3092        );
3093    }
3094}
3095
3096/// Inspects other worktrees (excluding main checkout, linked-worktree roots,
3097/// and blyte's `.wt/<id>` runs), and reports any that are both merged and clean.
3098/// Never deletes them.
3099pub fn report_other_worktrees(root: &Path) {
3100    if is_linked_worktree(root) {
3101        return;
3102    }
3103    let worktrees = parse_worktree_list(root);
3104    let mut ctx = CleanContext::new(root);
3105    report_other_worktrees_with_ctx(root, &mut ctx, &worktrees);
3106}
3107
3108struct CleanLockGuard(PathBuf);
3109
3110impl Drop for CleanLockGuard {
3111    fn drop(&mut self) {
3112        let _ = std::fs::remove_file(&self.0);
3113    }
3114}
3115
3116enum LockOutcome {
3117    Acquired(CleanLockGuard),
3118    AlreadyRunning,
3119    Error(String),
3120}
3121
3122fn acquire_clean_lock(root: &Path) -> LockOutcome {
3123    use std::io::Write;
3124    let wt_dir = root.join(".wt");
3125    if let Err(e) = std::fs::create_dir_all(&wt_dir) {
3126        return LockOutcome::Error(format!("{}: {e}", wt_dir.display()));
3127    }
3128    let lock_path = wt_dir.join("clean.lock");
3129    let pid_str = format!("{}\n", std::process::id());
3130
3131    match std::fs::OpenOptions::new()
3132        .write(true)
3133        .create_new(true)
3134        .open(&lock_path)
3135    {
3136        Ok(mut f) => {
3137            if let Err(e) = f.write_all(pid_str.as_bytes()) {
3138                let _ = std::fs::remove_file(&lock_path);
3139                return LockOutcome::Error(format!("{}: {e}", lock_path.display()));
3140            }
3141            LockOutcome::Acquired(CleanLockGuard(lock_path))
3142        }
3143        Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
3144            let contents = match std::fs::read_to_string(&lock_path) {
3145                Ok(c) => c,
3146                Err(read_err) => {
3147                    return LockOutcome::Error(format!("{}: {read_err}", lock_path.display()));
3148                }
3149            };
3150            let old_pid: i64 = match contents.trim().parse() {
3151                Ok(p) => p,
3152                Err(parse_err) => {
3153                    return LockOutcome::Error(format!(
3154                        "{}: invalid pid: {parse_err}",
3155                        lock_path.display()
3156                    ));
3157                }
3158            };
3159            if is_pid_alive(old_pid) {
3160                return LockOutcome::AlreadyRunning;
3161            }
3162            eprintln!(
3163                "replacing stale {} from dead pid {old_pid}",
3164                lock_path.display()
3165            );
3166            if let Err(rm_err) = std::fs::remove_file(&lock_path) {
3167                return LockOutcome::Error(format!("{}: {rm_err}", lock_path.display()));
3168            }
3169            match std::fs::OpenOptions::new()
3170                .write(true)
3171                .create_new(true)
3172                .open(&lock_path)
3173            {
3174                Ok(mut f) => {
3175                    if let Err(write_err) = f.write_all(pid_str.as_bytes()) {
3176                        let _ = std::fs::remove_file(&lock_path);
3177                        return LockOutcome::Error(format!("{}: {write_err}", lock_path.display()));
3178                    }
3179                    LockOutcome::Acquired(CleanLockGuard(lock_path))
3180                }
3181                Err(open_err) => LockOutcome::Error(format!("{}: {open_err}", lock_path.display())),
3182            }
3183        }
3184        Err(e) => LockOutcome::Error(format!("{}: {e}", lock_path.display())),
3185    }
3186}
3187
3188/// Runs the `blyte clean` command.
3189pub fn run(args: &crate::cli::CleanArgs) -> i32 {
3190    if (args.quiet || args.skip.is_some()) && (args.all || args.dry_run) {
3191        eprintln!("error: --quiet and --skip cannot be combined with --all or --dry-run");
3192        return 2;
3193    }
3194
3195    let repos = if args.all {
3196        let tidy_res = if args.dry_run {
3197            crate::registry::missing_registered()
3198        } else {
3199            crate::registry::prune_missing()
3200        };
3201        match tidy_res {
3202            Ok(removed) if !removed.is_empty() => {
3203                let verb = if args.dry_run {
3204                    "would forget"
3205                } else {
3206                    "forgot"
3207                };
3208                let list = removed
3209                    .iter()
3210                    .map(|p| p.display().to_string())
3211                    .collect::<Vec<_>>()
3212                    .join(", ");
3213                println!(
3214                    "{verb} {} repositories that no longer exist: {list}",
3215                    removed.len()
3216                );
3217            }
3218            Ok(_) => {}
3219            Err(err) => {
3220                let path = crate::registry::state_dir()
3221                    .map(|d| d.join("repos").display().to_string())
3222                    .unwrap_or_default();
3223                eprintln!("error: could not tidy the repository registry {path}: {err}");
3224            }
3225        }
3226        crate::registry::registered()
3227    } else {
3228        match find_repo_root() {
3229            Ok(root) => vec![root],
3230            Err(e) => {
3231                eprintln!("error: {e}");
3232                return 2;
3233            }
3234        }
3235    };
3236
3237    let _lock_guard = if args.quiet {
3238        let Some(root) = repos.first() else {
3239            eprintln!("error: blyte clean --quiet found no repository to clean");
3240            return 1;
3241        };
3242        match acquire_clean_lock(root) {
3243            LockOutcome::Acquired(guard) => Some(guard),
3244            LockOutcome::AlreadyRunning => return 0,
3245            LockOutcome::Error(e) => {
3246                eprintln!("error: {e}");
3247                return 1;
3248            }
3249        }
3250    } else {
3251        None
3252    };
3253
3254    let mut total_freed = 0;
3255    let mut had_errors = false;
3256    for repo in &repos {
3257        let stats = clean_repo(
3258            repo,
3259            args.older_than,
3260            args.dry_run,
3261            args.skip.as_deref(),
3262            args.quiet,
3263        );
3264        total_freed += stats.freed_bytes;
3265        if stats.had_errors {
3266            had_errors = true;
3267        }
3268    }
3269
3270    if !args.quiet {
3271        if args.dry_run {
3272            println!("would free {}", format_size(total_freed));
3273        } else {
3274            println!("freed {}", format_size(total_freed));
3275        }
3276    }
3277
3278    if had_errors {
3279        1
3280    } else {
3281        0
3282    }
3283}
3284
3285fn delete_wip_branch_strict(root: &Path, branch_name: &str) -> Result<(), String> {
3286    let del_out = std::process::Command::new("git")
3287        .args(["branch", "-D", branch_name])
3288        .current_dir(root)
3289        .output()
3290        .map_err(|e| format!("git branch -D {branch_name}: {e}"))?;
3291    if !del_out.status.success() {
3292        return Err(format!(
3293            "git branch -D {branch_name}: {}",
3294            String::from_utf8_lossy(&del_out.stderr).trim()
3295        ));
3296    }
3297    Ok(())
3298}
3299
3300/// Removes a finished run `<id>` when its work is merged (or it made no changes) and its worktree
3301/// has no uncommitted changes.
3302pub fn remove_finished_run(root: &Path, id: &str) -> Result<Option<String>, String> {
3303    let wt_path = root.join(".wt").join(id);
3304    let branch_name = format!("wip/{id}");
3305    let mut ctx = CleanContext::new(root);
3306
3307    if wt_path.exists() {
3308        let reason = match ctx.check_removable(id, u64::MAX) {
3309            Ok(
3310                r @ (RemovalReason::Merged
3311                | RemovalReason::MergedInto(_)
3312                | RemovalReason::MergedThrough(_)
3313                | RemovalReason::NoChanges),
3314            ) => r,
3315            Err(KeptReason::UnreadableVerdict(err) | KeptReason::UnreadableChildState(err)) => {
3316                return Err(err);
3317            }
3318            Ok(
3319                RemovalReason::SessionMerged(_)
3320                | RemovalReason::Verdict(_)
3321                | RemovalReason::OlderThan(_)
3322                | RemovalReason::ResearchReport
3323                | RemovalReason::ResearchReportInWorktree
3324                | RemovalReason::ResearchEndedWithoutReport(_)
3325                | RemovalReason::ResearchStoppedWithoutSummary(_),
3326            )
3327            | Err(_) => return Ok(None),
3328        };
3329        if has_uncommitted_changes(&wt_path) {
3330            return Ok(None);
3331        }
3332
3333        let had_prior_record = crate::removal_record::path(root, id).exists();
3334        crate::removal_record::record_removal(root, id, &reason)?;
3335
3336        let wt_rel = format!(".wt/{id}");
3337        let rm_out = std::process::Command::new("git")
3338            .args(["worktree", "remove", &wt_rel])
3339            .current_dir(root)
3340            .output()
3341            .map_err(|e| {
3342                if !had_prior_record {
3343                    let _ = std::fs::remove_file(crate::removal_record::path(root, id));
3344                }
3345                format!("git worktree remove {wt_rel}: {e}")
3346            })?;
3347        if !rm_out.status.success() {
3348            if !had_prior_record {
3349                let _ = std::fs::remove_file(crate::removal_record::path(root, id));
3350            }
3351            return Err(format!(
3352                "git worktree remove {wt_rel}: {}",
3353                String::from_utf8_lossy(&rm_out.stderr).trim()
3354            ));
3355        }
3356
3357        if ctx.get_branch_tip(&branch_name).is_some() {
3358            delete_wip_branch_strict(root, &branch_name)?;
3359        }
3360
3361        return Ok(Some(reason.to_string()));
3362    }
3363
3364    if ctx.get_branch_tip(&branch_name).is_some() {
3365        let Some(reason) = ctx.check_run_merged(id)? else {
3366            return Ok(None);
3367        };
3368        let had_prior_record = crate::removal_record::path(root, id).exists();
3369        crate::removal_record::record_removal(root, id, &reason)?;
3370        if let Err(err) = delete_wip_branch_strict(root, &branch_name) {
3371            if !had_prior_record {
3372                let _ = std::fs::remove_file(crate::removal_record::path(root, id));
3373            }
3374            return Err(err);
3375        }
3376        return Ok(Some(reason.to_string()));
3377    }
3378
3379    Ok(None)
3380}
3381
3382/// Starts `blyte clean --quiet [--skip <ID>]` in the background without waiting for it.
3383pub fn spawn_background_clean(root: &Path, skip_id: Option<&str>) {
3384    let res: Result<(), std::io::Error> = (|| {
3385        let wt_dir = root.join(".wt");
3386        std::fs::create_dir_all(&wt_dir)?;
3387        let log_file = std::fs::OpenOptions::new()
3388            .create(true)
3389            .append(true)
3390            .open(wt_dir.join("clean.log"))?;
3391        let stderr_file = log_file.try_clone()?;
3392        let exe = std::env::current_exe()?;
3393        let mut cmd = std::process::Command::new(exe);
3394        cmd.arg("clean").arg("--quiet");
3395        if let Some(id) = skip_id {
3396            cmd.arg("--skip").arg(id);
3397        }
3398        cmd.current_dir(root)
3399            .env_remove(blyte_agent::shell::MODEL_SHELL_ENV)
3400            .stdin(std::process::Stdio::null())
3401            .stdout(std::process::Stdio::from(log_file))
3402            .stderr(std::process::Stdio::from(stderr_file));
3403        let _child = cmd.spawn()?;
3404        Ok(())
3405    })();
3406    if let Err(e) = res {
3407        eprintln!("warning: could not start the background clean: {e}");
3408    }
3409}
3410
3411/// Removes a run's worktree on review after recording the verdict under the same rules.
3412/// Removes the worktree only when the rules allow it now (e.g. redone, or work already merged);
3413/// otherwise prints nothing extra beyond the verdict line, except for accepted/fixed prints
3414/// `worktree .wt/<id> kept until wip/<id> is merged`.
3415pub fn clean_on_review(root: &Path, id: &str) {
3416    let wt_path = root.join(".wt").join(id);
3417    if !wt_path.exists() {
3418        spawn_background_clean(root, Some(id));
3419        return;
3420    }
3421
3422    let mut ctx = CleanContext::new(root);
3423    let branch_name = format!("wip/{id}");
3424    let branch_exists = ctx.get_branch_tip(&branch_name).is_some();
3425
3426    let verdict_path = root.join(".wt").join(format!("{id}.verdict.json"));
3427    let verdict_str = match read_verdict_file(&verdict_path) {
3428        Ok(Some(v)) => v,
3429        Ok(None) => String::new(),
3430        Err(err) => {
3431            eprintln!("error: {err}");
3432            spawn_background_clean(root, Some(id));
3433            return;
3434        }
3435    };
3436
3437    let is_res = ctx.is_research_run(id);
3438    let removal_reason = match ctx.check_removable(id, 14) {
3439        Ok(r) if is_res || !has_uncommitted_changes(&wt_path) => Some(r),
3440        Err(err @ (KeptReason::UnreadableVerdict(_) | KeptReason::UnreadableChildState(_))) => {
3441            eprintln!("error: {err}");
3442            spawn_background_clean(root, Some(id));
3443            return;
3444        }
3445        _ => None,
3446    };
3447
3448    let Some(removal_reason) = removal_reason else {
3449        if verdict_str == "accepted" || verdict_str == "fixed" {
3450            println!("worktree .wt/{id} kept until {branch_name} is merged");
3451        }
3452        spawn_background_clean(root, Some(id));
3453        return;
3454    };
3455
3456    if removal_reason == RemovalReason::ResearchReportInWorktree {
3457        let src = wt_path.join("report.md");
3458        let dst = root.join(".wt").join(format!("{id}.report.md"));
3459        if let Err(err) = std::fs::copy(&src, &dst) {
3460            eprintln!(
3461                "error: could not copy {} to {}: {err}",
3462                src.display(),
3463                dst.display()
3464            );
3465            spawn_background_clean(root, Some(id));
3466            return;
3467        }
3468    }
3469
3470    let had_prior_record = crate::removal_record::path(root, id).exists();
3471    if let Err(err) = crate::removal_record::record_removal(root, id, &removal_reason) {
3472        eprintln!("error: could not write removal record for {id}: {err}");
3473        spawn_background_clean(root, Some(id));
3474        return;
3475    }
3476
3477    let removed_ok = if is_res {
3478        std::fs::remove_dir_all(&wt_path).is_ok()
3479    } else {
3480        let rm_out = std::process::Command::new("git")
3481            .args(["worktree", "remove", wt_path.to_str().unwrap_or("")])
3482            .current_dir(root)
3483            .output();
3484        let _ = std::process::Command::new("git")
3485            .args(["worktree", "prune"])
3486            .current_dir(root)
3487            .output();
3488        rm_out.map(|o| o.status.success()).unwrap_or(false)
3489    };
3490
3491    if !removed_ok {
3492        if !had_prior_record {
3493            let _ = std::fs::remove_file(crate::removal_record::path(root, id));
3494        }
3495        if verdict_str == "accepted" || verdict_str == "fixed" {
3496            println!("worktree .wt/{id} kept until {branch_name} is merged");
3497        }
3498        spawn_background_clean(root, Some(id));
3499        return;
3500    }
3501
3502    if branch_exists {
3503        let is_merged = if matches!(
3504            removal_reason,
3505            RemovalReason::Merged | RemovalReason::MergedInto(_) | RemovalReason::MergedThrough(_)
3506        ) {
3507            true
3508        } else {
3509            match ctx.check_run_merged(id) {
3510                Ok(Some(_)) => true,
3511                Ok(None) => false,
3512                Err(err) => {
3513                    eprintln!("error: {err}");
3514                    false
3515                }
3516            }
3517        };
3518        if is_merged {
3519            let del_out = std::process::Command::new("git")
3520                .args(["branch", "-D", &branch_name])
3521                .current_dir(root)
3522                .output();
3523            if del_out.map(|o| o.status.success()).unwrap_or(false) {
3524                ctx.wip_branch_tips.remove(&branch_name);
3525                println!("removed .wt/{id}; branch {branch_name} deleted");
3526            } else {
3527                println!("removed .wt/{id}; branch {branch_name} kept");
3528            }
3529        } else {
3530            println!("removed .wt/{id}; branch {branch_name} kept");
3531        }
3532    } else {
3533        println!("removed .wt/{id}");
3534    }
3535
3536    spawn_background_clean(root, Some(id));
3537}
3538
3539#[cfg(test)]
3540mod tests {
3541    use super::{run_clean_surfaces_at, unix_secs_from_system_time};
3542    use std::time::{Duration, UNIX_EPOCH};
3543
3544    #[test]
3545    fn unix_secs_from_system_time_rejects_pre_epoch_time() {
3546        let pre_epoch = UNIX_EPOCH
3547            .checked_sub(Duration::from_secs(1))
3548            .expect("pre-epoch SystemTime");
3549        let err = unix_secs_from_system_time(pre_epoch)
3550            .expect_err("expected error for time before UNIX_EPOCH");
3551        assert!(
3552            err.contains("UNIX_EPOCH"),
3553            "error should name UNIX_EPOCH: {err}"
3554        );
3555    }
3556
3557    #[test]
3558    fn unix_secs_from_system_time_accepts_post_epoch_time() {
3559        let ts = UNIX_EPOCH + Duration::from_secs(1_800_000_000);
3560        assert_eq!(unix_secs_from_system_time(ts), Ok(1_800_000_000));
3561    }
3562
3563    #[test]
3564    fn run_clean_surfaces_at_reports_error_on_pre_epoch_time() {
3565        let tmp = tempfile::tempdir().expect("tempdir");
3566        let pre_epoch = UNIX_EPOCH
3567            .checked_sub(Duration::from_secs(1))
3568            .expect("pre-epoch SystemTime");
3569        let had_errors = run_clean_surfaces_at(tmp.path(), 14, false, true, pre_epoch);
3570        assert!(had_errors, "pre-epoch system clock must set had_errors");
3571    }
3572}