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