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    CleanRepoStats {
2590        removed_worktrees,
2591        freed_bytes,
2592        had_errors,
2593    }
2594}
2595
2596#[derive(Debug)]
2597pub struct GitWorktreeInfo {
2598    pub path: PathBuf,
2599    pub head_sha: Option<String>,
2600    pub branch: Option<String>,
2601    pub is_detached: bool,
2602    pub is_bare: bool,
2603}
2604
2605/// Parses git worktrees from `git worktree list --porcelain`.
2606pub fn parse_worktree_list(root: &Path) -> Vec<GitWorktreeInfo> {
2607    let out = std::process::Command::new("git")
2608        .args(["worktree", "list", "--porcelain"])
2609        .current_dir(root)
2610        .output();
2611    let Ok(o) = out else {
2612        return Vec::new();
2613    };
2614    if !o.status.success() {
2615        return Vec::new();
2616    }
2617    let text = String::from_utf8_lossy(&o.stdout);
2618
2619    let mut list = Vec::new();
2620    let mut cur_path: Option<PathBuf> = None;
2621    let mut cur_head: Option<String> = None;
2622    let mut cur_branch: Option<String> = None;
2623    let mut cur_detached = false;
2624    let mut cur_bare = false;
2625
2626    let mut finish_entry = |path: &mut Option<PathBuf>,
2627                            head: &mut Option<String>,
2628                            branch: &mut Option<String>,
2629                            detached: &mut bool,
2630                            bare: &mut bool| {
2631        if let Some(p) = path.take() {
2632            list.push(GitWorktreeInfo {
2633                path: p,
2634                head_sha: head.take(),
2635                branch: branch.take(),
2636                is_detached: *detached,
2637                is_bare: *bare,
2638            });
2639            *detached = false;
2640            *bare = false;
2641        }
2642    };
2643
2644    for line in text.lines() {
2645        let line = line.trim();
2646        if line.is_empty() {
2647            finish_entry(
2648                &mut cur_path,
2649                &mut cur_head,
2650                &mut cur_branch,
2651                &mut cur_detached,
2652                &mut cur_bare,
2653            );
2654        } else if let Some(p) = line.strip_prefix("worktree ") {
2655            finish_entry(
2656                &mut cur_path,
2657                &mut cur_head,
2658                &mut cur_branch,
2659                &mut cur_detached,
2660                &mut cur_bare,
2661            );
2662            cur_path = Some(PathBuf::from(p.trim()));
2663        } else if let Some(h) = line.strip_prefix("HEAD ") {
2664            cur_head = Some(h.trim().to_string());
2665        } else if let Some(b) = line.strip_prefix("branch ") {
2666            let b_str = b.trim();
2667            let b_name = b_str.strip_prefix("refs/heads/").unwrap_or(b_str);
2668            cur_branch = Some(b_name.to_string());
2669        } else if line == "detached" {
2670            cur_detached = true;
2671        } else if line == "bare" {
2672            cur_bare = true;
2673        }
2674    }
2675    finish_entry(
2676        &mut cur_path,
2677        &mut cur_head,
2678        &mut cur_branch,
2679        &mut cur_detached,
2680        &mut cur_bare,
2681    );
2682    list
2683}
2684
2685/// Formats a worktree path for display and for git CLI commands:
2686/// relative to `root` if inside `root` or a sibling (same parent directory);
2687/// otherwise absolute.
2688pub fn display_worktree_path(target: &Path, root: &Path) -> String {
2689    let target_canon = target
2690        .canonicalize()
2691        .unwrap_or_else(|_| target.to_path_buf());
2692    let root_canon = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
2693
2694    // Inside the repository root
2695    if let Ok(rel) = target_canon.strip_prefix(&root_canon) {
2696        if !rel.as_os_str().is_empty() {
2697            return rel.to_string_lossy().replace('\\', "/");
2698        }
2699    }
2700
2701    // Sibling (same parent directory, e.g. ../app--side)
2702    if target_canon != root_canon {
2703        if let (Some(root_parent), Some(target_parent)) =
2704            (root_canon.parent(), target_canon.parent())
2705        {
2706            if root_parent == target_parent {
2707                if let Some(file_name) = target_canon.file_name() {
2708                    let rel = Path::new("..").join(file_name);
2709                    return rel.to_string_lossy().replace('\\', "/");
2710                }
2711            }
2712        }
2713    }
2714
2715    // Otherwise show the absolute path
2716    target_canon.to_string_lossy().replace('\\', "/")
2717}
2718
2719/// Returns true if `root` is a linked worktree (its git-dir differs from its git-common-dir).
2720pub fn is_linked_worktree(root: &Path) -> bool {
2721    let out = std::process::Command::new("git")
2722        .args([
2723            "rev-parse",
2724            "--path-format=absolute",
2725            "--git-dir",
2726            "--git-common-dir",
2727        ])
2728        .current_dir(root)
2729        .output();
2730    match out {
2731        Ok(o) if o.status.success() => {
2732            let text = String::from_utf8_lossy(&o.stdout);
2733            let mut lines = text.lines();
2734            let (Some(gd_str), Some(cd_str)) = (lines.next(), lines.next()) else {
2735                return false;
2736            };
2737            let gd_str = gd_str.trim();
2738            let cd_str = cd_str.trim();
2739            if gd_str == cd_str {
2740                return false;
2741            }
2742            let gd_path = PathBuf::from(gd_str);
2743            let cd_path = PathBuf::from(cd_str);
2744            let gd_canon = gd_path.canonicalize().unwrap_or(gd_path);
2745            let cd_canon = cd_path.canonicalize().unwrap_or(cd_path);
2746            gd_canon != cd_canon
2747        }
2748        _ => false,
2749    }
2750}
2751
2752/// Returns true if any path component is `.wt`.
2753pub fn has_wt_component(path: &Path) -> bool {
2754    path.components().any(|c| c.as_os_str() == ".wt")
2755}
2756
2757/// Checks whether a worktree's working tree is clean:
2758/// `git status --porcelain` lists nothing other than `.DS_Store` files, at any depth.
2759pub fn is_worktree_clean(wt_path: &Path) -> bool {
2760    let out = std::process::Command::new("git")
2761        .arg("--no-optional-locks")
2762        .arg("-C")
2763        .arg(wt_path.as_os_str())
2764        .args(["status", "--porcelain", "-u"])
2765        .output();
2766    match out {
2767        Ok(o) if o.status.success() => {
2768            let stdout = String::from_utf8_lossy(&o.stdout);
2769            for line in stdout.lines() {
2770                let trimmed = line.trim();
2771                if trimmed.is_empty() {
2772                    continue;
2773                }
2774                if line.len() < 3 {
2775                    return false;
2776                }
2777                let mut path_part = line[3..].trim();
2778                if let Some((_, new_path)) = path_part.split_once(" -> ") {
2779                    path_part = new_path.trim();
2780                }
2781                let unquoted = path_part
2782                    .strip_prefix('"')
2783                    .and_then(|p| p.strip_suffix('"'))
2784                    .unwrap_or(path_part);
2785                if Path::new(unquoted).file_name() != Some(std::ffi::OsStr::new(".DS_Store")) {
2786                    return false;
2787                }
2788            }
2789            true
2790        }
2791        _ => false,
2792    }
2793}
2794
2795fn report_other_worktrees_with_ctx(
2796    root: &Path,
2797    ctx: &mut CleanContext<'_>,
2798    worktrees: &[GitWorktreeInfo],
2799) {
2800    let root_canon = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
2801    let main_canon = worktrees
2802        .first()
2803        .map(|wt| wt.path.canonicalize().unwrap_or_else(|_| wt.path.clone()));
2804
2805    let mut other_count = 0;
2806    let mut other_bytes = 0;
2807
2808    for (idx, wt) in worktrees.iter().enumerate() {
2809        if idx == 0 {
2810            continue;
2811        }
2812        if wt.is_bare {
2813            continue;
2814        }
2815        if !wt.path.exists() {
2816            continue;
2817        }
2818
2819        let wt_canon = wt.path.canonicalize().unwrap_or_else(|_| wt.path.clone());
2820        if wt_canon == root_canon || wt.path == root {
2821            continue;
2822        }
2823        if Some(&wt_canon) == main_canon.as_ref() {
2824            continue;
2825        }
2826        if has_wt_component(&wt.path)
2827            || has_wt_component(&wt_canon)
2828            || is_session_worktree(root, &wt.path)
2829        {
2830            continue;
2831        }
2832
2833        let is_merged = if let Some(ref branch) = wt.branch {
2834            match ctx.is_branch_merged_checked(branch) {
2835                Ok(merged) => merged,
2836                Err(err) => {
2837                    eprintln!("error: {err}");
2838                    false
2839                }
2840            }
2841        } else if let Some(ref sha) = wt.head_sha {
2842            ctx.is_commit_merged(sha)
2843        } else {
2844            false
2845        };
2846
2847        if !is_merged {
2848            continue;
2849        }
2850
2851        if !is_worktree_clean(&wt.path) {
2852            continue;
2853        }
2854
2855        let size = dir_size(&wt.path);
2856        let path_str = display_worktree_path(&wt.path, root);
2857        let branch_label = wt.branch.as_deref().unwrap_or_else(|| {
2858            wt.head_sha
2859                .as_deref()
2860                .map(|s| &s[..s.len().min(7)])
2861                .unwrap_or("detached")
2862        });
2863
2864        println!(
2865            "merged worktree {path_str} ({branch_label}, {}): git worktree remove {path_str}",
2866            format_size(size)
2867        );
2868
2869        other_count += 1;
2870        other_bytes += size;
2871    }
2872
2873    if other_count > 0 {
2874        println!(
2875            "{other_count} other worktrees are merged and clean ({}); remove them with the commands above",
2876            format_size(other_bytes)
2877        );
2878    }
2879}
2880
2881/// Inspects other worktrees (excluding main checkout, linked-worktree roots,
2882/// and blyte's `.wt/<id>` runs), and reports any that are both merged and clean.
2883/// Never deletes them.
2884pub fn report_other_worktrees(root: &Path) {
2885    if is_linked_worktree(root) {
2886        return;
2887    }
2888    let worktrees = parse_worktree_list(root);
2889    let mut ctx = CleanContext::new(root);
2890    report_other_worktrees_with_ctx(root, &mut ctx, &worktrees);
2891}
2892
2893struct CleanLockGuard(PathBuf);
2894
2895impl Drop for CleanLockGuard {
2896    fn drop(&mut self) {
2897        let _ = std::fs::remove_file(&self.0);
2898    }
2899}
2900
2901enum LockOutcome {
2902    Acquired(CleanLockGuard),
2903    AlreadyRunning,
2904    Error(String),
2905}
2906
2907fn acquire_clean_lock(root: &Path) -> LockOutcome {
2908    use std::io::Write;
2909    let wt_dir = root.join(".wt");
2910    if let Err(e) = std::fs::create_dir_all(&wt_dir) {
2911        return LockOutcome::Error(format!("{}: {e}", wt_dir.display()));
2912    }
2913    let lock_path = wt_dir.join("clean.lock");
2914    let pid_str = format!("{}\n", std::process::id());
2915
2916    match std::fs::OpenOptions::new()
2917        .write(true)
2918        .create_new(true)
2919        .open(&lock_path)
2920    {
2921        Ok(mut f) => {
2922            if let Err(e) = f.write_all(pid_str.as_bytes()) {
2923                let _ = std::fs::remove_file(&lock_path);
2924                return LockOutcome::Error(format!("{}: {e}", lock_path.display()));
2925            }
2926            LockOutcome::Acquired(CleanLockGuard(lock_path))
2927        }
2928        Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
2929            let contents = match std::fs::read_to_string(&lock_path) {
2930                Ok(c) => c,
2931                Err(read_err) => {
2932                    return LockOutcome::Error(format!("{}: {read_err}", lock_path.display()));
2933                }
2934            };
2935            let old_pid: i64 = match contents.trim().parse() {
2936                Ok(p) => p,
2937                Err(parse_err) => {
2938                    return LockOutcome::Error(format!(
2939                        "{}: invalid pid: {parse_err}",
2940                        lock_path.display()
2941                    ));
2942                }
2943            };
2944            if is_pid_alive(old_pid) {
2945                return LockOutcome::AlreadyRunning;
2946            }
2947            eprintln!(
2948                "replacing stale {} from dead pid {old_pid}",
2949                lock_path.display()
2950            );
2951            if let Err(rm_err) = std::fs::remove_file(&lock_path) {
2952                return LockOutcome::Error(format!("{}: {rm_err}", lock_path.display()));
2953            }
2954            match std::fs::OpenOptions::new()
2955                .write(true)
2956                .create_new(true)
2957                .open(&lock_path)
2958            {
2959                Ok(mut f) => {
2960                    if let Err(write_err) = f.write_all(pid_str.as_bytes()) {
2961                        let _ = std::fs::remove_file(&lock_path);
2962                        return LockOutcome::Error(format!("{}: {write_err}", lock_path.display()));
2963                    }
2964                    LockOutcome::Acquired(CleanLockGuard(lock_path))
2965                }
2966                Err(open_err) => LockOutcome::Error(format!("{}: {open_err}", lock_path.display())),
2967            }
2968        }
2969        Err(e) => LockOutcome::Error(format!("{}: {e}", lock_path.display())),
2970    }
2971}
2972
2973/// Runs the `blyte clean` command.
2974pub fn run(args: &crate::cli::CleanArgs) -> i32 {
2975    if (args.quiet || args.skip.is_some()) && (args.all || args.dry_run) {
2976        eprintln!("error: --quiet and --skip cannot be combined with --all or --dry-run");
2977        return 2;
2978    }
2979
2980    let repos = if args.all {
2981        let tidy_res = if args.dry_run {
2982            crate::registry::missing_registered()
2983        } else {
2984            crate::registry::prune_missing()
2985        };
2986        match tidy_res {
2987            Ok(removed) if !removed.is_empty() => {
2988                let verb = if args.dry_run {
2989                    "would forget"
2990                } else {
2991                    "forgot"
2992                };
2993                let list = removed
2994                    .iter()
2995                    .map(|p| p.display().to_string())
2996                    .collect::<Vec<_>>()
2997                    .join(", ");
2998                println!(
2999                    "{verb} {} repositories that no longer exist: {list}",
3000                    removed.len()
3001                );
3002            }
3003            Ok(_) => {}
3004            Err(err) => {
3005                let path = crate::registry::state_dir()
3006                    .map(|d| d.join("repos").display().to_string())
3007                    .unwrap_or_default();
3008                eprintln!("error: could not tidy the repository registry {path}: {err}");
3009            }
3010        }
3011        crate::registry::registered()
3012    } else {
3013        match find_repo_root() {
3014            Ok(root) => vec![root],
3015            Err(e) => {
3016                eprintln!("error: {e}");
3017                return 2;
3018            }
3019        }
3020    };
3021
3022    let _lock_guard = if args.quiet {
3023        let Some(root) = repos.first() else {
3024            eprintln!("error: blyte clean --quiet found no repository to clean");
3025            return 1;
3026        };
3027        match acquire_clean_lock(root) {
3028            LockOutcome::Acquired(guard) => Some(guard),
3029            LockOutcome::AlreadyRunning => return 0,
3030            LockOutcome::Error(e) => {
3031                eprintln!("error: {e}");
3032                return 1;
3033            }
3034        }
3035    } else {
3036        None
3037    };
3038
3039    let mut total_freed = 0;
3040    let mut had_errors = false;
3041    for repo in &repos {
3042        let stats = clean_repo(
3043            repo,
3044            args.older_than,
3045            args.dry_run,
3046            args.skip.as_deref(),
3047            args.quiet,
3048        );
3049        total_freed += stats.freed_bytes;
3050        if stats.had_errors {
3051            had_errors = true;
3052        }
3053    }
3054
3055    if !args.quiet {
3056        if args.dry_run {
3057            println!("would free {}", format_size(total_freed));
3058        } else {
3059            println!("freed {}", format_size(total_freed));
3060        }
3061    }
3062
3063    if had_errors {
3064        1
3065    } else {
3066        0
3067    }
3068}
3069
3070fn delete_wip_branch_strict(root: &Path, branch_name: &str) -> Result<(), String> {
3071    let del_out = std::process::Command::new("git")
3072        .args(["branch", "-D", branch_name])
3073        .current_dir(root)
3074        .output()
3075        .map_err(|e| format!("git branch -D {branch_name}: {e}"))?;
3076    if !del_out.status.success() {
3077        return Err(format!(
3078            "git branch -D {branch_name}: {}",
3079            String::from_utf8_lossy(&del_out.stderr).trim()
3080        ));
3081    }
3082    Ok(())
3083}
3084
3085/// Removes a finished run `<id>` when its work is merged (or it made no changes) and its worktree
3086/// has no uncommitted changes.
3087pub fn remove_finished_run(root: &Path, id: &str) -> Result<Option<String>, String> {
3088    let wt_path = root.join(".wt").join(id);
3089    let branch_name = format!("wip/{id}");
3090    let mut ctx = CleanContext::new(root);
3091
3092    if wt_path.exists() {
3093        let reason = match ctx.check_removable(id, u64::MAX) {
3094            Ok(
3095                r @ (RemovalReason::Merged
3096                | RemovalReason::MergedInto(_)
3097                | RemovalReason::MergedThrough(_)
3098                | RemovalReason::NoChanges),
3099            ) => r,
3100            Err(KeptReason::UnreadableVerdict(err) | KeptReason::UnreadableChildState(err)) => {
3101                return Err(err);
3102            }
3103            Ok(
3104                RemovalReason::SessionMerged(_)
3105                | RemovalReason::Verdict(_)
3106                | RemovalReason::OlderThan(_)
3107                | RemovalReason::ResearchReport
3108                | RemovalReason::ResearchReportInWorktree
3109                | RemovalReason::ResearchEndedWithoutReport(_)
3110                | RemovalReason::ResearchStoppedWithoutSummary(_),
3111            )
3112            | Err(_) => return Ok(None),
3113        };
3114        if has_uncommitted_changes(&wt_path) {
3115            return Ok(None);
3116        }
3117
3118        let had_prior_record = crate::removal_record::path(root, id).exists();
3119        crate::removal_record::record_removal(root, id, &reason)?;
3120
3121        let wt_rel = format!(".wt/{id}");
3122        let rm_out = std::process::Command::new("git")
3123            .args(["worktree", "remove", &wt_rel])
3124            .current_dir(root)
3125            .output()
3126            .map_err(|e| {
3127                if !had_prior_record {
3128                    let _ = std::fs::remove_file(crate::removal_record::path(root, id));
3129                }
3130                format!("git worktree remove {wt_rel}: {e}")
3131            })?;
3132        if !rm_out.status.success() {
3133            if !had_prior_record {
3134                let _ = std::fs::remove_file(crate::removal_record::path(root, id));
3135            }
3136            return Err(format!(
3137                "git worktree remove {wt_rel}: {}",
3138                String::from_utf8_lossy(&rm_out.stderr).trim()
3139            ));
3140        }
3141
3142        if ctx.get_branch_tip(&branch_name).is_some() {
3143            delete_wip_branch_strict(root, &branch_name)?;
3144        }
3145
3146        return Ok(Some(reason.to_string()));
3147    }
3148
3149    if ctx.get_branch_tip(&branch_name).is_some() {
3150        let Some(reason) = ctx.check_run_merged(id)? else {
3151            return Ok(None);
3152        };
3153        let had_prior_record = crate::removal_record::path(root, id).exists();
3154        crate::removal_record::record_removal(root, id, &reason)?;
3155        if let Err(err) = delete_wip_branch_strict(root, &branch_name) {
3156            if !had_prior_record {
3157                let _ = std::fs::remove_file(crate::removal_record::path(root, id));
3158            }
3159            return Err(err);
3160        }
3161        return Ok(Some(reason.to_string()));
3162    }
3163
3164    Ok(None)
3165}
3166
3167/// Starts `blyte clean --quiet [--skip <ID>]` in the background without waiting for it.
3168pub fn spawn_background_clean(root: &Path, skip_id: Option<&str>) {
3169    let res: Result<(), std::io::Error> = (|| {
3170        let wt_dir = root.join(".wt");
3171        std::fs::create_dir_all(&wt_dir)?;
3172        let log_file = std::fs::OpenOptions::new()
3173            .create(true)
3174            .append(true)
3175            .open(wt_dir.join("clean.log"))?;
3176        let stderr_file = log_file.try_clone()?;
3177        let exe = std::env::current_exe()?;
3178        let mut cmd = std::process::Command::new(exe);
3179        cmd.arg("clean").arg("--quiet");
3180        if let Some(id) = skip_id {
3181            cmd.arg("--skip").arg(id);
3182        }
3183        cmd.current_dir(root)
3184            .env_remove(blyte_agent::shell::MODEL_SHELL_ENV)
3185            .stdin(std::process::Stdio::null())
3186            .stdout(std::process::Stdio::from(log_file))
3187            .stderr(std::process::Stdio::from(stderr_file));
3188        let _child = cmd.spawn()?;
3189        Ok(())
3190    })();
3191    if let Err(e) = res {
3192        eprintln!("warning: could not start the background clean: {e}");
3193    }
3194}
3195
3196/// Removes a run's worktree on review after recording the verdict under the same rules.
3197/// Removes the worktree only when the rules allow it now (e.g. redone, or work already merged);
3198/// otherwise prints nothing extra beyond the verdict line, except for accepted/fixed prints
3199/// `worktree .wt/<id> kept until wip/<id> is merged`.
3200pub fn clean_on_review(root: &Path, id: &str) {
3201    let wt_path = root.join(".wt").join(id);
3202    if !wt_path.exists() {
3203        spawn_background_clean(root, Some(id));
3204        return;
3205    }
3206
3207    let mut ctx = CleanContext::new(root);
3208    let branch_name = format!("wip/{id}");
3209    let branch_exists = ctx.get_branch_tip(&branch_name).is_some();
3210
3211    let verdict_path = root.join(".wt").join(format!("{id}.verdict.json"));
3212    let verdict_str = match read_verdict_file(&verdict_path) {
3213        Ok(Some(v)) => v,
3214        Ok(None) => String::new(),
3215        Err(err) => {
3216            eprintln!("error: {err}");
3217            spawn_background_clean(root, Some(id));
3218            return;
3219        }
3220    };
3221
3222    let is_res = ctx.is_research_run(id);
3223    let removal_reason = match ctx.check_removable(id, 14) {
3224        Ok(r) if is_res || !has_uncommitted_changes(&wt_path) => Some(r),
3225        Err(err @ (KeptReason::UnreadableVerdict(_) | KeptReason::UnreadableChildState(_))) => {
3226            eprintln!("error: {err}");
3227            spawn_background_clean(root, Some(id));
3228            return;
3229        }
3230        _ => None,
3231    };
3232
3233    let Some(removal_reason) = removal_reason else {
3234        if verdict_str == "accepted" || verdict_str == "fixed" {
3235            println!("worktree .wt/{id} kept until {branch_name} is merged");
3236        }
3237        spawn_background_clean(root, Some(id));
3238        return;
3239    };
3240
3241    if removal_reason == RemovalReason::ResearchReportInWorktree {
3242        let src = wt_path.join("report.md");
3243        let dst = root.join(".wt").join(format!("{id}.report.md"));
3244        if let Err(err) = std::fs::copy(&src, &dst) {
3245            eprintln!(
3246                "error: could not copy {} to {}: {err}",
3247                src.display(),
3248                dst.display()
3249            );
3250            spawn_background_clean(root, Some(id));
3251            return;
3252        }
3253    }
3254
3255    let had_prior_record = crate::removal_record::path(root, id).exists();
3256    if let Err(err) = crate::removal_record::record_removal(root, id, &removal_reason) {
3257        eprintln!("error: could not write removal record for {id}: {err}");
3258        spawn_background_clean(root, Some(id));
3259        return;
3260    }
3261
3262    let removed_ok = if is_res {
3263        std::fs::remove_dir_all(&wt_path).is_ok()
3264    } else {
3265        let rm_out = std::process::Command::new("git")
3266            .args(["worktree", "remove", wt_path.to_str().unwrap_or("")])
3267            .current_dir(root)
3268            .output();
3269        let _ = std::process::Command::new("git")
3270            .args(["worktree", "prune"])
3271            .current_dir(root)
3272            .output();
3273        rm_out.map(|o| o.status.success()).unwrap_or(false)
3274    };
3275
3276    if !removed_ok {
3277        if !had_prior_record {
3278            let _ = std::fs::remove_file(crate::removal_record::path(root, id));
3279        }
3280        if verdict_str == "accepted" || verdict_str == "fixed" {
3281            println!("worktree .wt/{id} kept until {branch_name} is merged");
3282        }
3283        spawn_background_clean(root, Some(id));
3284        return;
3285    }
3286
3287    if branch_exists {
3288        let is_merged = if matches!(
3289            removal_reason,
3290            RemovalReason::Merged | RemovalReason::MergedInto(_) | RemovalReason::MergedThrough(_)
3291        ) {
3292            true
3293        } else {
3294            match ctx.check_run_merged(id) {
3295                Ok(Some(_)) => true,
3296                Ok(None) => false,
3297                Err(err) => {
3298                    eprintln!("error: {err}");
3299                    false
3300                }
3301            }
3302        };
3303        if is_merged {
3304            let del_out = std::process::Command::new("git")
3305                .args(["branch", "-D", &branch_name])
3306                .current_dir(root)
3307                .output();
3308            if del_out.map(|o| o.status.success()).unwrap_or(false) {
3309                ctx.wip_branch_tips.remove(&branch_name);
3310                println!("removed .wt/{id}; branch {branch_name} deleted");
3311            } else {
3312                println!("removed .wt/{id}; branch {branch_name} kept");
3313            }
3314        } else {
3315            println!("removed .wt/{id}; branch {branch_name} kept");
3316        }
3317    } else {
3318        println!("removed .wt/{id}");
3319    }
3320
3321    spawn_background_clean(root, Some(id));
3322}