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