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    Verdict(String),
12    NoChanges,
13    ResearchReport,
14    OlderThan(u64),
15}
16
17impl std::fmt::Display for RemovalReason {
18    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
19        match self {
20            Self::Merged => write!(f, "merged"),
21            Self::MergedInto(base) => write!(f, "merged into {base}"),
22            Self::MergedThrough(child) => write!(f, "merged through {child}"),
23            Self::Verdict(v) => {
24                if v.is_empty() {
25                    write!(f, "verdict")
26                } else {
27                    write!(f, "verdict {v}")
28                }
29            }
30            Self::NoChanges => write!(f, "no changes"),
31            Self::ResearchReport => write!(f, "research report"),
32            Self::OlderThan(d) => write!(f, "finished over {d} days ago"),
33        }
34    }
35}
36
37#[derive(Debug, PartialEq, Eq)]
38pub enum KeptReason {
39    UncommittedChanges,
40    Running,
41    NoVerdict,
42    NotMergedYet,
43    NoReport,
44    Custom(String),
45}
46
47impl std::fmt::Display for KeptReason {
48    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
49        match self {
50            Self::UncommittedChanges => write!(f, "uncommitted changes"),
51            Self::Running => write!(f, "running"),
52            Self::NoVerdict => write!(f, "no verdict"),
53            Self::NotMergedYet => write!(f, "not merged yet"),
54            Self::NoReport => write!(f, "no report"),
55            Self::Custom(s) => write!(f, "{s}"),
56        }
57    }
58}
59
60/// Recursively computes directory size in bytes without following symlinks.
61pub fn dir_size(path: &Path) -> u64 {
62    let mut total = 0;
63    let Ok(meta) = std::fs::symlink_metadata(path) else {
64        return 0;
65    };
66    if meta.file_type().is_symlink() {
67        return 0;
68    }
69    if meta.is_file() {
70        return meta.len();
71    }
72    if meta.is_dir() {
73        let Ok(entries) = std::fs::read_dir(path) else {
74            return 0;
75        };
76        for entry in entries.flatten() {
77            let Ok(ft) = entry.file_type() else {
78                continue;
79            };
80            if ft.is_symlink() {
81                continue;
82            } else if ft.is_dir() {
83                total += dir_size(&entry.path());
84            } else if ft.is_file() {
85                if let Ok(m) = entry.metadata() {
86                    total += m.len();
87                }
88            }
89        }
90    }
91    total
92}
93
94/// Formats byte count into human-readable representation: e.g. "812 MB", "12.3 GB".
95pub fn format_size(bytes: u64) -> String {
96    const KB: f64 = 1024.0;
97    const MB: f64 = 1024.0 * 1024.0;
98    const GB: f64 = 1024.0 * 1024.0 * 1024.0;
99    let b = bytes as f64;
100    let (val, unit) = if b >= GB {
101        (b / GB, "GB")
102    } else if b >= MB {
103        (b / MB, "MB")
104    } else if b >= KB {
105        (b / KB, "KB")
106    } else {
107        return format!("{bytes} B");
108    };
109
110    let s = if val >= 100.0 {
111        format!("{val:.0}")
112    } else {
113        let formatted = format!("{val:.1}");
114        formatted
115            .strip_suffix(".0")
116            .unwrap_or(&formatted)
117            .to_string()
118    };
119    format!("{s} {unit}")
120}
121
122/// Checks whether a process with the given PID is alive.
123pub fn is_pid_alive(pid: i64) -> bool {
124    if pid <= 0 {
125        return false;
126    }
127    let ret = unsafe { libc::kill(pid as libc::pid_t, 0) };
128    if ret == 0 {
129        true
130    } else {
131        std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
132    }
133}
134
135/// Finds the root repository (resolving the owning repository if inside a `.wt` run).
136pub fn find_repo_root() -> Result<PathBuf, String> {
137    let out = std::process::Command::new("git")
138        .args(["rev-parse", "--show-toplevel"])
139        .output()
140        .map_err(|e| format!("git not found: {e}"))?;
141    if !out.status.success() {
142        return Err("not a git repository".to_string());
143    }
144    let root = PathBuf::from(String::from_utf8_lossy(&out.stdout).trim());
145    if has_wt_component(&root) {
146        if let Some(wt_parent) = root.parent().and_then(|p| p.parent()) {
147            if root
148                .parent()
149                .and_then(|p| p.file_name())
150                .is_some_and(|n| n == ".wt")
151            {
152                return Ok(wt_parent.to_path_buf());
153            }
154        }
155        if let Some(main) = crate::config::main_checkout(&root) {
156            return Ok(main);
157        }
158    }
159    Ok(root)
160}
161
162/// Checks whether a run is a research run from its start file.
163pub fn is_research(root: &Path, id: &str) -> bool {
164    let start_path = root.join(".wt").join(format!("{id}.start.json"));
165    if let Ok(s) = std::fs::read_to_string(&start_path) {
166        if let Ok(val) = serde_json::from_str::<serde_json::Value>(&s) {
167            return val
168                .get("research")
169                .and_then(|r| r.as_bool())
170                .unwrap_or(false);
171        }
172    }
173    false
174}
175
176/// Checks whether a worktree has uncommitted changes via `git status --porcelain`.
177pub fn has_uncommitted_changes(wt_path: &Path) -> bool {
178    let out = std::process::Command::new("git")
179        .args([
180            "-C",
181            wt_path.to_str().unwrap_or(""),
182            "status",
183            "--porcelain",
184        ])
185        .output();
186    match out {
187        Ok(o) if o.status.success() => {
188            !o.stdout.is_empty() && !String::from_utf8_lossy(&o.stdout).trim().is_empty()
189        }
190        _ => true,
191    }
192}
193
194fn git_tree_sha(root: &Path, ref_name: &str) -> Option<String> {
195    let out = std::process::Command::new("git")
196        .args(["rev-parse", &format!("{ref_name}^{{tree}}")])
197        .current_dir(root)
198        .output()
199        .ok()?;
200    if out.status.success() {
201        Some(String::from_utf8_lossy(&out.stdout).trim().to_string())
202    } else {
203        None
204    }
205}
206
207fn is_cherry_merged_into_target(root: &Path, commit_sha: &str, target: &str) -> bool {
208    let cherry_out = std::process::Command::new("git")
209        .args(["cherry", target, commit_sha])
210        .current_dir(root)
211        .output();
212    if let Ok(o) = cherry_out {
213        if o.status.success() {
214            let s = String::from_utf8_lossy(&o.stdout);
215            let lines: Vec<&str> = s
216                .lines()
217                .map(|l| l.trim())
218                .filter(|l| !l.is_empty())
219                .collect();
220            if !lines.is_empty() && lines.iter().all(|l| l.starts_with('-')) {
221                return true;
222            }
223        }
224    }
225    false
226}
227
228fn is_merge_tree_merged_into_target(
229    root: &Path,
230    commit_sha: &str,
231    target: &str,
232    target_tree: Option<&str>,
233) -> bool {
234    let target_tree_sha = match target_tree {
235        Some(t) => Some(t.to_string()),
236        None => git_tree_sha(root, target),
237    };
238    if let Some(target_tree_sha) = target_tree_sha {
239        let merge_tree_out = std::process::Command::new("git")
240            .args(["merge-tree", "--write-tree", target, commit_sha])
241            .current_dir(root)
242            .output();
243        if let Ok(mt_o) = merge_tree_out {
244            if mt_o.status.success() {
245                let mt_stdout = String::from_utf8_lossy(&mt_o.stdout);
246                if let Some(first_line) = mt_stdout.lines().next() {
247                    if first_line.trim() == target_tree_sha {
248                        return true;
249                    }
250                }
251            }
252        }
253    }
254    false
255}
256
257fn parse_started_at(val: &serde_json::Value) -> Option<u64> {
258    let s = val.get("started_at")?;
259    if let Some(n) = s.as_u64() {
260        Some(n)
261    } else if let Some(n) = s.as_i64() {
262        if n >= 0 {
263            Some(n as u64)
264        } else {
265            None
266        }
267    } else if let Some(f) = s.as_f64() {
268        if f >= 0.0 {
269            Some(f as u64)
270        } else {
271            None
272        }
273    } else if let Some(st) = s.as_str() {
274        st.parse::<u64>().ok()
275    } else {
276        None
277    }
278}
279
280fn check_history_merged(
281    root: &Path,
282    tip_sha: &str,
283    target: &str,
284    started_at: Option<&serde_json::Value>,
285) -> bool {
286    let mb_out = std::process::Command::new("git")
287        .args(["merge-base", target, tip_sha])
288        .current_dir(root)
289        .output();
290    let Ok(mb_o) = mb_out else {
291        return false;
292    };
293    if !mb_o.status.success() {
294        return false;
295    }
296    let merge_base = String::from_utf8_lossy(&mb_o.stdout).trim().to_string();
297    if merge_base.is_empty() {
298        return false;
299    }
300
301    let diff_out = std::process::Command::new("git")
302        .args(["diff", "--name-only", &merge_base, tip_sha])
303        .current_dir(root)
304        .output();
305    let Ok(diff_o) = diff_out else {
306        return false;
307    };
308    if !diff_o.status.success() {
309        return false;
310    }
311    let files: Vec<String> = String::from_utf8_lossy(&diff_o.stdout)
312        .lines()
313        .map(|l| l.trim().to_string())
314        .filter(|l| !l.is_empty())
315        .collect();
316
317    if files.is_empty() {
318        return false;
319    }
320
321    let since_arg = started_at
322        .and_then(|v| {
323            if let Some(n) = v.as_i64() {
324                if n >= 100_000_000 {
325                    Some(format!("--since={n}"))
326                } else {
327                    Some("--since=1970-01-01T00:00:00Z".to_string())
328                }
329            } else if let Some(n) = v.as_u64() {
330                if n >= 100_000_000 {
331                    Some(format!("--since={n}"))
332                } else {
333                    Some("--since=1970-01-01T00:00:00Z".to_string())
334                }
335            } else {
336                v.as_str().map(|s| format!("--since={s}"))
337            }
338        })
339        .unwrap_or_else(|| "--since=1970-01-01T00:00:00Z".to_string());
340
341    let mut cmd = std::process::Command::new("git");
342    cmd.args([
343        "rev-list",
344        "--first-parent",
345        &since_arg,
346        "-n",
347        "20",
348        target,
349        "--",
350    ]);
351    for f in &files {
352        cmd.arg(f);
353    }
354    cmd.current_dir(root);
355    let Ok(rev_o) = cmd.output() else {
356        return false;
357    };
358    if !rev_o.status.success() {
359        return false;
360    }
361
362    let commits: Vec<String> = String::from_utf8_lossy(&rev_o.stdout)
363        .lines()
364        .map(|l| l.trim().to_string())
365        .filter(|l| !l.is_empty())
366        .collect();
367
368    for c in commits {
369        let mt_out = std::process::Command::new("git")
370            .args(["merge-tree", "--write-tree", &c, tip_sha])
371            .current_dir(root)
372            .output();
373        let Ok(mt_o) = mt_out else {
374            continue;
375        };
376        if !mt_o.status.success() {
377            continue;
378        }
379        let mt_stdout = String::from_utf8_lossy(&mt_o.stdout);
380        let Some(first_line) = mt_stdout.lines().next() else {
381            continue;
382        };
383        let mt_tree = first_line.trim();
384
385        if let Some(c_tree) = git_tree_sha(root, &c) {
386            if mt_tree == c_tree {
387                return true;
388            }
389        }
390    }
391
392    false
393}
394
395/// Context for cleaning a repository, caching metadata to avoid redundant git calls and disk reads.
396pub struct CleanContext<'a> {
397    pub root: &'a Path,
398    pub start_files: HashMap<String, serde_json::Value>,
399    pub all_run_ids: Vec<String>,
400    pub wip_branch_tips: HashMap<String, String>,
401    pub default_branch: String,
402    pub origin_default: Option<String>,
403    pub default_tree: Option<String>,
404    pub origin_default_tree: Option<String>,
405    pub wip_contains_cache: HashMap<String, Vec<String>>,
406    pub merged_cache: HashMap<String, Option<RemovalReason>>,
407    pub branch_contains_calls: usize,
408    pub quiet: bool,
409    pub cherry_pick_set: Option<HashSet<String>>,
410    pub rev_list_cache: HashMap<String, Vec<String>>,
411    pub ancestor_cache: HashMap<(String, String), bool>,
412}
413
414impl<'a> CleanContext<'a> {
415    pub fn new(root: &'a Path) -> Self {
416        let mut start_files = HashMap::new();
417        let mut all_run_ids = Vec::new();
418        let wt_dir = root.join(".wt");
419        if let Ok(entries) = std::fs::read_dir(&wt_dir) {
420            for entry in entries.flatten() {
421                let name = entry.file_name().to_string_lossy().to_string();
422                if let Some(id) = name.strip_suffix(".start.json") {
423                    all_run_ids.push(id.to_string());
424                    if let Ok(content) = std::fs::read_to_string(entry.path()) {
425                        if let Ok(val) = serde_json::from_str::<serde_json::Value>(&content) {
426                            start_files.insert(id.to_string(), val);
427                        }
428                    }
429                }
430            }
431        }
432        all_run_ids.sort();
433
434        let mut wip_branch_tips = HashMap::new();
435        let ref_out = std::process::Command::new("git")
436            .args([
437                "for-each-ref",
438                "--format=%(refname:short) %(objectname)",
439                "refs/heads/wip/",
440            ])
441            .current_dir(root)
442            .output();
443        if let Ok(o) = ref_out {
444            if o.status.success() {
445                for line in String::from_utf8_lossy(&o.stdout).lines() {
446                    let mut parts = line.split_whitespace();
447                    if let (Some(refname), Some(sha)) = (parts.next(), parts.next()) {
448                        wip_branch_tips.insert(refname.to_string(), sha.to_string());
449                    }
450                }
451            }
452        }
453
454        let default_branch = find_default_branch(root);
455        let name = default_branch
456            .strip_prefix("origin/")
457            .unwrap_or(&default_branch);
458        let remote = format!("origin/{name}");
459        let origin_default = if remote != default_branch
460            && git_ok(root, &["rev-parse", "--verify", "--quiet", &remote])
461        {
462            Some(remote)
463        } else {
464            None
465        };
466
467        let default_tree = git_tree_sha(root, &default_branch);
468        let origin_default_tree = origin_default
469            .as_deref()
470            .and_then(|r| git_tree_sha(root, r));
471
472        Self {
473            root,
474            start_files,
475            all_run_ids,
476            wip_branch_tips,
477            default_branch,
478            origin_default,
479            default_tree,
480            origin_default_tree,
481            wip_contains_cache: HashMap::new(),
482            merged_cache: HashMap::new(),
483            branch_contains_calls: 0,
484            quiet: false,
485            cherry_pick_set: None,
486            rev_list_cache: HashMap::new(),
487            ancestor_cache: HashMap::new(),
488        }
489    }
490
491    pub fn set_quiet(&mut self, quiet: bool) {
492        self.quiet = quiet;
493    }
494
495    fn compute_cherry_pick_set(&self) -> HashSet<String> {
496        let unremoved_ids = find_blyte_worktrees(self.root);
497        let candidate_ids: &[String] = if unremoved_ids.is_empty() {
498            &self.all_run_ids
499        } else {
500            &unremoved_ids
501        };
502
503        let mut min_started_at: Option<u64> = None;
504        let mut all_valid = true;
505
506        for id in candidate_ids {
507            let start_val = self.start_files.get(id);
508            let parsed = start_val.and_then(parse_started_at);
509            match parsed {
510                Some(ts) => {
511                    min_started_at = Some(min_started_at.map_or(ts, |m| m.min(ts)));
512                }
513                None => {
514                    all_valid = false;
515                }
516            }
517        }
518
519        let since_arg = if let (true, Some(min_ts)) = (all_valid, min_started_at) {
520            if min_ts >= 86_400 + 100_000_000 {
521                format!("--since={}", min_ts - 86_400)
522            } else {
523                "--since=1970-01-01T00:00:00Z".to_string()
524            }
525        } else {
526            "--since=1970-01-01T00:00:00Z".to_string()
527        };
528
529        let mut targets = Vec::new();
530        let mut seen = HashSet::new();
531
532        if git_ok(
533            self.root,
534            &["rev-parse", "--verify", "--quiet", &self.default_branch],
535        ) && seen.insert(self.default_branch.clone())
536        {
537            targets.push(self.default_branch.clone());
538        }
539
540        if let Some(ref origin_def) = self.origin_default {
541            if git_ok(self.root, &["rev-parse", "--verify", "--quiet", origin_def])
542                && seen.insert(origin_def.clone())
543            {
544                targets.push(origin_def.clone());
545            }
546        }
547
548        for id in &self.all_run_ids {
549            if let Some(base_str) = self
550                .start_files
551                .get(id)
552                .and_then(|s| s.get("base"))
553                .and_then(|b| b.as_str())
554            {
555                if let Some((_, base_targets)) = resolve_base_targets(self.root, base_str) {
556                    for bt in base_targets {
557                        if seen.insert(bt.clone()) {
558                            targets.push(bt);
559                        }
560                    }
561                }
562            }
563        }
564
565        if targets.is_empty() {
566            return HashSet::new();
567        }
568
569        let mut cmd = std::process::Command::new("git");
570        cmd.args(["log", "--format=%B", &since_arg]);
571        for t in &targets {
572            cmd.arg(t);
573        }
574        cmd.current_dir(self.root);
575
576        let mut set = HashSet::new();
577        if let Ok(o) = cmd.output() {
578            if o.status.success() {
579                let text = String::from_utf8_lossy(&o.stdout);
580                for line in text.lines() {
581                    let trimmed = line.trim();
582                    if let Some(rest) = trimmed.strip_prefix("(cherry picked from commit ") {
583                        if let Some(sha) = rest.strip_suffix(')') {
584                            let sha = sha.trim();
585                            if is_commit_id(sha) {
586                                set.insert(sha.to_lowercase());
587                            }
588                        }
589                    }
590                }
591            }
592        }
593
594        set
595    }
596
597    pub fn get_cherry_pick_set(&mut self) -> &HashSet<String> {
598        if self.cherry_pick_set.is_none() {
599            let set = self.compute_cherry_pick_set();
600            self.cherry_pick_set = Some(set);
601        }
602        self.cherry_pick_set.as_ref().unwrap()
603    }
604
605    fn is_ancestor_of_target(&mut self, commit_sha: &str, target: &str) -> bool {
606        let key = (commit_sha.to_string(), target.to_string());
607        if let Some(&cached) = self.ancestor_cache.get(&key) {
608            return cached;
609        }
610        let is_anc = std::process::Command::new("git")
611            .args(["merge-base", "--is-ancestor", commit_sha, target])
612            .current_dir(self.root)
613            .output()
614            .map(|c| c.status.success())
615            .unwrap_or(false);
616        self.ancestor_cache.insert(key, is_anc);
617        is_anc
618    }
619
620    fn is_ancestor_of_default(&mut self, commit_sha: &str) -> bool {
621        let def = self.default_branch.clone();
622        if self.is_ancestor_of_target(commit_sha, &def) {
623            return true;
624        }
625        if let Some(origin_def) = self.origin_default.clone() {
626            if self.is_ancestor_of_target(commit_sha, &origin_def) {
627                return true;
628            }
629        }
630        false
631    }
632
633    fn get_run_commits_against_default(&mut self, tip_sha: &str) -> Vec<String> {
634        if let Some(cached) = self.rev_list_cache.get(tip_sha) {
635            return cached.clone();
636        }
637        let out = std::process::Command::new("git")
638            .args(["rev-list", &format!("{}..{}", self.default_branch, tip_sha)])
639            .current_dir(self.root)
640            .output();
641        let commits: Vec<String> = match out {
642            Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout)
643                .lines()
644                .map(|l| l.trim().to_lowercase())
645                .filter(|l| !l.is_empty())
646                .collect(),
647            _ => Vec::new(),
648        };
649        self.rev_list_cache
650            .insert(tip_sha.to_string(), commits.clone());
651        commits
652    }
653
654    fn is_in_cherry_pick_record(&mut self, tip_sha: &str) -> bool {
655        let commits = self.get_run_commits_against_default(tip_sha);
656        if commits.is_empty() {
657            return false;
658        }
659        let cherry_set = self.get_cherry_pick_set();
660        commits.iter().all(|c| cherry_set.contains(c))
661    }
662
663    pub fn get_branch_tip(&self, branch_name: &str) -> Option<String> {
664        if let Some(sha) = self.wip_branch_tips.get(branch_name) {
665            return Some(sha.clone());
666        }
667        get_branch_tip(self.root, branch_name)
668    }
669
670    pub fn is_research_run(&self, id: &str) -> bool {
671        self.start_files
672            .get(id)
673            .and_then(|v| v.get("research"))
674            .and_then(|r| r.as_bool())
675            .unwrap_or_else(|| is_research(self.root, id))
676    }
677
678    pub fn get_wip_branches_containing(&mut self, tip_sha: &str) -> Vec<String> {
679        if let Some(cached) = self.wip_contains_cache.get(tip_sha) {
680            return cached.clone();
681        }
682
683        self.branch_contains_calls += 1;
684
685        let out = std::process::Command::new("git")
686            .args([
687                "branch",
688                "--list",
689                "--format=%(refname:short)",
690                "wip/*",
691                "--contains",
692                tip_sha,
693            ])
694            .current_dir(self.root)
695            .output();
696
697        let mut branches = Vec::new();
698        if let Ok(o) = out {
699            if o.status.success() {
700                for line in String::from_utf8_lossy(&o.stdout).lines() {
701                    let trimmed = line.trim().trim_start_matches(['*', '+', ' ']).trim();
702                    if !trimmed.is_empty() {
703                        branches.push(trimmed.to_string());
704                    }
705                }
706            }
707        }
708        self.wip_contains_cache
709            .insert(tip_sha.to_string(), branches.clone());
710        branches
711    }
712
713    pub fn get_children_of(&mut self, id: &str, tip_sha: &str) -> Vec<String> {
714        let mut children = Vec::new();
715        let mut seen = HashSet::new();
716
717        // 1. Edges from base fields directly
718        for (candidate_id, start_val) in &self.start_files {
719            if candidate_id == id {
720                continue;
721            }
722            if let Some(base_str) = start_val.get("base").and_then(|v| v.as_str()) {
723                let base_str = base_str.trim().trim_end_matches('/');
724                let target1 = format!("wip/{id}");
725                let target2 = format!("refs/heads/wip/{id}");
726                if (base_str == target1 || base_str == target2) && seen.insert(candidate_id.clone())
727                {
728                    children.push(candidate_id.clone());
729                }
730            }
731        }
732
733        // 2. Edges for runs without base:
734        if !tip_sha.is_empty() {
735            let tip_sha_owned = tip_sha.to_string();
736            let containing_branches = self.get_wip_branches_containing(&tip_sha_owned);
737            for b in containing_branches {
738                let clean_b = b.strip_prefix("refs/heads/").unwrap_or(&b);
739                if let Some(candidate_id) = clean_b.strip_prefix("wip/") {
740                    if candidate_id == id {
741                        continue;
742                    }
743                    if !self.start_files.contains_key(candidate_id) {
744                        continue;
745                    }
746                    let has_base = self
747                        .start_files
748                        .get(candidate_id)
749                        .and_then(|val| val.get("base"))
750                        .is_some_and(|b| !b.is_null());
751                    if !has_base && seen.insert(candidate_id.to_string()) {
752                        children.push(candidate_id.to_string());
753                    }
754                }
755            }
756        }
757
758        children.sort();
759        children
760    }
761
762    pub fn is_child_run_merged(&mut self, child: &str, visited: &mut HashSet<String>) -> bool {
763        if self.is_research_run(child) {
764            return false;
765        }
766
767        let branch_name = format!("wip/{child}");
768        let tip = self.get_branch_tip(&branch_name);
769
770        if tip.is_none() {
771            let verdict_path = self.root.join(".wt").join(format!("{child}.verdict.json"));
772            let (has_accepted_verdict, is_redone) = if verdict_path.is_file() {
773                let v = std::fs::read_to_string(&verdict_path)
774                    .ok()
775                    .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
776                    .and_then(|v| {
777                        v.get("verdict")
778                            .and_then(|s| s.as_str())
779                            .map(|s| s.to_string())
780                    })
781                    .unwrap_or_default();
782                (v == "accepted" || v == "fixed", v == "redone")
783            } else {
784                (false, false)
785            };
786
787            if is_redone {
788                return false;
789            }
790
791            let summary_path = self.root.join(".wt").join(format!("{child}.json"));
792            let is_verified = std::fs::read_to_string(&summary_path)
793                .ok()
794                .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
795                .and_then(|v| {
796                    v.get("outcome")
797                        .and_then(|s| s.as_str())
798                        .map(|s| s == "verified")
799                })
800                .unwrap_or(false);
801
802            let wt_gone = !self.root.join(".wt").join(child).is_dir();
803
804            return has_accepted_verdict || (is_verified && wt_gone);
805        }
806
807        self.check_run_merged_internal(child, visited).is_some()
808    }
809
810    pub fn check_run_merged(&mut self, id: &str) -> Option<RemovalReason> {
811        let mut visited = HashSet::new();
812        self.check_run_merged_internal(id, &mut visited)
813    }
814
815    fn check_run_merged_internal(
816        &mut self,
817        id: &str,
818        visited: &mut HashSet<String>,
819    ) -> Option<RemovalReason> {
820        if visited.contains(id) {
821            return None;
822        }
823
824        if let Some(cached) = self.merged_cache.get(id) {
825            return cached.clone();
826        }
827
828        visited.insert(id.to_string());
829
830        let branch_name = format!("wip/{id}");
831        let tip_sha = self.get_branch_tip(&branch_name);
832
833        let result = self.decide_run_merged(id, tip_sha.as_deref(), visited);
834
835        visited.remove(id);
836
837        self.merged_cache.insert(id.to_string(), result.clone());
838        result
839    }
840
841    fn decide_run_merged(
842        &mut self,
843        id: &str,
844        tip_sha: Option<&str>,
845        visited: &mut HashSet<String>,
846    ) -> Option<RemovalReason> {
847        let base_opt = self.start_files.get(id).and_then(|s| {
848            s.get("base")
849                .and_then(|b| b.as_str())
850                .map(|b| b.to_string())
851        });
852        let base_targets = base_opt
853            .as_deref()
854            .and_then(|b| resolve_base_targets(self.root, b));
855        let started_at = self
856            .start_files
857            .get(id)
858            .and_then(|s| s.get("started_at"))
859            .cloned();
860
861        if let Some(tip_sha) = tip_sha {
862            // 1. Ancestor (merge-base --is-ancestor)
863            if self.is_ancestor_of_default(tip_sha) {
864                return Some(RemovalReason::Merged);
865            }
866
867            // 2. The cherry-pick record
868            if self.is_in_cherry_pick_record(tip_sha) {
869                return Some(RemovalReason::Merged);
870            }
871
872            // 3. The base-branch checks
873            if let Some((ref display_name, ref targets)) = base_targets {
874                for target in targets {
875                    if self.is_ancestor_of_target(tip_sha, target) {
876                        return Some(RemovalReason::MergedInto(display_name.clone()));
877                    }
878                    if !self.quiet {
879                        if is_cherry_merged_into_target(self.root, tip_sha, target) {
880                            return Some(RemovalReason::MergedInto(display_name.clone()));
881                        }
882                        if is_merge_tree_merged_into_target(self.root, tip_sha, target, None) {
883                            return Some(RemovalReason::MergedInto(display_name.clone()));
884                        }
885                    }
886                }
887            }
888        }
889
890        // 4. The follow-up rule
891        let children = self.get_children_of(id, tip_sha.unwrap_or(""));
892        for child in children {
893            if visited.contains(&child) {
894                continue;
895            }
896            if self.is_child_run_merged(&child, visited) {
897                return Some(RemovalReason::MergedThrough(child));
898            }
899        }
900
901        // clean_quiet uses only: ancestor, cherry-pick record, follow-ups through those,
902        // and the redone / no_changes / research / age rules.
903        // No merge-tree, no history walk, no other-worktrees report.
904        if self.quiet {
905            return None;
906        }
907
908        if let Some(tip_sha) = tip_sha {
909            // 5. git cherry
910            if is_cherry_merged_into_target(self.root, tip_sha, &self.default_branch) {
911                return Some(RemovalReason::Merged);
912            }
913            if let Some(ref origin_def) = self.origin_default {
914                if is_cherry_merged_into_target(self.root, tip_sha, origin_def) {
915                    return Some(RemovalReason::Merged);
916                }
917            }
918
919            // 6. merge-tree against current tips
920            if is_merge_tree_merged_into_target(
921                self.root,
922                tip_sha,
923                &self.default_branch,
924                self.default_tree.as_deref(),
925            ) {
926                return Some(RemovalReason::Merged);
927            }
928            if let Some(ref origin_def) = self.origin_default {
929                if is_merge_tree_merged_into_target(
930                    self.root,
931                    tip_sha,
932                    origin_def,
933                    self.origin_default_tree.as_deref(),
934                ) {
935                    return Some(RemovalReason::Merged);
936                }
937            }
938
939            // 7. history walk (explicit blyte clean only)
940            if check_history_merged(
941                self.root,
942                tip_sha,
943                &self.default_branch,
944                started_at.as_ref(),
945            ) {
946                return Some(RemovalReason::Merged);
947            }
948            if let Some(ref origin_def) = self.origin_default {
949                if check_history_merged(self.root, tip_sha, origin_def, started_at.as_ref()) {
950                    return Some(RemovalReason::Merged);
951                }
952            }
953            if let Some((ref display_name, ref targets)) = base_targets {
954                for target in targets {
955                    if check_history_merged(self.root, tip_sha, target, started_at.as_ref()) {
956                        return Some(RemovalReason::MergedInto(display_name.clone()));
957                    }
958                }
959            }
960        }
961
962        None
963    }
964
965    pub fn find_merged_followup(&mut self, id: &str) -> Option<String> {
966        let branch_name = format!("wip/{id}");
967        let tip_sha = self.get_branch_tip(&branch_name);
968        let mut visited = HashSet::new();
969        visited.insert(id.to_string());
970        let children = self.get_children_of(id, tip_sha.as_deref().unwrap_or(""));
971        children
972            .into_iter()
973            .find(|child| self.is_child_run_merged(child, &mut visited))
974    }
975
976    pub fn check_removable(
977        &mut self,
978        id: &str,
979        older_than_days: u64,
980    ) -> Result<RemovalReason, KeptReason> {
981        let wt_dir = self.root.join(".wt");
982        let summary_path = wt_dir.join(format!("{id}.json"));
983        let verdict_path = wt_dir.join(format!("{id}.verdict.json"));
984        let report_path = wt_dir.join(format!("{id}.report.md"));
985
986        let start_json = self.start_files.get(id);
987        let summary_exists = summary_path.is_file();
988
989        // Check if run is finished: no live process (pid not running) or summary exists.
990        if !summary_exists {
991            if let Some(start) = start_json {
992                if let Some(pid) = start.get("pid").and_then(|p| p.as_i64()) {
993                    if is_pid_alive(pid) {
994                        return Err(KeptReason::Running);
995                    }
996                }
997            }
998        }
999
1000        let is_res = self.is_research_run(id);
1001
1002        // Rule 2: Discarded (the verdict is redone, or the outcome is no_changes)
1003        let verdict_str = if verdict_path.is_file() {
1004            std::fs::read_to_string(&verdict_path)
1005                .ok()
1006                .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
1007                .and_then(|v| {
1008                    v.get("verdict")
1009                        .and_then(|s| s.as_str())
1010                        .map(|s| s.to_string())
1011                })
1012                .unwrap_or_default()
1013        } else {
1014            String::new()
1015        };
1016
1017        if verdict_str == "redone" {
1018            return Ok(RemovalReason::Verdict("redone".to_string()));
1019        }
1020
1021        if summary_exists {
1022            if let Ok(summary_str) = std::fs::read_to_string(&summary_path) {
1023                if let Ok(val) = serde_json::from_str::<serde_json::Value>(&summary_str) {
1024                    if val.get("outcome").and_then(|o| o.as_str()) == Some("no_changes") {
1025                        return Ok(RemovalReason::NoChanges);
1026                    }
1027                }
1028            }
1029        }
1030
1031        // Rule 3: Research run and its report was copied out (.wt/<id>.report.md exists)
1032        if is_res && report_path.is_file() {
1033            return Ok(RemovalReason::ResearchReport);
1034        }
1035
1036        // Rule 1: Merged (its work is on the default branch or base branch or follow-up)
1037        if !is_res {
1038            if let Some(reason) = self.check_run_merged(id) {
1039                return Ok(reason);
1040            }
1041        }
1042
1043        // Rule 4: Finished more than older_than days ago, by the summary file's mtime
1044        if summary_exists {
1045            if let Ok(meta) = std::fs::metadata(&summary_path) {
1046                if let Ok(mtime) = meta.modified() {
1047                    let age = std::time::SystemTime::now()
1048                        .duration_since(mtime)
1049                        .unwrap_or(std::time::Duration::ZERO);
1050                    if age >= std::time::Duration::from_secs(older_than_days * 86400) {
1051                        return Ok(RemovalReason::OlderThan(older_than_days));
1052                    }
1053                }
1054            }
1055        }
1056
1057        // A verdict of accepted or fixed on its own no longer makes a worktree removable
1058        if !verdict_str.is_empty() {
1059            return Err(KeptReason::NotMergedYet);
1060        }
1061
1062        if is_res {
1063            Err(KeptReason::NoReport)
1064        } else {
1065            Err(KeptReason::NoVerdict)
1066        }
1067    }
1068}
1069
1070/// Evaluates whether a worktree is removable according to the clean rules.
1071pub fn check_removable(
1072    root: &Path,
1073    id: &str,
1074    older_than_days: u64,
1075) -> Result<RemovalReason, KeptReason> {
1076    let mut ctx = CleanContext::new(root);
1077    ctx.check_removable(id, older_than_days)
1078}
1079
1080/// Identifies the default branch (origin/HEAD's target, else main, else master).
1081pub fn find_default_branch(root: &Path) -> String {
1082    let sym_out = std::process::Command::new("git")
1083        .args(["symbolic-ref", "--short", "refs/remotes/origin/HEAD"])
1084        .current_dir(root)
1085        .output();
1086    if let Ok(o) = sym_out {
1087        if o.status.success() {
1088            let target = String::from_utf8_lossy(&o.stdout);
1089            let target = target.trim();
1090            let branch_name = target.strip_prefix("origin/").unwrap_or(target);
1091            let local_check = std::process::Command::new("git")
1092                .args([
1093                    "rev-parse",
1094                    "--verify",
1095                    &format!("refs/heads/{branch_name}"),
1096                ])
1097                .current_dir(root)
1098                .output();
1099            if local_check.map(|c| c.status.success()).unwrap_or(false) {
1100                return branch_name.to_string();
1101            }
1102            let remote_check = std::process::Command::new("git")
1103                .args(["rev-parse", "--verify", target])
1104                .current_dir(root)
1105                .output();
1106            if remote_check.map(|c| c.status.success()).unwrap_or(false) {
1107                return target.to_string();
1108            }
1109            return branch_name.to_string();
1110        }
1111    }
1112
1113    let main_check = std::process::Command::new("git")
1114        .args(["rev-parse", "--verify", "refs/heads/main"])
1115        .current_dir(root)
1116        .output();
1117    if main_check.map(|c| c.status.success()).unwrap_or(false) {
1118        return "main".to_string();
1119    }
1120
1121    let master_check = std::process::Command::new("git")
1122        .args(["rev-parse", "--verify", "refs/heads/master"])
1123        .current_dir(root)
1124        .output();
1125    if master_check.map(|c| c.status.success()).unwrap_or(false) {
1126        return "master".to_string();
1127    }
1128
1129    "main".to_string()
1130}
1131
1132/// Determines if a string is a commit SHA (hex-only, length 7 to 64).
1133fn is_commit_id(s: &str) -> bool {
1134    (s.len() >= 7 && s.len() <= 64) && s.chars().all(|c| c.is_ascii_hexdigit())
1135}
1136
1137/// Resolves candidate git refs for a run's base branch.
1138/// Returns (display_name, targets) if `base` is a branch name that resolves.
1139/// Returns None if `base` is not a branch name (e.g. HEAD, commit id, wip/ branch)
1140/// or if none of the candidate refs resolve in git.
1141pub fn resolve_base_targets(root: &Path, base: &str) -> Option<(String, Vec<String>)> {
1142    let base = base.trim();
1143    if base.is_empty() {
1144        return None;
1145    }
1146
1147    if base == "HEAD"
1148        || base.starts_with("HEAD~")
1149        || base.starts_with("HEAD^")
1150        || base.starts_with("HEAD@")
1151        || base.starts_with("HEAD:")
1152    {
1153        return None;
1154    }
1155
1156    if base == "FETCH_HEAD" || base == "ORIG_HEAD" || base == "MERGE_HEAD" {
1157        return None;
1158    }
1159
1160    if is_commit_id(base) {
1161        return None;
1162    }
1163
1164    let clean = if let Some(stripped) = base.strip_prefix("refs/heads/") {
1165        stripped
1166    } else if let Some(stripped) = base.strip_prefix("refs/remotes/") {
1167        stripped
1168    } else {
1169        base
1170    };
1171
1172    let is_wip = clean == "wip"
1173        || clean.starts_with("wip/")
1174        || clean == "origin/wip"
1175        || clean.starts_with("origin/wip/");
1176    if is_wip {
1177        return None;
1178    }
1179
1180    let (display_name, candidates) = if let Some(without_origin) = clean.strip_prefix("origin/") {
1181        if without_origin.is_empty()
1182            || without_origin == "wip"
1183            || without_origin.starts_with("wip/")
1184            || without_origin == "HEAD"
1185            || without_origin.starts_with("HEAD~")
1186            || without_origin.starts_with("HEAD^")
1187            || is_commit_id(without_origin)
1188        {
1189            return None;
1190        }
1191        let cand1 = format!("refs/remotes/{clean}");
1192        let cand2 = format!("refs/heads/{without_origin}");
1193        (without_origin.to_string(), vec![cand1, cand2])
1194    } else {
1195        let cand1 = format!("refs/heads/{clean}");
1196        let cand2 = format!("refs/remotes/origin/{clean}");
1197        (clean.to_string(), vec![cand1, cand2])
1198    };
1199
1200    let mut resolved = Vec::new();
1201    for cand in candidates {
1202        if git_ok(root, &["rev-parse", "--verify", "--quiet", &cand]) {
1203            resolved.push(cand);
1204        }
1205    }
1206
1207    if resolved.is_empty() {
1208        None
1209    } else {
1210        Some((display_name, resolved))
1211    }
1212}
1213
1214/// Reads `base` from `.wt/<id>.start.json` if present.
1215pub fn read_run_base(root: &Path, id: &str) -> Option<String> {
1216    let start_path = root.join(".wt").join(format!("{id}.start.json"));
1217    std::fs::read_to_string(&start_path)
1218        .ok()
1219        .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
1220        .and_then(|v| {
1221            v.get("base")
1222                .and_then(|b| b.as_str())
1223                .map(|s| s.to_string())
1224        })
1225}
1226
1227/// Returns the commit SHA at the tip of `branch_name` if it exists.
1228pub fn get_branch_tip(root: &Path, branch_name: &str) -> Option<String> {
1229    let check = std::process::Command::new("git")
1230        .args([
1231            "rev-parse",
1232            "--verify",
1233            &format!("refs/heads/{branch_name}"),
1234        ])
1235        .current_dir(root)
1236        .output()
1237        .ok()?;
1238    if !check.status.success() {
1239        return None;
1240    }
1241
1242    let tip_out = std::process::Command::new("git")
1243        .args(["rev-parse", &format!("refs/heads/{branch_name}")])
1244        .current_dir(root)
1245        .output()
1246        .ok()?;
1247    if tip_out.status.success() {
1248        Some(String::from_utf8_lossy(&tip_out.stdout).trim().to_string())
1249    } else {
1250        None
1251    }
1252}
1253
1254/// Checks whether a branch's work is on the default branch when any of:
1255/// - `git merge-base --is-ancestor <tip> <default>` succeeds;
1256/// - every commit `git cherry <default> <branch>` lists is marked `-`;
1257/// - merging it would change nothing: `git merge-tree --write-tree <default> <branch>` exits 0
1258///   and the tree id it prints (first line) equals `git rev-parse <default>^{tree}`.
1259pub fn is_branch_merged(root: &Path, branch_name: &str) -> bool {
1260    let mut ctx = CleanContext::new(root);
1261    if let Some(id) = branch_name.strip_prefix("wip/") {
1262        ctx.check_run_merged(id).is_some()
1263    } else {
1264        is_branch_merged_with_targets(root, branch_name, &[])
1265    }
1266}
1267
1268/// Checks whether a branch's work is on the default branch or any of the extra target refs.
1269pub fn is_branch_merged_with_targets(
1270    root: &Path,
1271    branch_name: &str,
1272    extra_targets: &[&str],
1273) -> bool {
1274    let Some(tip_sha) = get_branch_tip(root, branch_name) else {
1275        return false;
1276    };
1277
1278    is_commit_merged_with_targets(root, &tip_sha, extra_targets)
1279}
1280
1281/// Checks whether a branch's work is on the default branch or any of the extra target refs.
1282pub fn is_branch_merged_with_extra_targets(
1283    root: &Path,
1284    branch_name: &str,
1285    extra_targets: &[&str],
1286) -> bool {
1287    is_branch_merged_with_targets(root, branch_name, extra_targets)
1288}
1289
1290/// Checks whether a commit's work is on the default branch when any of:
1291/// - `git merge-base --is-ancestor <commit> <default>` succeeds;
1292/// - every commit `git cherry <default> <commit>` lists is marked `-`;
1293/// - merging it would change nothing: `git merge-tree --write-tree <default> <commit>` exits 0
1294///   and the tree id it prints equals `git rev-parse <default>^{tree}`.
1295pub fn is_commit_merged(root: &Path, commit_sha: &str) -> bool {
1296    is_commit_merged_with_targets(root, commit_sha, &[])
1297}
1298
1299/// Checks whether a commit's work is on the default branch or any of the extra target refs.
1300pub fn is_commit_merged_with_targets(
1301    root: &Path,
1302    commit_sha: &str,
1303    extra_targets: &[&str],
1304) -> bool {
1305    let default_branch = find_default_branch(root);
1306    // The local default branch can be far behind the remote one (1,292 commits in one repository,
1307    // 2026-10-01), so the remote-tracking branch, as of the last fetch, counts too.
1308    let name = default_branch
1309        .strip_prefix("origin/")
1310        .unwrap_or(&default_branch);
1311    let remote = format!("origin/{name}");
1312    let mut targets = vec![default_branch.clone()];
1313    if remote != default_branch && git_ok(root, &["rev-parse", "--verify", "--quiet", &remote]) {
1314        targets.push(remote);
1315    }
1316    for extra in extra_targets {
1317        if git_ok(root, &["rev-parse", "--verify", "--quiet", extra]) {
1318            targets.push(extra.to_string());
1319        }
1320    }
1321    targets
1322        .iter()
1323        .any(|target| merged_into(root, commit_sha, target))
1324}
1325
1326fn git_ok(root: &Path, args: &[&str]) -> bool {
1327    std::process::Command::new("git")
1328        .args(args)
1329        .current_dir(root)
1330        .output()
1331        .map(|o| o.status.success())
1332        .unwrap_or(false)
1333}
1334
1335/// Whether the commit's work is already on `default_branch`.
1336fn merged_into(root: &Path, commit_sha: &str, default_branch: &str) -> bool {
1337    // 1. `git merge-base --is-ancestor <tip> <default>` succeeds
1338    let ancestor_check = std::process::Command::new("git")
1339        .args(["merge-base", "--is-ancestor", commit_sha, default_branch])
1340        .current_dir(root)
1341        .output();
1342    if ancestor_check.map(|c| c.status.success()).unwrap_or(false) {
1343        return true;
1344    }
1345
1346    // 2. every commit `git cherry <default> <commit>` lists is marked `-`
1347    let cherry_out = std::process::Command::new("git")
1348        .args(["cherry", default_branch, commit_sha])
1349        .current_dir(root)
1350        .output();
1351    if let Ok(o) = cherry_out {
1352        if o.status.success() {
1353            let s = String::from_utf8_lossy(&o.stdout);
1354            let lines: Vec<&str> = s
1355                .lines()
1356                .map(|l| l.trim())
1357                .filter(|l| !l.is_empty())
1358                .collect();
1359            if !lines.is_empty() && lines.iter().all(|l| l.starts_with('-')) {
1360                return true;
1361            }
1362        }
1363    }
1364
1365    // 3. merging it would change nothing: `git merge-tree --write-tree <default> <commit>` exits 0
1366    // and the tree id it prints equals `git rev-parse <default>^{tree}`
1367    let default_tree_out = std::process::Command::new("git")
1368        .args(["rev-parse", &format!("{default_branch}^{{tree}}")])
1369        .current_dir(root)
1370        .output();
1371    if let Ok(tree_o) = default_tree_out {
1372        if tree_o.status.success() {
1373            let default_tree = String::from_utf8_lossy(&tree_o.stdout).trim().to_string();
1374            let merge_tree_out = std::process::Command::new("git")
1375                .args(["merge-tree", "--write-tree", default_branch, commit_sha])
1376                .current_dir(root)
1377                .output();
1378            if let Ok(mt_o) = merge_tree_out {
1379                if mt_o.status.success() {
1380                    let mt_stdout = String::from_utf8_lossy(&mt_o.stdout);
1381                    if let Some(first_line) = mt_stdout.lines().next() {
1382                        if first_line.trim() == default_tree {
1383                            return true;
1384                        }
1385                    }
1386                }
1387            }
1388        }
1389    }
1390
1391    false
1392}
1393
1394/// Lists all run IDs that have a corresponding `.wt/<id>.start.json`.
1395pub fn list_all_run_ids(root: &Path) -> Vec<String> {
1396    let wt_dir = root.join(".wt");
1397    let mut ids = Vec::new();
1398    if let Ok(entries) = std::fs::read_dir(&wt_dir) {
1399        for entry in entries.flatten() {
1400            let name = entry.file_name().to_string_lossy().to_string();
1401            if let Some(id) = name.strip_suffix(".start.json") {
1402                ids.push(id.to_string());
1403            }
1404        }
1405    }
1406    ids.sort();
1407    ids
1408}
1409
1410/// Finds a follow-up run that makes `<id>` merged.
1411pub fn find_merged_followup(root: &Path, id: &str) -> Option<String> {
1412    let mut ctx = CleanContext::new(root);
1413    ctx.find_merged_followup(id)
1414}
1415
1416/// Lists all `.wt/<id>` directories that have a corresponding `.wt/<id>.start.json`.
1417pub fn find_blyte_worktrees(root: &Path) -> Vec<String> {
1418    let wt_dir = root.join(".wt");
1419    if !wt_dir.is_dir() {
1420        return Vec::new();
1421    }
1422    let mut ids = Vec::new();
1423    if let Ok(entries) = std::fs::read_dir(&wt_dir) {
1424        for entry in entries.flatten() {
1425            if let Ok(ft) = entry.file_type() {
1426                if ft.is_dir() {
1427                    let name = entry.file_name().to_string_lossy().to_string();
1428                    let start_file = wt_dir.join(format!("{name}.start.json"));
1429                    if start_file.is_file() {
1430                        ids.push(name);
1431                    }
1432                }
1433            }
1434        }
1435    }
1436    ids.sort();
1437    ids
1438}
1439
1440pub struct CleanRepoStats {
1441    pub removed_worktrees: usize,
1442    pub freed_bytes: u64,
1443}
1444
1445/// Cleans one repository.
1446pub fn clean_repo(
1447    root: &Path,
1448    older_than_days: u64,
1449    dry_run: bool,
1450    skip_id: Option<&str>,
1451    quiet: bool,
1452) -> CleanRepoStats {
1453    let mut removed_worktrees = 0;
1454    let mut freed_bytes = 0;
1455
1456    let mut ctx = CleanContext::new(root);
1457    ctx.set_quiet(quiet);
1458    let start_time = std::time::Instant::now();
1459    let ids = find_blyte_worktrees(root);
1460    for id in ids {
1461        if quiet && start_time.elapsed() >= std::time::Duration::from_secs(1) {
1462            break;
1463        }
1464        if skip_id == Some(&id) {
1465            continue;
1466        }
1467
1468        let wt_path = root.join(".wt").join(&id);
1469        match ctx.check_removable(&id, older_than_days) {
1470            Err(kept_reason) => {
1471                if !quiet {
1472                    println!("kept .wt/{id} ({kept_reason})");
1473                }
1474            }
1475            Ok(removal_reason) => {
1476                let is_res = ctx.is_research_run(&id);
1477                if !is_res && has_uncommitted_changes(&wt_path) {
1478                    if !quiet {
1479                        println!("kept .wt/{id} (uncommitted changes)");
1480                    }
1481                    continue;
1482                }
1483
1484                let size = dir_size(&wt_path);
1485                let branch_name = format!("wip/{id}");
1486                let branch_exists = ctx.get_branch_tip(&branch_name).is_some();
1487                let is_merged = branch_exists
1488                    && (matches!(
1489                        removal_reason,
1490                        RemovalReason::Merged
1491                            | RemovalReason::MergedInto(_)
1492                            | RemovalReason::MergedThrough(_)
1493                    ) || ctx.check_run_merged(&id).is_some());
1494
1495                if dry_run {
1496                    if !quiet {
1497                        println!(
1498                            "would remove .wt/{id} ({removal_reason}, {})",
1499                            format_size(size)
1500                        );
1501                        if is_merged {
1502                            println!("would delete branch {branch_name} (merged)");
1503                        }
1504                    }
1505                    freed_bytes += size;
1506                    removed_worktrees += 1;
1507                } else {
1508                    let removed_ok = if is_res {
1509                        std::fs::remove_dir_all(&wt_path).is_ok()
1510                    } else {
1511                        let rm_out = std::process::Command::new("git")
1512                            .args(["worktree", "remove", wt_path.to_str().unwrap_or("")])
1513                            .current_dir(root)
1514                            .output();
1515                        let _ = std::process::Command::new("git")
1516                            .args(["worktree", "prune"])
1517                            .current_dir(root)
1518                            .output();
1519                        rm_out.map(|o| o.status.success()).unwrap_or(false)
1520                    };
1521
1522                    if removed_ok {
1523                        freed_bytes += size;
1524                        removed_worktrees += 1;
1525                        if !quiet {
1526                            println!("removed .wt/{id} ({removal_reason}, {})", format_size(size));
1527                        }
1528                        if is_merged {
1529                            let del_out = std::process::Command::new("git")
1530                                .args(["branch", "-D", &branch_name])
1531                                .current_dir(root)
1532                                .output();
1533                            if del_out.map(|o| o.status.success()).unwrap_or(false) {
1534                                ctx.wip_branch_tips.remove(&branch_name);
1535                                if !quiet {
1536                                    println!("deleted branch {branch_name} (merged)");
1537                                }
1538                            }
1539                        }
1540                    } else if !quiet {
1541                        println!("kept .wt/{id} (worktree remove failed)");
1542                    }
1543                }
1544            }
1545        }
1546    }
1547
1548    if !quiet {
1549        report_other_worktrees(root);
1550    }
1551
1552    CleanRepoStats {
1553        removed_worktrees,
1554        freed_bytes,
1555    }
1556}
1557
1558#[derive(Debug)]
1559pub struct GitWorktreeInfo {
1560    pub path: PathBuf,
1561    pub head_sha: Option<String>,
1562    pub branch: Option<String>,
1563    pub is_detached: bool,
1564    pub is_bare: bool,
1565}
1566
1567/// Parses git worktrees from `git worktree list --porcelain`.
1568pub fn parse_worktree_list(root: &Path) -> Vec<GitWorktreeInfo> {
1569    let out = std::process::Command::new("git")
1570        .args(["worktree", "list", "--porcelain"])
1571        .current_dir(root)
1572        .output();
1573    let Ok(o) = out else {
1574        return Vec::new();
1575    };
1576    if !o.status.success() {
1577        return Vec::new();
1578    }
1579    let text = String::from_utf8_lossy(&o.stdout);
1580
1581    let mut list = Vec::new();
1582    let mut cur_path: Option<PathBuf> = None;
1583    let mut cur_head: Option<String> = None;
1584    let mut cur_branch: Option<String> = None;
1585    let mut cur_detached = false;
1586    let mut cur_bare = false;
1587
1588    let mut finish_entry = |path: &mut Option<PathBuf>,
1589                            head: &mut Option<String>,
1590                            branch: &mut Option<String>,
1591                            detached: &mut bool,
1592                            bare: &mut bool| {
1593        if let Some(p) = path.take() {
1594            list.push(GitWorktreeInfo {
1595                path: p,
1596                head_sha: head.take(),
1597                branch: branch.take(),
1598                is_detached: *detached,
1599                is_bare: *bare,
1600            });
1601            *detached = false;
1602            *bare = false;
1603        }
1604    };
1605
1606    for line in text.lines() {
1607        let line = line.trim();
1608        if line.is_empty() {
1609            finish_entry(
1610                &mut cur_path,
1611                &mut cur_head,
1612                &mut cur_branch,
1613                &mut cur_detached,
1614                &mut cur_bare,
1615            );
1616        } else if let Some(p) = line.strip_prefix("worktree ") {
1617            finish_entry(
1618                &mut cur_path,
1619                &mut cur_head,
1620                &mut cur_branch,
1621                &mut cur_detached,
1622                &mut cur_bare,
1623            );
1624            cur_path = Some(PathBuf::from(p.trim()));
1625        } else if let Some(h) = line.strip_prefix("HEAD ") {
1626            cur_head = Some(h.trim().to_string());
1627        } else if let Some(b) = line.strip_prefix("branch ") {
1628            let b_str = b.trim();
1629            let b_name = b_str.strip_prefix("refs/heads/").unwrap_or(b_str);
1630            cur_branch = Some(b_name.to_string());
1631        } else if line == "detached" {
1632            cur_detached = true;
1633        } else if line == "bare" {
1634            cur_bare = true;
1635        }
1636    }
1637    finish_entry(
1638        &mut cur_path,
1639        &mut cur_head,
1640        &mut cur_branch,
1641        &mut cur_detached,
1642        &mut cur_bare,
1643    );
1644    list
1645}
1646
1647/// Formats a worktree path for display and for git CLI commands:
1648/// relative to `root` if inside `root` or a sibling (same parent directory);
1649/// otherwise absolute.
1650pub fn display_worktree_path(target: &Path, root: &Path) -> String {
1651    let target_canon = target
1652        .canonicalize()
1653        .unwrap_or_else(|_| target.to_path_buf());
1654    let root_canon = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
1655
1656    // Inside the repository root
1657    if let Ok(rel) = target_canon.strip_prefix(&root_canon) {
1658        if !rel.as_os_str().is_empty() {
1659            return rel.to_string_lossy().replace('\\', "/");
1660        }
1661    }
1662
1663    // Sibling (same parent directory, e.g. ../app--side)
1664    if target_canon != root_canon {
1665        if let (Some(root_parent), Some(target_parent)) =
1666            (root_canon.parent(), target_canon.parent())
1667        {
1668            if root_parent == target_parent {
1669                if let Some(file_name) = target_canon.file_name() {
1670                    let rel = Path::new("..").join(file_name);
1671                    return rel.to_string_lossy().replace('\\', "/");
1672                }
1673            }
1674        }
1675    }
1676
1677    // Otherwise show the absolute path
1678    target_canon.to_string_lossy().replace('\\', "/")
1679}
1680
1681/// Returns true if `root` is a linked worktree (its git-dir differs from its git-common-dir).
1682pub fn is_linked_worktree(root: &Path) -> bool {
1683    let git_dir_out = std::process::Command::new("git")
1684        .args(["rev-parse", "--git-dir"])
1685        .current_dir(root)
1686        .output();
1687    let common_dir_out = std::process::Command::new("git")
1688        .args(["rev-parse", "--git-common-dir"])
1689        .current_dir(root)
1690        .output();
1691    match (git_dir_out, common_dir_out) {
1692        (Ok(gd), Ok(cd)) if gd.status.success() && cd.status.success() => {
1693            let gd_str = String::from_utf8_lossy(&gd.stdout).trim().to_string();
1694            let cd_str = String::from_utf8_lossy(&cd.stdout).trim().to_string();
1695            if gd_str == cd_str {
1696                return false;
1697            }
1698            let gd_path = if Path::new(&gd_str).is_absolute() {
1699                PathBuf::from(&gd_str)
1700            } else {
1701                root.join(&gd_str)
1702            };
1703            let cd_path = if Path::new(&cd_str).is_absolute() {
1704                PathBuf::from(&cd_str)
1705            } else {
1706                root.join(&cd_str)
1707            };
1708            let gd_canon = gd_path.canonicalize().unwrap_or(gd_path);
1709            let cd_canon = cd_path.canonicalize().unwrap_or(cd_path);
1710            gd_canon != cd_canon
1711        }
1712        _ => false,
1713    }
1714}
1715
1716/// Returns true if any path component is `.wt`.
1717pub fn has_wt_component(path: &Path) -> bool {
1718    path.components().any(|c| c.as_os_str() == ".wt")
1719}
1720
1721/// Checks whether a worktree's working tree is clean:
1722/// `git status --porcelain` lists nothing other than `.DS_Store` files, at any depth.
1723pub fn is_worktree_clean(wt_path: &Path) -> bool {
1724    let out = std::process::Command::new("git")
1725        .arg("-C")
1726        .arg(wt_path.as_os_str())
1727        .args(["status", "--porcelain", "-u"])
1728        .output();
1729    match out {
1730        Ok(o) if o.status.success() => {
1731            let stdout = String::from_utf8_lossy(&o.stdout);
1732            for line in stdout.lines() {
1733                let trimmed = line.trim();
1734                if trimmed.is_empty() {
1735                    continue;
1736                }
1737                if line.len() < 3 {
1738                    return false;
1739                }
1740                let mut path_part = line[3..].trim();
1741                if let Some((_, new_path)) = path_part.split_once(" -> ") {
1742                    path_part = new_path.trim();
1743                }
1744                let unquoted = path_part
1745                    .strip_prefix('"')
1746                    .and_then(|p| p.strip_suffix('"'))
1747                    .unwrap_or(path_part);
1748                if Path::new(unquoted).file_name() != Some(std::ffi::OsStr::new(".DS_Store")) {
1749                    return false;
1750                }
1751            }
1752            true
1753        }
1754        _ => false,
1755    }
1756}
1757
1758/// Inspects other worktrees (excluding main checkout, linked-worktree roots,
1759/// and blyte's `.wt/<id>` runs), and reports any that are both merged and clean.
1760/// Never deletes them.
1761pub fn report_other_worktrees(root: &Path) {
1762    // Only report from the main worktree. If the root being cleaned is a linked worktree,
1763    // print nothing about other worktrees for it.
1764    if is_linked_worktree(root) {
1765        return;
1766    }
1767
1768    let worktrees = parse_worktree_list(root);
1769    let root_canon = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
1770    let main_canon = worktrees
1771        .first()
1772        .map(|wt| wt.path.canonicalize().unwrap_or_else(|_| wt.path.clone()));
1773
1774    let mut other_count = 0;
1775    let mut other_bytes = 0;
1776
1777    for (idx, wt) in worktrees.into_iter().enumerate() {
1778        // Never list the main worktree (first entry of git worktree list --porcelain)
1779        if idx == 0 {
1780            continue;
1781        }
1782        if wt.is_bare {
1783            continue;
1784        }
1785        if !wt.path.exists() {
1786            continue;
1787        }
1788
1789        let wt_canon = wt.path.canonicalize().unwrap_or_else(|_| wt.path.clone());
1790        // Skip the main checkout as well as the root itself
1791        if wt_canon == root_canon || wt.path == root {
1792            continue;
1793        }
1794        if Some(&wt_canon) == main_canon.as_ref() {
1795            continue;
1796        }
1797        // Never list blyte runs: exclude any worktree whose path has a .wt directory component anywhere
1798        if has_wt_component(&wt.path) || has_wt_component(&wt_canon) {
1799            continue;
1800        }
1801
1802        // Check if merged
1803        let is_merged = if let Some(ref branch) = wt.branch {
1804            is_branch_merged(root, branch)
1805        } else if let Some(ref sha) = wt.head_sha {
1806            is_commit_merged(root, sha)
1807        } else {
1808            false
1809        };
1810
1811        if !is_merged {
1812            continue;
1813        }
1814
1815        // Check if clean (lists nothing other than .DS_Store files)
1816        if !is_worktree_clean(&wt.path) {
1817            continue;
1818        }
1819
1820        let size = dir_size(&wt.path);
1821        let path_str = display_worktree_path(&wt.path, root);
1822        let branch_label = wt.branch.as_deref().unwrap_or_else(|| {
1823            wt.head_sha
1824                .as_deref()
1825                .map(|s| &s[..s.len().min(7)])
1826                .unwrap_or("detached")
1827        });
1828
1829        println!(
1830            "merged worktree {path_str} ({branch_label}, {}): git worktree remove {path_str}",
1831            format_size(size)
1832        );
1833
1834        other_count += 1;
1835        other_bytes += size;
1836    }
1837
1838    if other_count > 0 {
1839        println!(
1840            "{other_count} other worktrees are merged and clean ({}); remove them with the commands above",
1841            format_size(other_bytes)
1842        );
1843    }
1844}
1845
1846/// Runs the `blyte clean` command.
1847pub fn run(args: &crate::cli::CleanArgs) -> i32 {
1848    let repos = if args.all {
1849        crate::registry::registered()
1850    } else {
1851        match find_repo_root() {
1852            Ok(root) => vec![root],
1853            Err(e) => {
1854                eprintln!("error: {e}");
1855                return 2;
1856            }
1857        }
1858    };
1859
1860    let mut total_freed = 0;
1861    for repo in &repos {
1862        let stats = clean_repo(repo, args.older_than, args.dry_run, None, false);
1863        total_freed += stats.freed_bytes;
1864    }
1865
1866    if args.dry_run {
1867        println!("would free {}", format_size(total_freed));
1868    } else {
1869        println!("freed {}", format_size(total_freed));
1870    }
1871
1872    0
1873}
1874
1875/// Quiet cleanup at dispatch start: no output unless something was removed,
1876/// then one line `blyte: removed N finished worktrees (X GB)` on stderr.
1877/// Never fails the dispatch: logs errors to stderr and goes on.
1878pub fn clean_quiet(root: &Path, skip_id: Option<&str>) {
1879    let stats = clean_repo(root, 14, false, skip_id, true);
1880    if stats.removed_worktrees > 0 {
1881        eprintln!(
1882            "blyte: removed {} finished worktrees ({})",
1883            stats.removed_worktrees,
1884            format_size(stats.freed_bytes)
1885        );
1886    }
1887}
1888
1889/// Removes a run's worktree on review after recording the verdict under the same rules.
1890/// Removes the worktree only when the rules allow it now (e.g. redone, or work already merged);
1891/// otherwise prints nothing extra beyond the verdict line, except for accepted/fixed prints
1892/// `worktree .wt/<id> kept until wip/<id> is merged`.
1893pub fn clean_on_review(root: &Path, id: &str) {
1894    let wt_path = root.join(".wt").join(id);
1895    if !wt_path.exists() {
1896        return;
1897    }
1898
1899    let mut ctx = CleanContext::new(root);
1900    let branch_name = format!("wip/{id}");
1901    let branch_exists = ctx.get_branch_tip(&branch_name).is_some();
1902
1903    let verdict_path = root.join(".wt").join(format!("{id}.verdict.json"));
1904    let verdict_str = std::fs::read_to_string(&verdict_path)
1905        .ok()
1906        .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
1907        .and_then(|v| {
1908            v.get("verdict")
1909                .and_then(|s| s.as_str())
1910                .map(|s| s.to_string())
1911        })
1912        .unwrap_or_default();
1913
1914    let is_res = ctx.is_research_run(id);
1915    let removable = match ctx.check_removable(id, 14) {
1916        Ok(_) => is_res || !has_uncommitted_changes(&wt_path),
1917        Err(_) => false,
1918    };
1919
1920    if !removable {
1921        if verdict_str == "accepted" || verdict_str == "fixed" {
1922            println!("worktree .wt/{id} kept until {branch_name} is merged");
1923        }
1924        return;
1925    }
1926
1927    let removed_ok = if is_res {
1928        std::fs::remove_dir_all(&wt_path).is_ok()
1929    } else {
1930        let rm_out = std::process::Command::new("git")
1931            .args(["worktree", "remove", wt_path.to_str().unwrap_or("")])
1932            .current_dir(root)
1933            .output();
1934        let _ = std::process::Command::new("git")
1935            .args(["worktree", "prune"])
1936            .current_dir(root)
1937            .output();
1938        rm_out.map(|o| o.status.success()).unwrap_or(false)
1939    };
1940
1941    if !removed_ok {
1942        if verdict_str == "accepted" || verdict_str == "fixed" {
1943            println!("worktree .wt/{id} kept until {branch_name} is merged");
1944        }
1945        return;
1946    }
1947
1948    if branch_exists {
1949        let is_merged = ctx.check_run_merged(id).is_some();
1950        if is_merged {
1951            let del_out = std::process::Command::new("git")
1952                .args(["branch", "-D", &branch_name])
1953                .current_dir(root)
1954                .output();
1955            if del_out.map(|o| o.status.success()).unwrap_or(false) {
1956                ctx.wip_branch_tips.remove(&branch_name);
1957                println!("removed .wt/{id}; branch {branch_name} deleted");
1958            } else {
1959                println!("removed .wt/{id}; branch {branch_name} kept");
1960            }
1961        } else {
1962            println!("removed .wt/{id}; branch {branch_name} kept");
1963        }
1964    } else {
1965        println!("removed .wt/{id}");
1966    }
1967}