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, squash-merge subject match,
902        // follow-ups through those, and the redone / no_changes / research / age rules.
903        // No merge-tree, no history walk, no other-worktrees report.
904        if self.quiet {
905            if let Some(tip_sha) = tip_sha {
906                return self.squash_merged_reason(tip_sha, &base_targets);
907            }
908            return None;
909        }
910
911        if let Some(tip_sha) = tip_sha {
912            // 5. git cherry
913            if is_cherry_merged_into_target(self.root, tip_sha, &self.default_branch) {
914                return Some(RemovalReason::Merged);
915            }
916            if let Some(ref origin_def) = self.origin_default {
917                if is_cherry_merged_into_target(self.root, tip_sha, origin_def) {
918                    return Some(RemovalReason::Merged);
919                }
920            }
921
922            // 6. merge-tree against current tips
923            if is_merge_tree_merged_into_target(
924                self.root,
925                tip_sha,
926                &self.default_branch,
927                self.default_tree.as_deref(),
928            ) {
929                return Some(RemovalReason::Merged);
930            }
931            if let Some(ref origin_def) = self.origin_default {
932                if is_merge_tree_merged_into_target(
933                    self.root,
934                    tip_sha,
935                    origin_def,
936                    self.origin_default_tree.as_deref(),
937                ) {
938                    return Some(RemovalReason::Merged);
939                }
940            }
941
942            // 7. history walk (explicit blyte clean only)
943            if check_history_merged(
944                self.root,
945                tip_sha,
946                &self.default_branch,
947                started_at.as_ref(),
948            ) {
949                return Some(RemovalReason::Merged);
950            }
951            if let Some(ref origin_def) = self.origin_default {
952                if check_history_merged(self.root, tip_sha, origin_def, started_at.as_ref()) {
953                    return Some(RemovalReason::Merged);
954                }
955            }
956            if let Some((ref display_name, ref targets)) = base_targets {
957                for target in targets {
958                    if check_history_merged(self.root, tip_sha, target, started_at.as_ref()) {
959                        return Some(RemovalReason::MergedInto(display_name.clone()));
960                    }
961                }
962            }
963
964            // 8. squash-merge subject match
965            if let Some(reason) = self.squash_merged_reason(tip_sha, &base_targets) {
966                return Some(reason);
967            }
968        }
969
970        None
971    }
972
973    fn squash_merged_reason(
974        &self,
975        tip_sha: &str,
976        base_targets: &Option<(String, Vec<String>)>,
977    ) -> Option<RemovalReason> {
978        if is_squash_merged_into_target(self.root, tip_sha, &self.default_branch) {
979            return Some(RemovalReason::Merged);
980        }
981        if let Some(ref origin_def) = self.origin_default {
982            if is_squash_merged_into_target(self.root, tip_sha, origin_def) {
983                return Some(RemovalReason::Merged);
984            }
985        }
986        if let Some((ref display_name, ref targets)) = base_targets {
987            for target in targets {
988                if is_squash_merged_into_target(self.root, tip_sha, target) {
989                    return Some(RemovalReason::MergedInto(display_name.clone()));
990                }
991            }
992        }
993        None
994    }
995
996    pub fn find_merged_followup(&mut self, id: &str) -> Option<String> {
997        let branch_name = format!("wip/{id}");
998        let tip_sha = self.get_branch_tip(&branch_name);
999        let mut visited = HashSet::new();
1000        visited.insert(id.to_string());
1001        let children = self.get_children_of(id, tip_sha.as_deref().unwrap_or(""));
1002        children
1003            .into_iter()
1004            .find(|child| self.is_child_run_merged(child, &mut visited))
1005    }
1006
1007    pub fn check_removable(
1008        &mut self,
1009        id: &str,
1010        older_than_days: u64,
1011    ) -> Result<RemovalReason, KeptReason> {
1012        let wt_dir = self.root.join(".wt");
1013        let summary_path = wt_dir.join(format!("{id}.json"));
1014        let verdict_path = wt_dir.join(format!("{id}.verdict.json"));
1015        let report_path = wt_dir.join(format!("{id}.report.md"));
1016
1017        let start_json = self.start_files.get(id);
1018        let summary_exists = summary_path.is_file();
1019
1020        // Check if run is finished: no live process (pid not running) or a summary from this run exists.
1021        if let Some(start) = start_json {
1022            if let Some(pid) = start.get("pid").and_then(|p| p.as_i64()) {
1023                if is_pid_alive(pid) {
1024                    if !summary_exists {
1025                        return Err(KeptReason::Running);
1026                    }
1027                    let Some(started_at) = parse_started_at(start) else {
1028                        return Err(KeptReason::Running);
1029                    };
1030                    let summary_mtime = std::fs::metadata(&summary_path)
1031                        .ok()
1032                        .and_then(|m| m.modified().ok())
1033                        .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
1034                        .map(|d| d.as_secs());
1035                    if summary_mtime.is_none_or(|mtime| mtime < started_at) {
1036                        return Err(KeptReason::Running);
1037                    }
1038                }
1039            }
1040        }
1041
1042        let is_res = self.is_research_run(id);
1043
1044        // Rule 2: Discarded (the verdict is redone, or the outcome is no_changes)
1045        let verdict_str = if verdict_path.is_file() {
1046            std::fs::read_to_string(&verdict_path)
1047                .ok()
1048                .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
1049                .and_then(|v| {
1050                    v.get("verdict")
1051                        .and_then(|s| s.as_str())
1052                        .map(|s| s.to_string())
1053                })
1054                .unwrap_or_default()
1055        } else {
1056            String::new()
1057        };
1058
1059        if verdict_str == "redone" {
1060            return Ok(RemovalReason::Verdict("redone".to_string()));
1061        }
1062
1063        if summary_exists {
1064            if let Ok(summary_str) = std::fs::read_to_string(&summary_path) {
1065                if let Ok(val) = serde_json::from_str::<serde_json::Value>(&summary_str) {
1066                    if val.get("outcome").and_then(|o| o.as_str()) == Some("no_changes") {
1067                        return Ok(RemovalReason::NoChanges);
1068                    }
1069                }
1070            }
1071        }
1072
1073        // Rule 3: Research run and its report was copied out (.wt/<id>.report.md exists)
1074        if is_res && report_path.is_file() {
1075            return Ok(RemovalReason::ResearchReport);
1076        }
1077
1078        // Rule 1: Merged (its work is on the default branch or base branch or follow-up)
1079        if !is_res {
1080            if let Some(reason) = self.check_run_merged(id) {
1081                return Ok(reason);
1082            }
1083        }
1084
1085        // Rule 4: Finished more than older_than days ago, by the summary file's mtime
1086        if summary_exists {
1087            if let Ok(meta) = std::fs::metadata(&summary_path) {
1088                if let Ok(mtime) = meta.modified() {
1089                    let age = std::time::SystemTime::now()
1090                        .duration_since(mtime)
1091                        .unwrap_or(std::time::Duration::ZERO);
1092                    if age >= std::time::Duration::from_secs(older_than_days * 86400) {
1093                        return Ok(RemovalReason::OlderThan(older_than_days));
1094                    }
1095                }
1096            }
1097        }
1098
1099        // A verdict of accepted or fixed on its own no longer makes a worktree removable
1100        if !verdict_str.is_empty() {
1101            return Err(KeptReason::NotMergedYet);
1102        }
1103
1104        if is_res {
1105            Err(KeptReason::NoReport)
1106        } else {
1107            Err(KeptReason::NoVerdict)
1108        }
1109    }
1110}
1111
1112/// Evaluates whether a worktree is removable according to the clean rules.
1113pub fn check_removable(
1114    root: &Path,
1115    id: &str,
1116    older_than_days: u64,
1117) -> Result<RemovalReason, KeptReason> {
1118    let mut ctx = CleanContext::new(root);
1119    ctx.check_removable(id, older_than_days)
1120}
1121
1122/// Identifies the default branch (origin/HEAD's target, else main, else master).
1123pub fn find_default_branch(root: &Path) -> String {
1124    let sym_out = std::process::Command::new("git")
1125        .args(["symbolic-ref", "--short", "refs/remotes/origin/HEAD"])
1126        .current_dir(root)
1127        .output();
1128    if let Ok(o) = sym_out {
1129        if o.status.success() {
1130            let target = String::from_utf8_lossy(&o.stdout);
1131            let target = target.trim();
1132            let branch_name = target.strip_prefix("origin/").unwrap_or(target);
1133            let local_check = std::process::Command::new("git")
1134                .args([
1135                    "rev-parse",
1136                    "--verify",
1137                    &format!("refs/heads/{branch_name}"),
1138                ])
1139                .current_dir(root)
1140                .output();
1141            if local_check.map(|c| c.status.success()).unwrap_or(false) {
1142                return branch_name.to_string();
1143            }
1144            let remote_check = std::process::Command::new("git")
1145                .args(["rev-parse", "--verify", target])
1146                .current_dir(root)
1147                .output();
1148            if remote_check.map(|c| c.status.success()).unwrap_or(false) {
1149                return target.to_string();
1150            }
1151            return branch_name.to_string();
1152        }
1153    }
1154
1155    let main_check = std::process::Command::new("git")
1156        .args(["rev-parse", "--verify", "refs/heads/main"])
1157        .current_dir(root)
1158        .output();
1159    if main_check.map(|c| c.status.success()).unwrap_or(false) {
1160        return "main".to_string();
1161    }
1162
1163    let master_check = std::process::Command::new("git")
1164        .args(["rev-parse", "--verify", "refs/heads/master"])
1165        .current_dir(root)
1166        .output();
1167    if master_check.map(|c| c.status.success()).unwrap_or(false) {
1168        return "master".to_string();
1169    }
1170
1171    "main".to_string()
1172}
1173
1174/// Determines if a string is a commit SHA (hex-only, length 7 to 64).
1175fn is_commit_id(s: &str) -> bool {
1176    (s.len() >= 7 && s.len() <= 64) && s.chars().all(|c| c.is_ascii_hexdigit())
1177}
1178
1179/// Resolves candidate git refs for a run's base branch.
1180/// Returns (display_name, targets) if `base` is a branch name that resolves.
1181/// Returns None if `base` is not a branch name (e.g. HEAD, commit id, wip/ branch)
1182/// or if none of the candidate refs resolve in git.
1183pub fn resolve_base_targets(root: &Path, base: &str) -> Option<(String, Vec<String>)> {
1184    let base = base.trim();
1185    if base.is_empty() {
1186        return None;
1187    }
1188
1189    if base == "HEAD"
1190        || base.starts_with("HEAD~")
1191        || base.starts_with("HEAD^")
1192        || base.starts_with("HEAD@")
1193        || base.starts_with("HEAD:")
1194    {
1195        return None;
1196    }
1197
1198    if base == "FETCH_HEAD" || base == "ORIG_HEAD" || base == "MERGE_HEAD" {
1199        return None;
1200    }
1201
1202    if is_commit_id(base) {
1203        return None;
1204    }
1205
1206    let clean = if let Some(stripped) = base.strip_prefix("refs/heads/") {
1207        stripped
1208    } else if let Some(stripped) = base.strip_prefix("refs/remotes/") {
1209        stripped
1210    } else {
1211        base
1212    };
1213
1214    let is_wip = clean == "wip"
1215        || clean.starts_with("wip/")
1216        || clean == "origin/wip"
1217        || clean.starts_with("origin/wip/");
1218    if is_wip {
1219        return None;
1220    }
1221
1222    let (display_name, candidates) = if let Some(without_origin) = clean.strip_prefix("origin/") {
1223        if without_origin.is_empty()
1224            || without_origin == "wip"
1225            || without_origin.starts_with("wip/")
1226            || without_origin == "HEAD"
1227            || without_origin.starts_with("HEAD~")
1228            || without_origin.starts_with("HEAD^")
1229            || is_commit_id(without_origin)
1230        {
1231            return None;
1232        }
1233        let cand1 = format!("refs/remotes/{clean}");
1234        let cand2 = format!("refs/heads/{without_origin}");
1235        (without_origin.to_string(), vec![cand1, cand2])
1236    } else {
1237        let cand1 = format!("refs/heads/{clean}");
1238        let cand2 = format!("refs/remotes/origin/{clean}");
1239        (clean.to_string(), vec![cand1, cand2])
1240    };
1241
1242    let mut resolved = Vec::new();
1243    for cand in candidates {
1244        if git_ok(root, &["rev-parse", "--verify", "--quiet", &cand]) {
1245            resolved.push(cand);
1246        }
1247    }
1248
1249    if resolved.is_empty() {
1250        None
1251    } else {
1252        Some((display_name, resolved))
1253    }
1254}
1255
1256/// Reads `base` from `.wt/<id>.start.json` if present.
1257pub fn read_run_base(root: &Path, id: &str) -> Option<String> {
1258    let start_path = root.join(".wt").join(format!("{id}.start.json"));
1259    std::fs::read_to_string(&start_path)
1260        .ok()
1261        .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
1262        .and_then(|v| {
1263            v.get("base")
1264                .and_then(|b| b.as_str())
1265                .map(|s| s.to_string())
1266        })
1267}
1268
1269/// Returns the commit SHA at the tip of `branch_name` if it exists.
1270pub fn get_branch_tip(root: &Path, branch_name: &str) -> Option<String> {
1271    let check = std::process::Command::new("git")
1272        .args([
1273            "rev-parse",
1274            "--verify",
1275            &format!("refs/heads/{branch_name}"),
1276        ])
1277        .current_dir(root)
1278        .output()
1279        .ok()?;
1280    if !check.status.success() {
1281        return None;
1282    }
1283
1284    let tip_out = std::process::Command::new("git")
1285        .args(["rev-parse", &format!("refs/heads/{branch_name}")])
1286        .current_dir(root)
1287        .output()
1288        .ok()?;
1289    if tip_out.status.success() {
1290        Some(String::from_utf8_lossy(&tip_out.stdout).trim().to_string())
1291    } else {
1292        None
1293    }
1294}
1295
1296/// Checks whether a branch's work is on the default branch when any of:
1297/// - `git merge-base --is-ancestor <tip> <default>` succeeds;
1298/// - every commit `git cherry <default> <branch>` lists is marked `-`;
1299/// - merging it would change nothing: `git merge-tree --write-tree <default> <branch>` exits 0
1300///   and the tree id it prints (first line) equals `git rev-parse <default>^{tree}`;
1301/// - 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).
1302pub fn is_branch_merged(root: &Path, branch_name: &str) -> bool {
1303    let mut ctx = CleanContext::new(root);
1304    if let Some(id) = branch_name.strip_prefix("wip/") {
1305        ctx.check_run_merged(id).is_some()
1306    } else {
1307        is_branch_merged_with_targets(root, branch_name, &[])
1308    }
1309}
1310
1311/// Checks whether a branch's work is on the default branch or any of the extra target refs.
1312pub fn is_branch_merged_with_targets(
1313    root: &Path,
1314    branch_name: &str,
1315    extra_targets: &[&str],
1316) -> bool {
1317    let Some(tip_sha) = get_branch_tip(root, branch_name) else {
1318        return false;
1319    };
1320
1321    is_commit_merged_with_targets(root, &tip_sha, extra_targets)
1322}
1323
1324/// Checks whether a branch's work is on the default branch or any of the extra target refs.
1325pub fn is_branch_merged_with_extra_targets(
1326    root: &Path,
1327    branch_name: &str,
1328    extra_targets: &[&str],
1329) -> bool {
1330    is_branch_merged_with_targets(root, branch_name, extra_targets)
1331}
1332
1333/// Checks whether a commit's work is on the default branch when any of:
1334/// - `git merge-base --is-ancestor <commit> <default>` succeeds;
1335/// - every commit `git cherry <default> <commit>` lists is marked `-`;
1336/// - merging it would change nothing: `git merge-tree --write-tree <default> <commit>` exits 0
1337///   and the tree id it prints equals `git rev-parse <default>^{tree}`.
1338pub fn is_commit_merged(root: &Path, commit_sha: &str) -> bool {
1339    is_commit_merged_with_targets(root, commit_sha, &[])
1340}
1341
1342/// Checks whether a commit's work is on the default branch or any of the extra target refs.
1343pub fn is_commit_merged_with_targets(
1344    root: &Path,
1345    commit_sha: &str,
1346    extra_targets: &[&str],
1347) -> bool {
1348    let default_branch = find_default_branch(root);
1349    // The local default branch can be far behind the remote one (1,292 commits in one repository,
1350    // 2026-10-01), so the remote-tracking branch, as of the last fetch, counts too.
1351    let name = default_branch
1352        .strip_prefix("origin/")
1353        .unwrap_or(&default_branch);
1354    let remote = format!("origin/{name}");
1355    let mut targets = vec![default_branch.clone()];
1356    if remote != default_branch && git_ok(root, &["rev-parse", "--verify", "--quiet", &remote]) {
1357        targets.push(remote);
1358    }
1359    for extra in extra_targets {
1360        if git_ok(root, &["rev-parse", "--verify", "--quiet", extra]) {
1361            targets.push(extra.to_string());
1362        }
1363    }
1364    targets
1365        .iter()
1366        .any(|target| merged_into(root, commit_sha, target))
1367}
1368
1369fn git_ok(root: &Path, args: &[&str]) -> bool {
1370    std::process::Command::new("git")
1371        .args(args)
1372        .current_dir(root)
1373        .output()
1374        .map(|o| o.status.success())
1375        .unwrap_or(false)
1376}
1377
1378/// Whether the commit's work is already on `default_branch`.
1379fn merged_into(root: &Path, commit_sha: &str, default_branch: &str) -> bool {
1380    // 1. `git merge-base --is-ancestor <tip> <default>` succeeds
1381    let ancestor_check = std::process::Command::new("git")
1382        .args(["merge-base", "--is-ancestor", commit_sha, default_branch])
1383        .current_dir(root)
1384        .output();
1385    if ancestor_check.map(|c| c.status.success()).unwrap_or(false) {
1386        return true;
1387    }
1388
1389    // 2. every commit `git cherry <default> <commit>` lists is marked `-`
1390    let cherry_out = std::process::Command::new("git")
1391        .args(["cherry", default_branch, commit_sha])
1392        .current_dir(root)
1393        .output();
1394    if let Ok(o) = cherry_out {
1395        if o.status.success() {
1396            let s = String::from_utf8_lossy(&o.stdout);
1397            let lines: Vec<&str> = s
1398                .lines()
1399                .map(|l| l.trim())
1400                .filter(|l| !l.is_empty())
1401                .collect();
1402            if !lines.is_empty() && lines.iter().all(|l| l.starts_with('-')) {
1403                return true;
1404            }
1405        }
1406    }
1407
1408    // 3. merging it would change nothing: `git merge-tree --write-tree <default> <commit>` exits 0
1409    // and the tree id it prints equals `git rev-parse <default>^{tree}`
1410    let default_tree_out = std::process::Command::new("git")
1411        .args(["rev-parse", &format!("{default_branch}^{{tree}}")])
1412        .current_dir(root)
1413        .output();
1414    if let Ok(tree_o) = default_tree_out {
1415        if tree_o.status.success() {
1416            let default_tree = String::from_utf8_lossy(&tree_o.stdout).trim().to_string();
1417            let merge_tree_out = std::process::Command::new("git")
1418                .args(["merge-tree", "--write-tree", default_branch, commit_sha])
1419                .current_dir(root)
1420                .output();
1421            if let Ok(mt_o) = merge_tree_out {
1422                if mt_o.status.success() {
1423                    let mt_stdout = String::from_utf8_lossy(&mt_o.stdout);
1424                    if let Some(first_line) = mt_stdout.lines().next() {
1425                        if first_line.trim() == default_tree {
1426                            return true;
1427                        }
1428                    }
1429                }
1430            }
1431        }
1432    }
1433
1434    // 4. every commit's subject on <commit> appears as a whole line in the messages of <default>'s
1435    // commits since the branch forked
1436    is_squash_merged_into_target(root, commit_sha, default_branch)
1437}
1438
1439fn is_squash_merged_into_target(root: &Path, commit_sha: &str, target: &str) -> bool {
1440    let mb_out = std::process::Command::new("git")
1441        .args(["merge-base", target, commit_sha])
1442        .current_dir(root)
1443        .output();
1444    let Ok(mb_o) = mb_out else {
1445        return false;
1446    };
1447    if !mb_o.status.success() {
1448        return false;
1449    }
1450    let base = String::from_utf8_lossy(&mb_o.stdout).trim().to_string();
1451    if base.is_empty() {
1452        return false;
1453    }
1454
1455    let subj_out = std::process::Command::new("git")
1456        .args([
1457            "log",
1458            "--no-merges",
1459            "--format=%s",
1460            &format!("{target}..{commit_sha}"),
1461        ])
1462        .current_dir(root)
1463        .output();
1464    let Ok(subj_o) = subj_out else {
1465        return false;
1466    };
1467    if !subj_o.status.success() {
1468        return false;
1469    }
1470    let subj_stdout = String::from_utf8_lossy(&subj_o.stdout);
1471    let subjects: Vec<&str> = subj_stdout
1472        .lines()
1473        .map(|l| l.trim())
1474        .filter(|l| !l.is_empty())
1475        .collect();
1476    if subjects.is_empty() {
1477        return false;
1478    }
1479
1480    let hay_out = std::process::Command::new("git")
1481        .args(["log", "--format=%B", &format!("{base}..{target}")])
1482        .current_dir(root)
1483        .output();
1484    let Ok(hay_o) = hay_out else {
1485        return false;
1486    };
1487    if !hay_o.status.success() {
1488        return false;
1489    }
1490    let hay_stdout = String::from_utf8_lossy(&hay_o.stdout);
1491    let mut haystack_lines = HashSet::new();
1492    for line in hay_stdout.lines() {
1493        let trimmed = line.trim();
1494        if trimmed.is_empty() {
1495            continue;
1496        }
1497        haystack_lines.insert(trimmed.to_string());
1498        if let Some(stripped) = trimmed
1499            .strip_prefix("* ")
1500            .or_else(|| trimmed.strip_prefix("- "))
1501        {
1502            let stripped = stripped.trim();
1503            if !stripped.is_empty() {
1504                haystack_lines.insert(stripped.to_string());
1505            }
1506        }
1507    }
1508
1509    subjects.iter().all(|s| haystack_lines.contains(*s))
1510}
1511
1512/// Lists all run IDs that have a corresponding `.wt/<id>.start.json`.
1513pub fn list_all_run_ids(root: &Path) -> Vec<String> {
1514    let wt_dir = root.join(".wt");
1515    let mut ids = Vec::new();
1516    if let Ok(entries) = std::fs::read_dir(&wt_dir) {
1517        for entry in entries.flatten() {
1518            let name = entry.file_name().to_string_lossy().to_string();
1519            if let Some(id) = name.strip_suffix(".start.json") {
1520                ids.push(id.to_string());
1521            }
1522        }
1523    }
1524    ids.sort();
1525    ids
1526}
1527
1528/// Finds a follow-up run that makes `<id>` merged.
1529pub fn find_merged_followup(root: &Path, id: &str) -> Option<String> {
1530    let mut ctx = CleanContext::new(root);
1531    ctx.find_merged_followup(id)
1532}
1533
1534/// Lists all `.wt/<id>` directories that have a corresponding `.wt/<id>.start.json`.
1535pub fn find_blyte_worktrees(root: &Path) -> Vec<String> {
1536    let wt_dir = root.join(".wt");
1537    if !wt_dir.is_dir() {
1538        return Vec::new();
1539    }
1540    let mut ids = Vec::new();
1541    if let Ok(entries) = std::fs::read_dir(&wt_dir) {
1542        for entry in entries.flatten() {
1543            if let Ok(ft) = entry.file_type() {
1544                if ft.is_dir() {
1545                    let name = entry.file_name().to_string_lossy().to_string();
1546                    let start_file = wt_dir.join(format!("{name}.start.json"));
1547                    if start_file.is_file() {
1548                        ids.push(name);
1549                    }
1550                }
1551            }
1552        }
1553    }
1554    ids.sort();
1555    ids
1556}
1557
1558pub struct CleanRepoStats {
1559    pub removed_worktrees: usize,
1560    pub freed_bytes: u64,
1561}
1562
1563/// Cleans one repository.
1564pub fn clean_repo(
1565    root: &Path,
1566    older_than_days: u64,
1567    dry_run: bool,
1568    skip_id: Option<&str>,
1569    quiet: bool,
1570    time_budget: Option<std::time::Duration>,
1571) -> CleanRepoStats {
1572    let mut removed_worktrees = 0;
1573    let mut freed_bytes = 0;
1574
1575    let mut ctx = CleanContext::new(root);
1576    ctx.set_quiet(quiet);
1577    let start_time = std::time::Instant::now();
1578    let ids = find_blyte_worktrees(root);
1579    for id in ids {
1580        if let Some(budget) = time_budget {
1581            if start_time.elapsed() >= budget {
1582                break;
1583            }
1584        }
1585        if skip_id == Some(&id) {
1586            continue;
1587        }
1588
1589        let wt_path = root.join(".wt").join(&id);
1590        match ctx.check_removable(&id, older_than_days) {
1591            Err(kept_reason) => {
1592                if !quiet {
1593                    println!("kept .wt/{id} ({kept_reason})");
1594                }
1595            }
1596            Ok(removal_reason) => {
1597                let is_res = ctx.is_research_run(&id);
1598                if !is_res && has_uncommitted_changes(&wt_path) {
1599                    if !quiet {
1600                        println!("kept .wt/{id} (uncommitted changes)");
1601                    }
1602                    continue;
1603                }
1604
1605                let size = dir_size(&wt_path);
1606                let branch_name = format!("wip/{id}");
1607                let branch_exists = ctx.get_branch_tip(&branch_name).is_some();
1608                let is_merged = branch_exists
1609                    && (matches!(
1610                        removal_reason,
1611                        RemovalReason::Merged
1612                            | RemovalReason::MergedInto(_)
1613                            | RemovalReason::MergedThrough(_)
1614                    ) || ctx.check_run_merged(&id).is_some());
1615
1616                if dry_run {
1617                    if !quiet {
1618                        println!(
1619                            "would remove .wt/{id} ({removal_reason}, {})",
1620                            format_size(size)
1621                        );
1622                        if is_merged {
1623                            println!("would delete branch {branch_name} (merged)");
1624                        }
1625                    }
1626                    freed_bytes += size;
1627                    removed_worktrees += 1;
1628                } else {
1629                    let removed_ok = if is_res {
1630                        std::fs::remove_dir_all(&wt_path).is_ok()
1631                    } else {
1632                        let rm_out = std::process::Command::new("git")
1633                            .args(["worktree", "remove", wt_path.to_str().unwrap_or("")])
1634                            .current_dir(root)
1635                            .output();
1636                        let _ = std::process::Command::new("git")
1637                            .args(["worktree", "prune"])
1638                            .current_dir(root)
1639                            .output();
1640                        rm_out.map(|o| o.status.success()).unwrap_or(false)
1641                    };
1642
1643                    if removed_ok {
1644                        freed_bytes += size;
1645                        removed_worktrees += 1;
1646                        if !quiet {
1647                            println!("removed .wt/{id} ({removal_reason}, {})", format_size(size));
1648                        }
1649                        if is_merged {
1650                            let del_out = std::process::Command::new("git")
1651                                .args(["branch", "-D", &branch_name])
1652                                .current_dir(root)
1653                                .output();
1654                            if del_out.map(|o| o.status.success()).unwrap_or(false) {
1655                                ctx.wip_branch_tips.remove(&branch_name);
1656                                if !quiet {
1657                                    println!("deleted branch {branch_name} (merged)");
1658                                }
1659                            }
1660                        }
1661                    } else if !quiet {
1662                        println!("kept .wt/{id} (worktree remove failed)");
1663                    }
1664                }
1665            }
1666        }
1667    }
1668
1669    if !quiet {
1670        report_other_worktrees(root);
1671    }
1672
1673    CleanRepoStats {
1674        removed_worktrees,
1675        freed_bytes,
1676    }
1677}
1678
1679#[derive(Debug)]
1680pub struct GitWorktreeInfo {
1681    pub path: PathBuf,
1682    pub head_sha: Option<String>,
1683    pub branch: Option<String>,
1684    pub is_detached: bool,
1685    pub is_bare: bool,
1686}
1687
1688/// Parses git worktrees from `git worktree list --porcelain`.
1689pub fn parse_worktree_list(root: &Path) -> Vec<GitWorktreeInfo> {
1690    let out = std::process::Command::new("git")
1691        .args(["worktree", "list", "--porcelain"])
1692        .current_dir(root)
1693        .output();
1694    let Ok(o) = out else {
1695        return Vec::new();
1696    };
1697    if !o.status.success() {
1698        return Vec::new();
1699    }
1700    let text = String::from_utf8_lossy(&o.stdout);
1701
1702    let mut list = Vec::new();
1703    let mut cur_path: Option<PathBuf> = None;
1704    let mut cur_head: Option<String> = None;
1705    let mut cur_branch: Option<String> = None;
1706    let mut cur_detached = false;
1707    let mut cur_bare = false;
1708
1709    let mut finish_entry = |path: &mut Option<PathBuf>,
1710                            head: &mut Option<String>,
1711                            branch: &mut Option<String>,
1712                            detached: &mut bool,
1713                            bare: &mut bool| {
1714        if let Some(p) = path.take() {
1715            list.push(GitWorktreeInfo {
1716                path: p,
1717                head_sha: head.take(),
1718                branch: branch.take(),
1719                is_detached: *detached,
1720                is_bare: *bare,
1721            });
1722            *detached = false;
1723            *bare = false;
1724        }
1725    };
1726
1727    for line in text.lines() {
1728        let line = line.trim();
1729        if line.is_empty() {
1730            finish_entry(
1731                &mut cur_path,
1732                &mut cur_head,
1733                &mut cur_branch,
1734                &mut cur_detached,
1735                &mut cur_bare,
1736            );
1737        } else if let Some(p) = line.strip_prefix("worktree ") {
1738            finish_entry(
1739                &mut cur_path,
1740                &mut cur_head,
1741                &mut cur_branch,
1742                &mut cur_detached,
1743                &mut cur_bare,
1744            );
1745            cur_path = Some(PathBuf::from(p.trim()));
1746        } else if let Some(h) = line.strip_prefix("HEAD ") {
1747            cur_head = Some(h.trim().to_string());
1748        } else if let Some(b) = line.strip_prefix("branch ") {
1749            let b_str = b.trim();
1750            let b_name = b_str.strip_prefix("refs/heads/").unwrap_or(b_str);
1751            cur_branch = Some(b_name.to_string());
1752        } else if line == "detached" {
1753            cur_detached = true;
1754        } else if line == "bare" {
1755            cur_bare = true;
1756        }
1757    }
1758    finish_entry(
1759        &mut cur_path,
1760        &mut cur_head,
1761        &mut cur_branch,
1762        &mut cur_detached,
1763        &mut cur_bare,
1764    );
1765    list
1766}
1767
1768/// Formats a worktree path for display and for git CLI commands:
1769/// relative to `root` if inside `root` or a sibling (same parent directory);
1770/// otherwise absolute.
1771pub fn display_worktree_path(target: &Path, root: &Path) -> String {
1772    let target_canon = target
1773        .canonicalize()
1774        .unwrap_or_else(|_| target.to_path_buf());
1775    let root_canon = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
1776
1777    // Inside the repository root
1778    if let Ok(rel) = target_canon.strip_prefix(&root_canon) {
1779        if !rel.as_os_str().is_empty() {
1780            return rel.to_string_lossy().replace('\\', "/");
1781        }
1782    }
1783
1784    // Sibling (same parent directory, e.g. ../app--side)
1785    if target_canon != root_canon {
1786        if let (Some(root_parent), Some(target_parent)) =
1787            (root_canon.parent(), target_canon.parent())
1788        {
1789            if root_parent == target_parent {
1790                if let Some(file_name) = target_canon.file_name() {
1791                    let rel = Path::new("..").join(file_name);
1792                    return rel.to_string_lossy().replace('\\', "/");
1793                }
1794            }
1795        }
1796    }
1797
1798    // Otherwise show the absolute path
1799    target_canon.to_string_lossy().replace('\\', "/")
1800}
1801
1802/// Returns true if `root` is a linked worktree (its git-dir differs from its git-common-dir).
1803pub fn is_linked_worktree(root: &Path) -> bool {
1804    let git_dir_out = std::process::Command::new("git")
1805        .args(["rev-parse", "--git-dir"])
1806        .current_dir(root)
1807        .output();
1808    let common_dir_out = std::process::Command::new("git")
1809        .args(["rev-parse", "--git-common-dir"])
1810        .current_dir(root)
1811        .output();
1812    match (git_dir_out, common_dir_out) {
1813        (Ok(gd), Ok(cd)) if gd.status.success() && cd.status.success() => {
1814            let gd_str = String::from_utf8_lossy(&gd.stdout).trim().to_string();
1815            let cd_str = String::from_utf8_lossy(&cd.stdout).trim().to_string();
1816            if gd_str == cd_str {
1817                return false;
1818            }
1819            let gd_path = if Path::new(&gd_str).is_absolute() {
1820                PathBuf::from(&gd_str)
1821            } else {
1822                root.join(&gd_str)
1823            };
1824            let cd_path = if Path::new(&cd_str).is_absolute() {
1825                PathBuf::from(&cd_str)
1826            } else {
1827                root.join(&cd_str)
1828            };
1829            let gd_canon = gd_path.canonicalize().unwrap_or(gd_path);
1830            let cd_canon = cd_path.canonicalize().unwrap_or(cd_path);
1831            gd_canon != cd_canon
1832        }
1833        _ => false,
1834    }
1835}
1836
1837/// Returns true if any path component is `.wt`.
1838pub fn has_wt_component(path: &Path) -> bool {
1839    path.components().any(|c| c.as_os_str() == ".wt")
1840}
1841
1842/// Checks whether a worktree's working tree is clean:
1843/// `git status --porcelain` lists nothing other than `.DS_Store` files, at any depth.
1844pub fn is_worktree_clean(wt_path: &Path) -> bool {
1845    let out = std::process::Command::new("git")
1846        .arg("-C")
1847        .arg(wt_path.as_os_str())
1848        .args(["status", "--porcelain", "-u"])
1849        .output();
1850    match out {
1851        Ok(o) if o.status.success() => {
1852            let stdout = String::from_utf8_lossy(&o.stdout);
1853            for line in stdout.lines() {
1854                let trimmed = line.trim();
1855                if trimmed.is_empty() {
1856                    continue;
1857                }
1858                if line.len() < 3 {
1859                    return false;
1860                }
1861                let mut path_part = line[3..].trim();
1862                if let Some((_, new_path)) = path_part.split_once(" -> ") {
1863                    path_part = new_path.trim();
1864                }
1865                let unquoted = path_part
1866                    .strip_prefix('"')
1867                    .and_then(|p| p.strip_suffix('"'))
1868                    .unwrap_or(path_part);
1869                if Path::new(unquoted).file_name() != Some(std::ffi::OsStr::new(".DS_Store")) {
1870                    return false;
1871                }
1872            }
1873            true
1874        }
1875        _ => false,
1876    }
1877}
1878
1879/// Inspects other worktrees (excluding main checkout, linked-worktree roots,
1880/// and blyte's `.wt/<id>` runs), and reports any that are both merged and clean.
1881/// Never deletes them.
1882pub fn report_other_worktrees(root: &Path) {
1883    // Only report from the main worktree. If the root being cleaned is a linked worktree,
1884    // print nothing about other worktrees for it.
1885    if is_linked_worktree(root) {
1886        return;
1887    }
1888
1889    let worktrees = parse_worktree_list(root);
1890    let root_canon = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
1891    let main_canon = worktrees
1892        .first()
1893        .map(|wt| wt.path.canonicalize().unwrap_or_else(|_| wt.path.clone()));
1894
1895    let mut other_count = 0;
1896    let mut other_bytes = 0;
1897
1898    for (idx, wt) in worktrees.into_iter().enumerate() {
1899        // Never list the main worktree (first entry of git worktree list --porcelain)
1900        if idx == 0 {
1901            continue;
1902        }
1903        if wt.is_bare {
1904            continue;
1905        }
1906        if !wt.path.exists() {
1907            continue;
1908        }
1909
1910        let wt_canon = wt.path.canonicalize().unwrap_or_else(|_| wt.path.clone());
1911        // Skip the main checkout as well as the root itself
1912        if wt_canon == root_canon || wt.path == root {
1913            continue;
1914        }
1915        if Some(&wt_canon) == main_canon.as_ref() {
1916            continue;
1917        }
1918        // Never list blyte runs: exclude any worktree whose path has a .wt directory component anywhere
1919        if has_wt_component(&wt.path) || has_wt_component(&wt_canon) {
1920            continue;
1921        }
1922
1923        // Check if merged
1924        let is_merged = if let Some(ref branch) = wt.branch {
1925            is_branch_merged(root, branch)
1926        } else if let Some(ref sha) = wt.head_sha {
1927            is_commit_merged(root, sha)
1928        } else {
1929            false
1930        };
1931
1932        if !is_merged {
1933            continue;
1934        }
1935
1936        // Check if clean (lists nothing other than .DS_Store files)
1937        if !is_worktree_clean(&wt.path) {
1938            continue;
1939        }
1940
1941        let size = dir_size(&wt.path);
1942        let path_str = display_worktree_path(&wt.path, root);
1943        let branch_label = wt.branch.as_deref().unwrap_or_else(|| {
1944            wt.head_sha
1945                .as_deref()
1946                .map(|s| &s[..s.len().min(7)])
1947                .unwrap_or("detached")
1948        });
1949
1950        println!(
1951            "merged worktree {path_str} ({branch_label}, {}): git worktree remove {path_str}",
1952            format_size(size)
1953        );
1954
1955        other_count += 1;
1956        other_bytes += size;
1957    }
1958
1959    if other_count > 0 {
1960        println!(
1961            "{other_count} other worktrees are merged and clean ({}); remove them with the commands above",
1962            format_size(other_bytes)
1963        );
1964    }
1965}
1966
1967/// Runs the `blyte clean` command.
1968pub fn run(args: &crate::cli::CleanArgs) -> i32 {
1969    let repos = if args.all {
1970        crate::registry::registered()
1971    } else {
1972        match find_repo_root() {
1973            Ok(root) => vec![root],
1974            Err(e) => {
1975                eprintln!("error: {e}");
1976                return 2;
1977            }
1978        }
1979    };
1980
1981    let mut total_freed = 0;
1982    for repo in &repos {
1983        let stats = clean_repo(repo, args.older_than, args.dry_run, None, false, None);
1984        total_freed += stats.freed_bytes;
1985    }
1986
1987    if args.dry_run {
1988        println!("would free {}", format_size(total_freed));
1989    } else {
1990        println!("freed {}", format_size(total_freed));
1991    }
1992
1993    0
1994}
1995
1996/// Quiet cleanup at dispatch start: no output unless something was removed,
1997/// then one line `blyte: removed N finished worktrees (X GB)` on stderr.
1998/// Never fails the dispatch: logs errors to stderr and goes on.
1999pub fn clean_quiet(root: &Path, skip_id: Option<&str>) {
2000    clean_quiet_with_budget(root, skip_id, std::time::Duration::from_secs(1));
2001}
2002
2003pub fn clean_quiet_with_budget(
2004    root: &Path,
2005    skip_id: Option<&str>,
2006    time_budget: std::time::Duration,
2007) {
2008    let stats = clean_repo(root, 14, false, skip_id, true, Some(time_budget));
2009    if stats.removed_worktrees > 0 {
2010        eprintln!(
2011            "blyte: removed {} finished worktrees ({})",
2012            stats.removed_worktrees,
2013            format_size(stats.freed_bytes)
2014        );
2015    }
2016}
2017
2018/// Removes a run's worktree on review after recording the verdict under the same rules.
2019/// Removes the worktree only when the rules allow it now (e.g. redone, or work already merged);
2020/// otherwise prints nothing extra beyond the verdict line, except for accepted/fixed prints
2021/// `worktree .wt/<id> kept until wip/<id> is merged`.
2022pub fn clean_on_review(root: &Path, id: &str) {
2023    let wt_path = root.join(".wt").join(id);
2024    if !wt_path.exists() {
2025        clean_quiet(root, Some(id));
2026        return;
2027    }
2028
2029    let mut ctx = CleanContext::new(root);
2030    let branch_name = format!("wip/{id}");
2031    let branch_exists = ctx.get_branch_tip(&branch_name).is_some();
2032
2033    let verdict_path = root.join(".wt").join(format!("{id}.verdict.json"));
2034    let verdict_str = std::fs::read_to_string(&verdict_path)
2035        .ok()
2036        .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
2037        .and_then(|v| {
2038            v.get("verdict")
2039                .and_then(|s| s.as_str())
2040                .map(|s| s.to_string())
2041        })
2042        .unwrap_or_default();
2043
2044    let is_res = ctx.is_research_run(id);
2045    let removable = match ctx.check_removable(id, 14) {
2046        Ok(_) => is_res || !has_uncommitted_changes(&wt_path),
2047        Err(_) => false,
2048    };
2049
2050    if !removable {
2051        if verdict_str == "accepted" || verdict_str == "fixed" {
2052            println!("worktree .wt/{id} kept until {branch_name} is merged");
2053        }
2054        clean_quiet(root, Some(id));
2055        return;
2056    }
2057
2058    let removed_ok = if is_res {
2059        std::fs::remove_dir_all(&wt_path).is_ok()
2060    } else {
2061        let rm_out = std::process::Command::new("git")
2062            .args(["worktree", "remove", wt_path.to_str().unwrap_or("")])
2063            .current_dir(root)
2064            .output();
2065        let _ = std::process::Command::new("git")
2066            .args(["worktree", "prune"])
2067            .current_dir(root)
2068            .output();
2069        rm_out.map(|o| o.status.success()).unwrap_or(false)
2070    };
2071
2072    if !removed_ok {
2073        if verdict_str == "accepted" || verdict_str == "fixed" {
2074            println!("worktree .wt/{id} kept until {branch_name} is merged");
2075        }
2076        clean_quiet(root, Some(id));
2077        return;
2078    }
2079
2080    if branch_exists {
2081        let is_merged = ctx.check_run_merged(id).is_some();
2082        if is_merged {
2083            let del_out = std::process::Command::new("git")
2084                .args(["branch", "-D", &branch_name])
2085                .current_dir(root)
2086                .output();
2087            if del_out.map(|o| o.status.success()).unwrap_or(false) {
2088                ctx.wip_branch_tips.remove(&branch_name);
2089                println!("removed .wt/{id}; branch {branch_name} deleted");
2090            } else {
2091                println!("removed .wt/{id}; branch {branch_name} kept");
2092            }
2093        } else {
2094            println!("removed .wt/{id}; branch {branch_name} kept");
2095        }
2096    } else {
2097        println!("removed .wt/{id}");
2098    }
2099
2100    clean_quiet(root, Some(id));
2101}