Skip to main content

blyte_cli/
clean.rs

1//! Worktree cleanup for finished runs: `blyte clean`, on review, and at dispatch.
2
3use std::collections::{HashMap, HashSet};
4use std::path::{Path, PathBuf};
5
6#[derive(Debug, PartialEq, Eq, Clone)]
7pub enum RemovalReason {
8    Merged,
9    MergedInto(String),
10    MergedThrough(String),
11    SessionMerged(String),
12    Verdict(String),
13    NoChanges,
14    ResearchReport,
15    ResearchReportInWorktree,
16    ResearchEndedWithoutReport(String),
17    ResearchStoppedWithoutSummary(u64),
18    OlderThan(u64),
19}
20
21impl std::fmt::Display for RemovalReason {
22    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
23        match self {
24            Self::Merged => write!(f, "merged"),
25            Self::MergedInto(base) => write!(f, "merged into {base}"),
26            Self::MergedThrough(child) => write!(f, "merged through {child}"),
27            Self::SessionMerged(branch) => write!(f, "{branch} merged"),
28            Self::Verdict(v) => {
29                if v.is_empty() {
30                    write!(f, "verdict")
31                } else {
32                    write!(f, "verdict {v}")
33                }
34            }
35            Self::NoChanges => write!(f, "no changes"),
36            Self::ResearchReport => write!(f, "research report"),
37            Self::ResearchReportInWorktree => {
38                write!(f, "research report (copied out on removal)")
39            }
40            Self::ResearchEndedWithoutReport(outcome) => {
41                write!(f, "research run ended without a report ({outcome})")
42            }
43            Self::ResearchStoppedWithoutSummary(d) => {
44                write!(
45                    f,
46                    "research run stopped without a summary, started more than {d} days ago"
47                )
48            }
49            Self::OlderThan(d) => write!(f, "finished over {d} days ago"),
50        }
51    }
52}
53
54#[derive(Debug, PartialEq, Eq)]
55pub enum KeptReason {
56    UncommittedChanges,
57    Running,
58    NoVerdict,
59    NotMergedYet,
60    NoReport,
61    UnreadableSummary,
62    InUse,
63    CannotCheckInUse(String),
64    UsedRecently(u64),
65    HoldsRuns(String),
66    UnreadableStartRecord(String),
67    Custom(String),
68}
69
70impl std::fmt::Display for KeptReason {
71    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
72        match self {
73            Self::UncommittedChanges => write!(f, "uncommitted changes"),
74            Self::Running => write!(f, "running"),
75            Self::NoVerdict => write!(f, "no verdict"),
76            Self::NotMergedYet => write!(f, "not merged yet"),
77            Self::NoReport => write!(f, "no report"),
78            Self::UnreadableSummary => write!(f, "unreadable summary"),
79            Self::InUse => write!(f, "in use by a running process"),
80            Self::CannotCheckInUse(err) => {
81                write!(f, "cannot tell whether it is in use: {err}")
82            }
83            Self::UsedRecently(d) => write!(f, "used in the last {d} days"),
84            Self::HoldsRuns(path) => write!(f, "holds runs: review them from {path}"),
85            Self::UnreadableStartRecord(reason) => write!(f, "unreadable start record: {reason}"),
86            Self::Custom(s) => write!(f, "{s}"),
87        }
88    }
89}
90
91/// Recursively computes directory size in bytes without following symlinks.
92pub fn dir_size(path: &Path) -> u64 {
93    let mut total = 0;
94    let Ok(meta) = std::fs::symlink_metadata(path) else {
95        return 0;
96    };
97    if meta.file_type().is_symlink() {
98        return 0;
99    }
100    if meta.is_file() {
101        return meta.len();
102    }
103    if meta.is_dir() {
104        let Ok(entries) = std::fs::read_dir(path) else {
105            return 0;
106        };
107        for entry in entries.flatten() {
108            let Ok(ft) = entry.file_type() else {
109                continue;
110            };
111            if ft.is_symlink() {
112                continue;
113            } else if ft.is_dir() {
114                total += dir_size(&entry.path());
115            } else if ft.is_file() {
116                if let Ok(m) = entry.metadata() {
117                    total += m.len();
118                }
119            }
120        }
121    }
122    total
123}
124
125/// Formats byte count into human-readable representation: e.g. "812 MB", "12.3 GB".
126pub fn format_size(bytes: u64) -> String {
127    const KB: f64 = 1024.0;
128    const MB: f64 = 1024.0 * 1024.0;
129    const GB: f64 = 1024.0 * 1024.0 * 1024.0;
130    let b = bytes as f64;
131    let (val, unit) = if b >= GB {
132        (b / GB, "GB")
133    } else if b >= MB {
134        (b / MB, "MB")
135    } else if b >= KB {
136        (b / KB, "KB")
137    } else {
138        return format!("{bytes} B");
139    };
140
141    let s = if val >= 100.0 {
142        format!("{val:.0}")
143    } else {
144        let formatted = format!("{val:.1}");
145        formatted
146            .strip_suffix(".0")
147            .unwrap_or(&formatted)
148            .to_string()
149    };
150    format!("{s} {unit}")
151}
152
153/// Checks whether a process with the given PID is alive.
154pub fn is_pid_alive(pid: i64) -> bool {
155    if pid <= 0 {
156        return false;
157    }
158    let ret = unsafe { libc::kill(pid as libc::pid_t, 0) };
159    if ret == 0 {
160        true
161    } else {
162        std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
163    }
164}
165
166/// Finds the root repository (resolving the main checkout if inside a linked worktree).
167pub fn find_repo_root() -> Result<PathBuf, String> {
168    let out = std::process::Command::new("git")
169        .args([
170            "rev-parse",
171            "--path-format=absolute",
172            "--show-toplevel",
173            "--git-dir",
174            "--git-common-dir",
175        ])
176        .output()
177        .map_err(|e| format!("git not found: {e}"))?;
178    if !out.status.success() {
179        return Err("not a git repository".to_string());
180    }
181    let text = String::from_utf8_lossy(&out.stdout);
182    let mut lines = text.lines();
183    let (Some(toplevel), Some(git_dir), Some(common_dir)) =
184        (lines.next(), lines.next(), lines.next())
185    else {
186        return Err("not a git repository".to_string());
187    };
188    let root = PathBuf::from(toplevel.trim());
189    let git_dir = git_dir.trim();
190    let common_dir = common_dir.trim();
191    if git_dir != common_dir {
192        let common = PathBuf::from(common_dir);
193        let main = (|| -> Option<PathBuf> {
194            if common.file_name()? != ".git" {
195                return None;
196            }
197            let parent = common.parent()?;
198            let parent_canon = parent.canonicalize().ok()?;
199            let root_canon = root.canonicalize().ok()?;
200            if parent_canon == root_canon {
201                return None;
202            }
203            Some(parent.to_path_buf())
204        })();
205        main.ok_or_else(|| {
206            format!(
207                "cannot find main checkout for linked worktree {}",
208                root.display()
209            )
210        })
211    } else {
212        Ok(root)
213    }
214}
215
216/// Checks whether a run is a research run from its start file.
217pub fn is_research(root: &Path, id: &str) -> bool {
218    let start_path = root.join(".wt").join(format!("{id}.start.json"));
219    if let Ok(s) = std::fs::read_to_string(&start_path) {
220        if let Ok(val) = serde_json::from_str::<serde_json::Value>(&s) {
221            return val
222                .get("research")
223                .and_then(|r| r.as_bool())
224                .unwrap_or(false);
225        }
226    }
227    false
228}
229
230/// Checks whether a worktree has uncommitted changes via `git status --porcelain`.
231pub fn has_uncommitted_changes(wt_path: &Path) -> bool {
232    let out = std::process::Command::new("git")
233        .args([
234            "-C",
235            wt_path.to_str().unwrap_or(""),
236            "status",
237            "--porcelain",
238        ])
239        .output();
240    match out {
241        Ok(o) if o.status.success() => {
242            !o.stdout.is_empty() && !String::from_utf8_lossy(&o.stdout).trim().is_empty()
243        }
244        _ => true,
245    }
246}
247
248fn git_tree_sha(root: &Path, ref_name: &str) -> Option<String> {
249    let out = std::process::Command::new("git")
250        .args(["rev-parse", &format!("{ref_name}^{{tree}}")])
251        .current_dir(root)
252        .output()
253        .ok()?;
254    if out.status.success() {
255        Some(String::from_utf8_lossy(&out.stdout).trim().to_string())
256    } else {
257        None
258    }
259}
260
261fn is_cherry_merged_into_target(root: &Path, commit_sha: &str, target: &str) -> bool {
262    let cherry_out = std::process::Command::new("git")
263        .args(["cherry", target, commit_sha])
264        .current_dir(root)
265        .output();
266    if let Ok(o) = cherry_out {
267        if o.status.success() {
268            let s = String::from_utf8_lossy(&o.stdout);
269            let lines: Vec<&str> = s
270                .lines()
271                .map(|l| l.trim())
272                .filter(|l| !l.is_empty())
273                .collect();
274            if !lines.is_empty() && lines.iter().all(|l| l.starts_with('-')) {
275                return true;
276            }
277        }
278    }
279    false
280}
281
282fn is_merge_tree_merged_into_target(
283    root: &Path,
284    commit_sha: &str,
285    target: &str,
286    target_tree: Option<&str>,
287) -> bool {
288    let target_tree_sha = match target_tree {
289        Some(t) => Some(t.to_string()),
290        None => git_tree_sha(root, target),
291    };
292    if let Some(target_tree_sha) = target_tree_sha {
293        let merge_tree_out = std::process::Command::new("git")
294            .args(["merge-tree", "--write-tree", target, commit_sha])
295            .current_dir(root)
296            .output();
297        if let Ok(mt_o) = merge_tree_out {
298            if mt_o.status.success() {
299                let mt_stdout = String::from_utf8_lossy(&mt_o.stdout);
300                if let Some(first_line) = mt_stdout.lines().next() {
301                    if first_line.trim() == target_tree_sha {
302                        return true;
303                    }
304                }
305            }
306        }
307    }
308    false
309}
310
311fn parse_started_at(val: &serde_json::Value) -> Option<u64> {
312    let s = val.get("started_at")?;
313    if let Some(n) = s.as_u64() {
314        Some(n)
315    } else if let Some(n) = s.as_i64() {
316        if n >= 0 {
317            Some(n as u64)
318        } else {
319            None
320        }
321    } else if let Some(f) = s.as_f64() {
322        if f >= 0.0 {
323            Some(f as u64)
324        } else {
325            None
326        }
327    } else if let Some(st) = s.as_str() {
328        st.parse::<u64>().ok()
329    } else {
330        None
331    }
332}
333
334fn check_history_merged_with_base(
335    root: &Path,
336    tip_sha: &str,
337    target: &str,
338    merge_base: &str,
339    started_at: Option<&serde_json::Value>,
340) -> bool {
341    let diff_out = std::process::Command::new("git")
342        .args(["diff", "--name-only", merge_base, tip_sha])
343        .current_dir(root)
344        .output();
345    let Ok(diff_o) = diff_out else {
346        return false;
347    };
348    if !diff_o.status.success() {
349        return false;
350    }
351    let files: Vec<String> = String::from_utf8_lossy(&diff_o.stdout)
352        .lines()
353        .map(|l| l.trim().to_string())
354        .filter(|l| !l.is_empty())
355        .collect();
356
357    if files.is_empty() {
358        return false;
359    }
360
361    let since_arg = started_at
362        .and_then(|v| {
363            if let Some(n) = v.as_i64() {
364                if n >= 100_000_000 {
365                    Some(format!("--since={n}"))
366                } else {
367                    Some("--since=1970-01-01T00:00:00Z".to_string())
368                }
369            } else if let Some(n) = v.as_u64() {
370                if n >= 100_000_000 {
371                    Some(format!("--since={n}"))
372                } else {
373                    Some("--since=1970-01-01T00:00:00Z".to_string())
374                }
375            } else {
376                v.as_str().map(|s| format!("--since={s}"))
377            }
378        })
379        .unwrap_or_else(|| "--since=1970-01-01T00:00:00Z".to_string());
380
381    let mut cmd = std::process::Command::new("git");
382    cmd.args([
383        "rev-list",
384        "--first-parent",
385        &since_arg,
386        "-n",
387        "20",
388        target,
389        "--",
390    ]);
391    for f in &files {
392        cmd.arg(f);
393    }
394    cmd.current_dir(root);
395    let Ok(rev_o) = cmd.output() else {
396        return false;
397    };
398    if !rev_o.status.success() {
399        return false;
400    }
401
402    let commits: Vec<String> = String::from_utf8_lossy(&rev_o.stdout)
403        .lines()
404        .map(|l| l.trim().to_string())
405        .filter(|l| !l.is_empty())
406        .collect();
407
408    for c in commits {
409        let mt_out = std::process::Command::new("git")
410            .args(["merge-tree", "--write-tree", &c, tip_sha])
411            .current_dir(root)
412            .output();
413        let Ok(mt_o) = mt_out else {
414            continue;
415        };
416        if !mt_o.status.success() {
417            continue;
418        }
419        let mt_stdout = String::from_utf8_lossy(&mt_o.stdout);
420        let Some(first_line) = mt_stdout.lines().next() else {
421            continue;
422        };
423        let mt_tree = first_line.trim();
424
425        if let Some(c_tree) = git_tree_sha(root, &c) {
426            if mt_tree == c_tree {
427                return true;
428            }
429        }
430    }
431
432    false
433}
434
435/// Reads `.wt/<id>.start.json` from disk now.
436///
437/// A missing file is `Ok(None)`. A read error, or content that is not a JSON object
438/// (including an empty or half-written file), is an error naming the path and the reason.
439pub fn read_start_record(root: &Path, id: &str) -> Result<Option<serde_json::Value>, String> {
440    let path = root.join(".wt").join(format!("{id}.start.json"));
441    let content = match std::fs::read_to_string(&path) {
442        Ok(content) => content,
443        Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(None),
444        Err(err) => return Err(format!("{}: {err}", path.display())),
445    };
446    match serde_json::from_str::<serde_json::Value>(&content) {
447        Ok(value) if value.is_object() => Ok(Some(value)),
448        Ok(_) => Err(format!("{}: not a JSON object", path.display())),
449        Err(err) => Err(format!("{}: {err}", path.display())),
450    }
451}
452
453#[derive(Debug, Clone)]
454pub struct RefEntry {
455    pub objectname: String,
456    pub symref: Option<String>,
457    pub tree: Option<String>,
458}
459
460fn load_refs(root: &Path) -> (HashMap<String, RefEntry>, bool) {
461    let mut refs = HashMap::new();
462    let out = std::process::Command::new("git")
463        .args([
464            "for-each-ref",
465            "--format=%(refname)%09%(objectname)%09%(symref)%09%(tree)",
466            "refs/heads",
467            "refs/remotes/origin",
468        ])
469        .current_dir(root)
470        .output();
471    let Ok(o) = out else {
472        return (refs, false);
473    };
474    if !o.status.success() {
475        return (refs, false);
476    }
477    for line in String::from_utf8_lossy(&o.stdout).lines() {
478        let mut cols = line.split('\t');
479        let Some(refname) = cols.next() else {
480            continue;
481        };
482        let Some(objectname) = cols.next() else {
483            continue;
484        };
485        let symref = cols.next().unwrap_or("");
486        let tree = cols.next().unwrap_or("");
487        if refname.is_empty() || objectname.is_empty() {
488            continue;
489        }
490        refs.insert(
491            refname.to_string(),
492            RefEntry {
493                objectname: objectname.to_string(),
494                symref: if symref.is_empty() {
495                    None
496                } else {
497                    Some(symref.to_string())
498                },
499                tree: if tree.is_empty() {
500                    None
501                } else {
502                    Some(tree.to_string())
503                },
504            },
505        );
506    }
507    (refs, true)
508}
509
510fn lookup_ref<'b>(
511    refs: &'b HashMap<String, RefEntry>,
512    name: &str,
513) -> Option<(&'b str, &'b RefEntry)> {
514    if name.starts_with("refs/") {
515        return refs.get_key_value(name).map(|(k, v)| (k.as_str(), v));
516    }
517    let head_key = format!("refs/heads/{name}");
518    if let Some((k, v)) = refs.get_key_value(&head_key) {
519        return Some((k.as_str(), v));
520    }
521    let remote_key = format!("refs/remotes/{name}");
522    if let Some((k, v)) = refs.get_key_value(&remote_key) {
523        return Some((k.as_str(), v));
524    }
525    None
526}
527
528fn find_default_branch_from_refs(refs: &HashMap<String, RefEntry>) -> String {
529    if let Some(head_entry) = refs.get("refs/remotes/origin/HEAD") {
530        if let Some(ref symref) = head_entry.symref {
531            let target = symref.strip_prefix("refs/remotes/").unwrap_or(symref);
532            let branch_name = target.strip_prefix("origin/").unwrap_or(target);
533            if refs.contains_key(&format!("refs/heads/{branch_name}")) {
534                return branch_name.to_string();
535            }
536            if refs.contains_key(symref) || refs.contains_key(&format!("refs/remotes/{target}")) {
537                return target.to_string();
538            }
539            return branch_name.to_string();
540        }
541    }
542    if refs.contains_key("refs/heads/main") {
543        return "main".to_string();
544    }
545    if refs.contains_key("refs/heads/master") {
546        return "master".to_string();
547    }
548    "main".to_string()
549}
550
551/// Context for cleaning a repository, caching metadata to avoid redundant git calls and disk reads.
552pub struct CleanContext<'a> {
553    pub root: &'a Path,
554    pub start_files: HashMap<String, serde_json::Value>,
555    pub all_run_ids: Vec<String>,
556    pub refs: HashMap<String, RefEntry>,
557    pub refs_loaded: bool,
558    pub wip_branch_tips: HashMap<String, String>,
559    pub default_branch: String,
560    pub origin_default: Option<String>,
561    pub default_tree: Option<String>,
562    pub origin_default_tree: Option<String>,
563    pub wip_contains_cache: HashMap<String, Vec<String>>,
564    pub merged_cache: HashMap<String, Option<RemovalReason>>,
565    pub branch_contains_calls: usize,
566    pub cherry_pick_set: Option<HashSet<String>>,
567    pub rev_list_cache: HashMap<String, Vec<String>>,
568    pub ancestor_cache: HashMap<(String, String), bool>,
569    pub contains_target: HashSet<(String, String)>,
570    pub merge_base_cache: HashMap<(String, String), Option<String>>,
571    pub cherry_cache: HashMap<(String, String), bool>,
572    pub merge_tree_cache: HashMap<(String, String), bool>,
573}
574
575impl<'a> CleanContext<'a> {
576    pub fn new(root: &'a Path) -> Self {
577        let mut start_files = HashMap::new();
578        let mut all_run_ids = Vec::new();
579        let wt_dir = root.join(".wt");
580        if let Ok(entries) = std::fs::read_dir(&wt_dir) {
581            for entry in entries.flatten() {
582                let name = entry.file_name().to_string_lossy().to_string();
583                if let Some(id) = name.strip_suffix(".start.json") {
584                    all_run_ids.push(id.to_string());
585                    if let Ok(content) = std::fs::read_to_string(entry.path()) {
586                        if let Ok(val) = serde_json::from_str::<serde_json::Value>(&content) {
587                            start_files.insert(id.to_string(), val);
588                        }
589                    }
590                }
591            }
592        }
593        all_run_ids.sort();
594
595        let (refs, refs_loaded) = load_refs(root);
596
597        let mut wip_branch_tips = HashMap::new();
598        for (refname, entry) in &refs {
599            if let Some(short) = refname.strip_prefix("refs/heads/") {
600                if short.starts_with("wip/") {
601                    wip_branch_tips.insert(short.to_string(), entry.objectname.clone());
602                }
603            }
604        }
605
606        let default_branch = if refs_loaded {
607            find_default_branch_from_refs(&refs)
608        } else {
609            find_default_branch(root)
610        };
611        let name = default_branch
612            .strip_prefix("origin/")
613            .unwrap_or(&default_branch);
614        let remote = format!("origin/{name}");
615        let origin_default = if remote != default_branch
616            && if refs_loaded {
617                refs.contains_key(&format!("refs/remotes/{remote}"))
618            } else {
619                git_ok(root, &["rev-parse", "--verify", "--quiet", &remote])
620            } {
621            Some(remote)
622        } else {
623            None
624        };
625
626        let default_tree = if refs_loaded {
627            lookup_ref(&refs, &default_branch).and_then(|(_, e)| e.tree.clone())
628        } else {
629            git_tree_sha(root, &default_branch)
630        };
631        let origin_default_tree = origin_default.as_deref().and_then(|r| {
632            if refs_loaded {
633                lookup_ref(&refs, r).and_then(|(_, e)| e.tree.clone())
634            } else {
635                git_tree_sha(root, r)
636            }
637        });
638
639        let mut ancestor_cache = HashMap::new();
640        let mut contains_target = HashSet::new();
641
642        if refs_loaded {
643            let mut default_targets: Vec<String> = Vec::new();
644            if lookup_ref(&refs, &default_branch).is_some() {
645                default_targets.push(default_branch.clone());
646            }
647            if let Some(ref origin_def) = origin_default {
648                if lookup_ref(&refs, origin_def).is_some() {
649                    default_targets.push(origin_def.clone());
650                }
651            }
652
653            let mut seen_target_shas = HashSet::new();
654            for target in &default_targets {
655                let Some((_, target_entry)) = lookup_ref(&refs, target) else {
656                    continue;
657                };
658                let target_sha = target_entry.objectname.clone();
659                if !seen_target_shas.insert(target_sha.clone()) {
660                    continue;
661                }
662
663                let merged_out = std::process::Command::new("git")
664                    .args([
665                        "for-each-ref",
666                        &format!("--merged={target}"),
667                        "--format=%(refname:short)",
668                        "refs/heads",
669                    ])
670                    .current_dir(root)
671                    .output();
672                if let Ok(o) = merged_out {
673                    if o.status.success() {
674                        let merged_set: HashSet<String> = String::from_utf8_lossy(&o.stdout)
675                            .lines()
676                            .map(|l| l.trim().to_string())
677                            .filter(|l| !l.is_empty())
678                            .collect();
679                        for (refname, entry) in &refs {
680                            if let Some(short) = refname.strip_prefix("refs/heads/") {
681                                ancestor_cache.insert(
682                                    (entry.objectname.clone(), target_sha.clone()),
683                                    merged_set.contains(short),
684                                );
685                            }
686                        }
687                    }
688                }
689
690                let contains_out = std::process::Command::new("git")
691                    .args([
692                        "for-each-ref",
693                        &format!("--contains={target}"),
694                        "--format=%(refname:short)",
695                        "refs/heads",
696                    ])
697                    .current_dir(root)
698                    .output();
699                if let Ok(o) = contains_out {
700                    if o.status.success() {
701                        for line in String::from_utf8_lossy(&o.stdout).lines() {
702                            let short = line.trim();
703                            if short.is_empty() {
704                                continue;
705                            }
706                            if let Some(entry) = refs.get(&format!("refs/heads/{short}")) {
707                                contains_target
708                                    .insert((entry.objectname.clone(), target_sha.clone()));
709                            }
710                        }
711                    }
712                }
713            }
714        }
715
716        Self {
717            root,
718            start_files,
719            all_run_ids,
720            refs,
721            refs_loaded,
722            wip_branch_tips,
723            default_branch,
724            origin_default,
725            default_tree,
726            origin_default_tree,
727            wip_contains_cache: HashMap::new(),
728            merged_cache: HashMap::new(),
729            branch_contains_calls: 0,
730            cherry_pick_set: None,
731            rev_list_cache: HashMap::new(),
732            ancestor_cache,
733            contains_target,
734            merge_base_cache: HashMap::new(),
735            cherry_cache: HashMap::new(),
736            merge_tree_cache: HashMap::new(),
737        }
738    }
739
740    pub fn remove_branch(&mut self, branch_name: &str) {
741        self.wip_branch_tips.remove(branch_name);
742        self.refs.remove(&format!("refs/heads/{branch_name}"));
743    }
744
745    pub fn tree_sha(&self, ref_name: &str) -> Option<String> {
746        if let Some((_, entry)) = lookup_ref(&self.refs, ref_name) {
747            if entry.tree.is_some() {
748                return entry.tree.clone();
749            }
750        }
751        if self.refs_loaded
752            && (ref_name.starts_with("refs/heads/") || ref_name.starts_with("refs/remotes/origin/"))
753        {
754            return None;
755        }
756        git_tree_sha(self.root, ref_name)
757    }
758
759    fn ref_exists(&self, refname: &str) -> bool {
760        if lookup_ref(&self.refs, refname).is_some() {
761            return true;
762        }
763        if self.refs_loaded
764            && (refname.starts_with("refs/heads/") || refname.starts_with("refs/remotes/origin/"))
765        {
766            return false;
767        }
768        git_ok(self.root, &["rev-parse", "--verify", "--quiet", refname])
769    }
770
771    fn resolve_base_targets(&self, base: &str) -> Option<(String, Vec<String>)> {
772        resolve_base_targets_with(base, |cand| self.ref_exists(cand))
773    }
774
775    fn target_key(&self, target: &str) -> String {
776        lookup_ref(&self.refs, target)
777            .map(|(_, e)| e.objectname.clone())
778            .unwrap_or_else(|| target.to_string())
779    }
780
781    fn target_is_ancestor_of(&self, target: &str, commit_sha: &str) -> bool {
782        let key = (commit_sha.to_string(), self.target_key(target));
783        self.contains_target.contains(&key)
784    }
785
786    fn merge_base(&mut self, target: &str, commit_sha: &str) -> Option<String> {
787        let key = (self.target_key(target), commit_sha.to_string());
788        if let Some(cached) = self.merge_base_cache.get(&key) {
789            return cached.clone();
790        }
791        let mb_out = std::process::Command::new("git")
792            .args(["merge-base", target, commit_sha])
793            .current_dir(self.root)
794            .output();
795        let mb = match mb_out {
796            Ok(o) if o.status.success() => {
797                let s = String::from_utf8_lossy(&o.stdout).trim().to_string();
798                if s.is_empty() {
799                    None
800                } else {
801                    Some(s)
802                }
803            }
804            _ => None,
805        };
806        self.merge_base_cache.insert(key, mb.clone());
807        mb
808    }
809
810    fn compute_cherry_pick_set(&self) -> HashSet<String> {
811        let unremoved_ids = find_blyte_worktrees(self.root);
812        let candidate_ids: &[String] = if unremoved_ids.is_empty() {
813            &self.all_run_ids
814        } else {
815            &unremoved_ids
816        };
817
818        let mut min_started_at: Option<u64> = None;
819        let mut all_valid = true;
820
821        for id in candidate_ids {
822            let start_val = self.start_files.get(id);
823            let parsed = start_val.and_then(parse_started_at);
824            match parsed {
825                Some(ts) => {
826                    min_started_at = Some(min_started_at.map_or(ts, |m| m.min(ts)));
827                }
828                None => {
829                    all_valid = false;
830                }
831            }
832        }
833
834        let since_arg = if let (true, Some(min_ts)) = (all_valid, min_started_at) {
835            if min_ts >= 86_400 + 100_000_000 {
836                format!("--since={}", min_ts - 86_400)
837            } else {
838                "--since=1970-01-01T00:00:00Z".to_string()
839            }
840        } else {
841            "--since=1970-01-01T00:00:00Z".to_string()
842        };
843
844        let mut targets = Vec::new();
845        let mut seen = HashSet::new();
846
847        if lookup_ref(&self.refs, &self.default_branch).is_some()
848            || (!self.refs_loaded
849                && git_ok(
850                    self.root,
851                    &["rev-parse", "--verify", "--quiet", &self.default_branch],
852                ))
853        {
854            let key = lookup_ref(&self.refs, &self.default_branch)
855                .map(|(k, _)| k.to_string())
856                .unwrap_or_else(|| self.default_branch.clone());
857            if seen.insert(key) {
858                targets.push(self.default_branch.clone());
859            }
860        }
861
862        if let Some(ref origin_def) = self.origin_default {
863            if lookup_ref(&self.refs, origin_def).is_some()
864                || (!self.refs_loaded
865                    && git_ok(self.root, &["rev-parse", "--verify", "--quiet", origin_def]))
866            {
867                let key = lookup_ref(&self.refs, origin_def)
868                    .map(|(k, _)| k.to_string())
869                    .unwrap_or_else(|| origin_def.clone());
870                if seen.insert(key) {
871                    targets.push(origin_def.clone());
872                }
873            }
874        }
875
876        for id in &self.all_run_ids {
877            if let Some(base_str) = self
878                .start_files
879                .get(id)
880                .and_then(|s| s.get("base"))
881                .and_then(|b| b.as_str())
882            {
883                if let Some((_, base_targets)) = self.resolve_base_targets(base_str) {
884                    for bt in base_targets {
885                        let key = lookup_ref(&self.refs, &bt)
886                            .map(|(k, _)| k.to_string())
887                            .unwrap_or_else(|| bt.clone());
888                        if seen.insert(key) {
889                            targets.push(bt);
890                        }
891                    }
892                }
893            }
894        }
895
896        if targets.is_empty() {
897            return HashSet::new();
898        }
899
900        let mut cmd = std::process::Command::new("git");
901        cmd.args(["log", "--format=%B", &since_arg]);
902        for t in &targets {
903            cmd.arg(t);
904        }
905        cmd.current_dir(self.root);
906
907        let mut set = HashSet::new();
908        if let Ok(o) = cmd.output() {
909            if o.status.success() {
910                let text = String::from_utf8_lossy(&o.stdout);
911                for line in text.lines() {
912                    let trimmed = line.trim();
913                    if let Some(rest) = trimmed.strip_prefix("(cherry picked from commit ") {
914                        if let Some(sha) = rest.strip_suffix(')') {
915                            let sha = sha.trim();
916                            if is_commit_id(sha) {
917                                set.insert(sha.to_lowercase());
918                            }
919                        }
920                    }
921                }
922            }
923        }
924
925        set
926    }
927
928    pub fn get_cherry_pick_set(&mut self) -> &HashSet<String> {
929        if self.cherry_pick_set.is_none() {
930            let set = self.compute_cherry_pick_set();
931            self.cherry_pick_set = Some(set);
932        }
933        self.cherry_pick_set.as_ref().unwrap()
934    }
935
936    fn is_ancestor_of_target(&mut self, commit_sha: &str, target: &str) -> bool {
937        let key = (commit_sha.to_string(), self.target_key(target));
938        if let Some(&cached) = self.ancestor_cache.get(&key) {
939            return cached;
940        }
941        let is_anc = std::process::Command::new("git")
942            .args(["merge-base", "--is-ancestor", commit_sha, target])
943            .current_dir(self.root)
944            .output()
945            .map(|c| c.status.success())
946            .unwrap_or(false);
947        self.ancestor_cache.insert(key, is_anc);
948        is_anc
949    }
950
951    fn is_ancestor_of_default(&mut self, commit_sha: &str) -> bool {
952        let def = self.default_branch.clone();
953        if self.is_ancestor_of_target(commit_sha, &def) {
954            return true;
955        }
956        if let Some(origin_def) = self.origin_default.clone() {
957            if self.is_ancestor_of_target(commit_sha, &origin_def) {
958                return true;
959            }
960        }
961        false
962    }
963
964    fn get_run_commits_against_default(&mut self, tip_sha: &str) -> Vec<String> {
965        if let Some(cached) = self.rev_list_cache.get(tip_sha) {
966            return cached.clone();
967        }
968        let out = std::process::Command::new("git")
969            .args(["rev-list", &format!("{}..{}", self.default_branch, tip_sha)])
970            .current_dir(self.root)
971            .output();
972        let commits: Vec<String> = match out {
973            Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout)
974                .lines()
975                .map(|l| l.trim().to_lowercase())
976                .filter(|l| !l.is_empty())
977                .collect(),
978            _ => Vec::new(),
979        };
980        self.rev_list_cache
981            .insert(tip_sha.to_string(), commits.clone());
982        commits
983    }
984
985    fn is_in_cherry_pick_record(&mut self, tip_sha: &str) -> bool {
986        if self.get_cherry_pick_set().is_empty() {
987            return false;
988        }
989        let commits = self.get_run_commits_against_default(tip_sha);
990        if commits.is_empty() {
991            return false;
992        }
993        let cherry_set = self.get_cherry_pick_set();
994        commits.iter().all(|c| cherry_set.contains(c))
995    }
996
997    pub fn get_branch_tip(&self, branch_name: &str) -> Option<String> {
998        if let Some(sha) = self.wip_branch_tips.get(branch_name) {
999            return Some(sha.clone());
1000        }
1001        if let Some(entry) = self.refs.get(&format!("refs/heads/{branch_name}")) {
1002            return Some(entry.objectname.clone());
1003        }
1004        if self.refs_loaded {
1005            return None;
1006        }
1007        get_branch_tip(self.root, branch_name)
1008    }
1009
1010    pub fn is_research_run(&self, id: &str) -> bool {
1011        self.start_files
1012            .get(id)
1013            .and_then(|v| v.get("research"))
1014            .and_then(|r| r.as_bool())
1015            .unwrap_or_else(|| is_research(self.root, id))
1016    }
1017
1018    pub fn get_wip_branches_containing(&mut self, tip_sha: &str) -> Vec<String> {
1019        if let Some(cached) = self.wip_contains_cache.get(tip_sha) {
1020            return cached.clone();
1021        }
1022
1023        self.branch_contains_calls += 1;
1024
1025        let out = std::process::Command::new("git")
1026            .args([
1027                "branch",
1028                "--list",
1029                "--format=%(refname:short)",
1030                "wip/*",
1031                "--contains",
1032                tip_sha,
1033            ])
1034            .current_dir(self.root)
1035            .output();
1036
1037        let mut branches = Vec::new();
1038        if let Ok(o) = out {
1039            if o.status.success() {
1040                for line in String::from_utf8_lossy(&o.stdout).lines() {
1041                    let trimmed = line.trim().trim_start_matches(['*', '+', ' ']).trim();
1042                    if !trimmed.is_empty() {
1043                        branches.push(trimmed.to_string());
1044                    }
1045                }
1046            }
1047        }
1048        self.wip_contains_cache
1049            .insert(tip_sha.to_string(), branches.clone());
1050        branches
1051    }
1052
1053    pub fn get_children_of(&mut self, id: &str, tip_sha: &str) -> Vec<String> {
1054        let mut children = Vec::new();
1055        let mut seen = HashSet::new();
1056
1057        for (candidate_id, start_val) in &self.start_files {
1058            if candidate_id == id {
1059                continue;
1060            }
1061            if let Some(base_str) = start_val.get("base").and_then(|v| v.as_str()) {
1062                let base_str = base_str.trim().trim_end_matches('/');
1063                let target1 = format!("wip/{id}");
1064                let target2 = format!("refs/heads/wip/{id}");
1065                if (base_str == target1 || base_str == target2) && seen.insert(candidate_id.clone())
1066                {
1067                    children.push(candidate_id.clone());
1068                }
1069            }
1070        }
1071
1072        let has_other_without_base = self.start_files.iter().any(|(candidate_id, val)| {
1073            candidate_id != id && val.get("base").is_none_or(|b| b.is_null())
1074        });
1075
1076        if !tip_sha.is_empty() && has_other_without_base {
1077            let tip_sha_owned = tip_sha.to_string();
1078            let containing_branches = self.get_wip_branches_containing(&tip_sha_owned);
1079            for b in containing_branches {
1080                let clean_b = b.strip_prefix("refs/heads/").unwrap_or(&b);
1081                if let Some(candidate_id) = clean_b.strip_prefix("wip/") {
1082                    if candidate_id == id {
1083                        continue;
1084                    }
1085                    if !self.start_files.contains_key(candidate_id) {
1086                        continue;
1087                    }
1088                    let has_base = self
1089                        .start_files
1090                        .get(candidate_id)
1091                        .and_then(|val| val.get("base"))
1092                        .is_some_and(|b| !b.is_null());
1093                    if !has_base && seen.insert(candidate_id.to_string()) {
1094                        children.push(candidate_id.to_string());
1095                    }
1096                }
1097            }
1098        }
1099
1100        children.sort();
1101        children
1102    }
1103
1104    pub fn is_child_run_merged(&mut self, child: &str, visited: &mut HashSet<String>) -> bool {
1105        if self.is_research_run(child) {
1106            return false;
1107        }
1108
1109        let branch_name = format!("wip/{child}");
1110        let tip = self.get_branch_tip(&branch_name);
1111
1112        if tip.is_none() {
1113            let verdict_path = self.root.join(".wt").join(format!("{child}.verdict.json"));
1114            let (has_accepted_verdict, is_redone) = if verdict_path.is_file() {
1115                let v = std::fs::read_to_string(&verdict_path)
1116                    .ok()
1117                    .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
1118                    .and_then(|v| {
1119                        v.get("verdict")
1120                            .and_then(|s| s.as_str())
1121                            .map(|s| s.to_string())
1122                    })
1123                    .unwrap_or_default();
1124                (v == "accepted" || v == "fixed", v == "redone")
1125            } else {
1126                (false, false)
1127            };
1128
1129            if is_redone {
1130                return false;
1131            }
1132
1133            let summary_path = self.root.join(".wt").join(format!("{child}.json"));
1134            let is_verified = std::fs::read_to_string(&summary_path)
1135                .ok()
1136                .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
1137                .and_then(|v| {
1138                    v.get("outcome")
1139                        .and_then(|s| s.as_str())
1140                        .map(|s| s == "verified")
1141                })
1142                .unwrap_or(false);
1143
1144            let wt_gone = !self.root.join(".wt").join(child).is_dir();
1145
1146            return has_accepted_verdict || (is_verified && wt_gone);
1147        }
1148
1149        self.check_run_merged_internal(child, visited).is_some()
1150    }
1151
1152    pub fn check_run_merged(&mut self, id: &str) -> Option<RemovalReason> {
1153        let mut visited = HashSet::new();
1154        self.check_run_merged_internal(id, &mut visited)
1155    }
1156
1157    fn check_run_merged_internal(
1158        &mut self,
1159        id: &str,
1160        visited: &mut HashSet<String>,
1161    ) -> Option<RemovalReason> {
1162        if visited.contains(id) {
1163            return None;
1164        }
1165
1166        if let Some(cached) = self.merged_cache.get(id) {
1167            return cached.clone();
1168        }
1169
1170        visited.insert(id.to_string());
1171
1172        let branch_name = format!("wip/{id}");
1173        let tip_sha = self.get_branch_tip(&branch_name);
1174
1175        let result = self.decide_run_merged(id, tip_sha.as_deref(), visited);
1176
1177        visited.remove(id);
1178
1179        self.merged_cache.insert(id.to_string(), result.clone());
1180        result
1181    }
1182
1183    fn check_history_merged(
1184        &mut self,
1185        tip_sha: &str,
1186        target: &str,
1187        started_at: Option<&serde_json::Value>,
1188    ) -> bool {
1189        if self.target_is_ancestor_of(target, tip_sha) {
1190            return false;
1191        }
1192        let Some(merge_base) = self.merge_base(target, tip_sha) else {
1193            return false;
1194        };
1195        check_history_merged_with_base(self.root, tip_sha, target, &merge_base, started_at)
1196    }
1197
1198    fn is_squash_merged_into_target(&mut self, commit_sha: &str, target: &str) -> bool {
1199        if self.target_is_ancestor_of(target, commit_sha) {
1200            return false;
1201        }
1202        let Some(merge_base) = self.merge_base(target, commit_sha) else {
1203            return false;
1204        };
1205        is_squash_merged_with_base(self.root, commit_sha, target, &merge_base)
1206    }
1207
1208    fn is_cherry_merged_into_target(&mut self, commit_sha: &str, target: &str) -> bool {
1209        let key = (commit_sha.to_string(), self.target_key(target));
1210        if let Some(&cached) = self.cherry_cache.get(&key) {
1211            return cached;
1212        }
1213        let merged = is_cherry_merged_into_target(self.root, commit_sha, target);
1214        self.cherry_cache.insert(key, merged);
1215        merged
1216    }
1217
1218    fn is_merge_tree_merged_into_target(
1219        &mut self,
1220        commit_sha: &str,
1221        target: &str,
1222        target_tree: Option<&str>,
1223    ) -> bool {
1224        let key = (commit_sha.to_string(), self.target_key(target));
1225        if let Some(&cached) = self.merge_tree_cache.get(&key) {
1226            return cached;
1227        }
1228        let resolved_tree = match target_tree {
1229            Some(t) => Some(t.to_string()),
1230            None => self.tree_sha(target),
1231        };
1232        let merged = match resolved_tree.as_deref() {
1233            Some(tree) => {
1234                is_merge_tree_merged_into_target(self.root, commit_sha, target, Some(tree))
1235            }
1236            None => false,
1237        };
1238        self.merge_tree_cache.insert(key, merged);
1239        merged
1240    }
1241
1242    fn merged_into(&mut self, commit_sha: &str, target: &str) -> bool {
1243        if self.is_ancestor_of_target(commit_sha, target) {
1244            return true;
1245        }
1246        if self.is_cherry_merged_into_target(commit_sha, target) {
1247            return true;
1248        }
1249        if self.is_merge_tree_merged_into_target(commit_sha, target, None) {
1250            return true;
1251        }
1252        if self.is_squash_merged_into_target(commit_sha, target) {
1253            return true;
1254        }
1255        false
1256    }
1257
1258    pub fn is_commit_merged_with_targets(
1259        &mut self,
1260        commit_sha: &str,
1261        extra_targets: &[&str],
1262    ) -> bool {
1263        let def = self.default_branch.clone();
1264        if self.merged_into(commit_sha, &def) {
1265            return true;
1266        }
1267        if let Some(origin_def) = self.origin_default.clone() {
1268            if self.merged_into(commit_sha, &origin_def) {
1269                return true;
1270            }
1271        }
1272        for &extra in extra_targets {
1273            if self.ref_exists(extra) && self.merged_into(commit_sha, extra) {
1274                return true;
1275            }
1276        }
1277        false
1278    }
1279
1280    pub fn is_commit_merged(&mut self, commit_sha: &str) -> bool {
1281        self.is_commit_merged_with_targets(commit_sha, &[])
1282    }
1283
1284    pub fn is_branch_merged_with_targets(
1285        &mut self,
1286        branch_name: &str,
1287        extra_targets: &[&str],
1288    ) -> bool {
1289        let Some(tip) = self.get_branch_tip(branch_name) else {
1290            return false;
1291        };
1292        self.is_commit_merged_with_targets(&tip, extra_targets)
1293    }
1294
1295    pub fn is_branch_merged(&mut self, branch_name: &str) -> bool {
1296        if let Some(id) = branch_name.strip_prefix("wip/") {
1297            self.check_run_merged(id).is_some()
1298        } else {
1299            self.is_branch_merged_with_targets(branch_name, &[])
1300        }
1301    }
1302
1303    fn decide_run_merged(
1304        &mut self,
1305        id: &str,
1306        tip_sha: Option<&str>,
1307        visited: &mut HashSet<String>,
1308    ) -> Option<RemovalReason> {
1309        let base_opt = self.start_files.get(id).and_then(|s| {
1310            s.get("base")
1311                .and_then(|b| b.as_str())
1312                .map(|b| b.to_string())
1313        });
1314        let base_targets = base_opt
1315            .as_deref()
1316            .and_then(|b| self.resolve_base_targets(b));
1317        let started_at = self
1318            .start_files
1319            .get(id)
1320            .and_then(|s| s.get("started_at"))
1321            .cloned();
1322
1323        if let Some(tip_sha) = tip_sha {
1324            if self.is_ancestor_of_default(tip_sha) {
1325                return Some(RemovalReason::Merged);
1326            }
1327
1328            if self.is_in_cherry_pick_record(tip_sha) {
1329                return Some(RemovalReason::Merged);
1330            }
1331
1332            if let Some((ref display_name, ref targets)) = base_targets {
1333                for target in targets {
1334                    if self.is_ancestor_of_target(tip_sha, target) {
1335                        return Some(RemovalReason::MergedInto(display_name.clone()));
1336                    }
1337                    if self.is_cherry_merged_into_target(tip_sha, target) {
1338                        return Some(RemovalReason::MergedInto(display_name.clone()));
1339                    }
1340                    if self.is_merge_tree_merged_into_target(tip_sha, target, None) {
1341                        return Some(RemovalReason::MergedInto(display_name.clone()));
1342                    }
1343                }
1344            }
1345        }
1346
1347        let children = self.get_children_of(id, tip_sha.unwrap_or(""));
1348        for child in children {
1349            if visited.contains(&child) {
1350                continue;
1351            }
1352            if self.is_child_run_merged(&child, visited) {
1353                return Some(RemovalReason::MergedThrough(child));
1354            }
1355        }
1356
1357        if let Some(tip_sha) = tip_sha {
1358            let def = self.default_branch.clone();
1359            if self.is_cherry_merged_into_target(tip_sha, &def) {
1360                return Some(RemovalReason::Merged);
1361            }
1362            if let Some(origin_def) = self.origin_default.clone() {
1363                if self.is_cherry_merged_into_target(tip_sha, &origin_def) {
1364                    return Some(RemovalReason::Merged);
1365                }
1366            }
1367
1368            let def_tree = self.default_tree.clone();
1369            if self.is_merge_tree_merged_into_target(tip_sha, &def, def_tree.as_deref()) {
1370                return Some(RemovalReason::Merged);
1371            }
1372            if let Some(origin_def) = self.origin_default.clone() {
1373                let origin_tree = self.origin_default_tree.clone();
1374                if self.is_merge_tree_merged_into_target(
1375                    tip_sha,
1376                    &origin_def,
1377                    origin_tree.as_deref(),
1378                ) {
1379                    return Some(RemovalReason::Merged);
1380                }
1381            }
1382
1383            if self.check_history_merged(tip_sha, &def, started_at.as_ref()) {
1384                return Some(RemovalReason::Merged);
1385            }
1386            if let Some(origin_def) = self.origin_default.clone() {
1387                if self.check_history_merged(tip_sha, &origin_def, started_at.as_ref()) {
1388                    return Some(RemovalReason::Merged);
1389                }
1390            }
1391            if let Some((ref display_name, ref targets)) = base_targets {
1392                for target in targets {
1393                    if self.check_history_merged(tip_sha, target, started_at.as_ref()) {
1394                        return Some(RemovalReason::MergedInto(display_name.clone()));
1395                    }
1396                }
1397            }
1398
1399            if let Some(reason) = self.squash_merged_reason(tip_sha, &base_targets) {
1400                return Some(reason);
1401            }
1402        }
1403
1404        None
1405    }
1406
1407    fn squash_merged_reason(
1408        &mut self,
1409        tip_sha: &str,
1410        base_targets: &Option<(String, Vec<String>)>,
1411    ) -> Option<RemovalReason> {
1412        let def = self.default_branch.clone();
1413        if self.is_squash_merged_into_target(tip_sha, &def) {
1414            return Some(RemovalReason::Merged);
1415        }
1416        if let Some(origin_def) = self.origin_default.clone() {
1417            if self.is_squash_merged_into_target(tip_sha, &origin_def) {
1418                return Some(RemovalReason::Merged);
1419            }
1420        }
1421        if let Some((ref display_name, ref targets)) = base_targets {
1422            for target in targets {
1423                if self.is_squash_merged_into_target(tip_sha, target) {
1424                    return Some(RemovalReason::MergedInto(display_name.clone()));
1425                }
1426            }
1427        }
1428        None
1429    }
1430
1431    pub fn find_merged_followup(&mut self, id: &str) -> Option<String> {
1432        let branch_name = format!("wip/{id}");
1433        let tip_sha = self.get_branch_tip(&branch_name);
1434        let mut visited = HashSet::new();
1435        visited.insert(id.to_string());
1436        let children = self.get_children_of(id, tip_sha.as_deref().unwrap_or(""));
1437        children
1438            .into_iter()
1439            .find(|child| self.is_child_run_merged(child, &mut visited))
1440    }
1441
1442    pub fn check_removable(
1443        &mut self,
1444        id: &str,
1445        older_than_days: u64,
1446    ) -> Result<RemovalReason, KeptReason> {
1447        let wt_dir = self.root.join(".wt");
1448        let summary_path = wt_dir.join(format!("{id}.json"));
1449        let verdict_path = wt_dir.join(format!("{id}.verdict.json"));
1450        let report_path = wt_dir.join(format!("{id}.report.md"));
1451
1452        match read_start_record(self.root, id) {
1453            Err(reason) => return Err(KeptReason::UnreadableStartRecord(reason)),
1454            Ok(Some(value)) => {
1455                self.start_files.insert(id.to_string(), value);
1456            }
1457            Ok(None) => {
1458                self.start_files.remove(id);
1459            }
1460        }
1461        let start_json = self.start_files.get(id);
1462        let summary_exists = summary_path.is_file();
1463
1464        // Check if run is finished: no live process (pid not running) or a summary from this run exists.
1465        if let Some(start) = start_json {
1466            if let Some(pid) = start.get("pid").and_then(|p| p.as_i64()) {
1467                if is_pid_alive(pid) {
1468                    if !summary_exists {
1469                        return Err(KeptReason::Running);
1470                    }
1471                    let Some(started_at) = parse_started_at(start) else {
1472                        return Err(KeptReason::Running);
1473                    };
1474                    let summary_mtime = std::fs::metadata(&summary_path)
1475                        .ok()
1476                        .and_then(|m| m.modified().ok())
1477                        .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
1478                        .map(|d| d.as_secs());
1479                    if summary_mtime.is_none_or(|mtime| mtime < started_at) {
1480                        return Err(KeptReason::Running);
1481                    }
1482                }
1483            }
1484        }
1485
1486        let is_res = self.is_research_run(id);
1487
1488        // Rule 2: Discarded (the verdict is redone, or the outcome is no_changes)
1489        let verdict_str = if verdict_path.is_file() {
1490            std::fs::read_to_string(&verdict_path)
1491                .ok()
1492                .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
1493                .and_then(|v| {
1494                    v.get("verdict")
1495                        .and_then(|s| s.as_str())
1496                        .map(|s| s.to_string())
1497                })
1498                .unwrap_or_default()
1499        } else {
1500            String::new()
1501        };
1502
1503        if verdict_str == "redone" {
1504            return Ok(RemovalReason::Verdict("redone".to_string()));
1505        }
1506
1507        if summary_exists {
1508            if let Ok(summary_str) = std::fs::read_to_string(&summary_path) {
1509                if let Ok(val) = serde_json::from_str::<serde_json::Value>(&summary_str) {
1510                    if val.get("outcome").and_then(|o| o.as_str()) == Some("no_changes") {
1511                        return Ok(RemovalReason::NoChanges);
1512                    }
1513                }
1514            }
1515        }
1516
1517        // Rule 3: Research run and its report was copied out (.wt/<id>.report.md exists)
1518        if is_res && report_path.is_file() {
1519            return Ok(RemovalReason::ResearchReport);
1520        }
1521
1522        if is_res {
1523            let wt_report_path = wt_dir.join(id).join("report.md");
1524            if wt_report_path.is_file() && !report_path.is_file() {
1525                return Ok(RemovalReason::ResearchReportInWorktree);
1526            }
1527            if summary_exists {
1528                let outcome = std::fs::read_to_string(&summary_path)
1529                    .ok()
1530                    .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
1531                    .and_then(|v| {
1532                        v.get("outcome")
1533                            .and_then(|o| o.as_str())
1534                            .filter(|s| !s.is_empty())
1535                            .map(|s| s.to_string())
1536                    });
1537                return match outcome {
1538                    Some(outcome) => Ok(RemovalReason::ResearchEndedWithoutReport(outcome)),
1539                    None => Err(KeptReason::UnreadableSummary),
1540                };
1541            }
1542            let start_path = wt_dir.join(format!("{id}.start.json"));
1543            if let Ok(meta) = std::fs::metadata(&start_path) {
1544                if let Ok(mtime) = meta.modified() {
1545                    let age = std::time::SystemTime::now()
1546                        .duration_since(mtime)
1547                        .unwrap_or(std::time::Duration::ZERO);
1548                    if age >= std::time::Duration::from_secs(older_than_days.saturating_mul(86400))
1549                    {
1550                        return Ok(RemovalReason::ResearchStoppedWithoutSummary(
1551                            older_than_days,
1552                        ));
1553                    }
1554                }
1555            }
1556        }
1557
1558        // Rule 1: Merged (its work is on the default branch or base branch or follow-up)
1559        if !is_res {
1560            if let Some(reason) = self.check_run_merged(id) {
1561                return Ok(reason);
1562            }
1563        }
1564
1565        // Rule 4: Finished more than older_than days ago, by the summary file's mtime
1566        if summary_exists {
1567            if let Ok(meta) = std::fs::metadata(&summary_path) {
1568                if let Ok(mtime) = meta.modified() {
1569                    let age = std::time::SystemTime::now()
1570                        .duration_since(mtime)
1571                        .unwrap_or(std::time::Duration::ZERO);
1572                    if age >= std::time::Duration::from_secs(older_than_days.saturating_mul(86400))
1573                    {
1574                        return Ok(RemovalReason::OlderThan(older_than_days));
1575                    }
1576                }
1577            }
1578        }
1579
1580        // A verdict of accepted or fixed on its own no longer makes a worktree removable
1581        if !verdict_str.is_empty() {
1582            return Err(KeptReason::NotMergedYet);
1583        }
1584
1585        if is_res {
1586            Err(KeptReason::NoReport)
1587        } else {
1588            Err(KeptReason::NoVerdict)
1589        }
1590    }
1591}
1592
1593/// Evaluates whether a worktree is removable according to the clean rules.
1594pub fn check_removable(
1595    root: &Path,
1596    id: &str,
1597    older_than_days: u64,
1598) -> Result<RemovalReason, KeptReason> {
1599    let mut ctx = CleanContext::new(root);
1600    ctx.check_removable(id, older_than_days)
1601}
1602
1603/// Identifies the default branch (origin/HEAD's target, else main, else master).
1604pub fn find_default_branch(root: &Path) -> String {
1605    let sym_out = std::process::Command::new("git")
1606        .args(["symbolic-ref", "--short", "refs/remotes/origin/HEAD"])
1607        .current_dir(root)
1608        .output();
1609    if let Ok(o) = sym_out {
1610        if o.status.success() {
1611            let target = String::from_utf8_lossy(&o.stdout);
1612            let target = target.trim();
1613            let branch_name = target.strip_prefix("origin/").unwrap_or(target);
1614            let local_check = std::process::Command::new("git")
1615                .args([
1616                    "rev-parse",
1617                    "--verify",
1618                    &format!("refs/heads/{branch_name}"),
1619                ])
1620                .current_dir(root)
1621                .output();
1622            if local_check.map(|c| c.status.success()).unwrap_or(false) {
1623                return branch_name.to_string();
1624            }
1625            let remote_check = std::process::Command::new("git")
1626                .args(["rev-parse", "--verify", target])
1627                .current_dir(root)
1628                .output();
1629            if remote_check.map(|c| c.status.success()).unwrap_or(false) {
1630                return target.to_string();
1631            }
1632            return branch_name.to_string();
1633        }
1634    }
1635
1636    let main_check = std::process::Command::new("git")
1637        .args(["rev-parse", "--verify", "refs/heads/main"])
1638        .current_dir(root)
1639        .output();
1640    if main_check.map(|c| c.status.success()).unwrap_or(false) {
1641        return "main".to_string();
1642    }
1643
1644    let master_check = std::process::Command::new("git")
1645        .args(["rev-parse", "--verify", "refs/heads/master"])
1646        .current_dir(root)
1647        .output();
1648    if master_check.map(|c| c.status.success()).unwrap_or(false) {
1649        return "master".to_string();
1650    }
1651
1652    "main".to_string()
1653}
1654
1655/// Determines if a string is a commit SHA (hex-only, length 7 to 64).
1656fn is_commit_id(s: &str) -> bool {
1657    (s.len() >= 7 && s.len() <= 64) && s.chars().all(|c| c.is_ascii_hexdigit())
1658}
1659
1660fn resolve_base_targets_with<F>(base: &str, mut ref_exists: F) -> Option<(String, Vec<String>)>
1661where
1662    F: FnMut(&str) -> bool,
1663{
1664    let base = base.trim();
1665    if base.is_empty() {
1666        return None;
1667    }
1668
1669    if base == "HEAD"
1670        || base.starts_with("HEAD~")
1671        || base.starts_with("HEAD^")
1672        || base.starts_with("HEAD@")
1673        || base.starts_with("HEAD:")
1674    {
1675        return None;
1676    }
1677
1678    if base == "FETCH_HEAD" || base == "ORIG_HEAD" || base == "MERGE_HEAD" {
1679        return None;
1680    }
1681
1682    if is_commit_id(base) {
1683        return None;
1684    }
1685
1686    let clean = if let Some(stripped) = base.strip_prefix("refs/heads/") {
1687        stripped
1688    } else if let Some(stripped) = base.strip_prefix("refs/remotes/") {
1689        stripped
1690    } else {
1691        base
1692    };
1693
1694    let is_wip = clean == "wip"
1695        || clean.starts_with("wip/")
1696        || clean == "origin/wip"
1697        || clean.starts_with("origin/wip/");
1698    if is_wip {
1699        return None;
1700    }
1701
1702    let (display_name, candidates) = if let Some(without_origin) = clean.strip_prefix("origin/") {
1703        if without_origin.is_empty()
1704            || without_origin == "wip"
1705            || without_origin.starts_with("wip/")
1706            || without_origin == "HEAD"
1707            || without_origin.starts_with("HEAD~")
1708            || without_origin.starts_with("HEAD^")
1709            || is_commit_id(without_origin)
1710        {
1711            return None;
1712        }
1713        let cand1 = format!("refs/remotes/{clean}");
1714        let cand2 = format!("refs/heads/{without_origin}");
1715        (without_origin.to_string(), vec![cand1, cand2])
1716    } else {
1717        let cand1 = format!("refs/heads/{clean}");
1718        let cand2 = format!("refs/remotes/origin/{clean}");
1719        (clean.to_string(), vec![cand1, cand2])
1720    };
1721
1722    let mut resolved = Vec::new();
1723    for cand in candidates {
1724        if ref_exists(&cand) {
1725            resolved.push(cand);
1726        }
1727    }
1728
1729    if resolved.is_empty() {
1730        None
1731    } else {
1732        Some((display_name, resolved))
1733    }
1734}
1735
1736/// Resolves candidate git refs for a run's base branch.
1737/// Returns (display_name, targets) if `base` is a branch name that resolves.
1738/// Returns None if `base` is not a branch name (e.g. HEAD, commit id, wip/ branch)
1739/// or if none of the candidate refs resolve in git.
1740pub fn resolve_base_targets(root: &Path, base: &str) -> Option<(String, Vec<String>)> {
1741    resolve_base_targets_with(base, |cand| {
1742        git_ok(root, &["rev-parse", "--verify", "--quiet", cand])
1743    })
1744}
1745
1746/// Reads `base` from `.wt/<id>.start.json` if present.
1747pub fn read_run_base(root: &Path, id: &str) -> Option<String> {
1748    let start_path = root.join(".wt").join(format!("{id}.start.json"));
1749    std::fs::read_to_string(&start_path)
1750        .ok()
1751        .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
1752        .and_then(|v| {
1753            v.get("base")
1754                .and_then(|b| b.as_str())
1755                .map(|s| s.to_string())
1756        })
1757}
1758
1759/// Returns the commit SHA at the tip of `branch_name` if it exists.
1760pub fn get_branch_tip(root: &Path, branch_name: &str) -> Option<String> {
1761    let check = std::process::Command::new("git")
1762        .args([
1763            "rev-parse",
1764            "--verify",
1765            &format!("refs/heads/{branch_name}"),
1766        ])
1767        .current_dir(root)
1768        .output()
1769        .ok()?;
1770    if !check.status.success() {
1771        return None;
1772    }
1773
1774    let tip_out = std::process::Command::new("git")
1775        .args(["rev-parse", &format!("refs/heads/{branch_name}")])
1776        .current_dir(root)
1777        .output()
1778        .ok()?;
1779    if tip_out.status.success() {
1780        Some(String::from_utf8_lossy(&tip_out.stdout).trim().to_string())
1781    } else {
1782        None
1783    }
1784}
1785
1786/// Checks whether a branch's work is on the default branch when any of:
1787/// - `git merge-base --is-ancestor <tip> <default>` succeeds;
1788/// - every commit `git cherry <default> <branch>` lists is marked `-`;
1789/// - merging it would change nothing: `git merge-tree --write-tree <default> <branch>` exits 0
1790///   and the tree id it prints (first line) equals `git rev-parse <default>^{tree}`;
1791/// - 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).
1792pub fn is_branch_merged(root: &Path, branch_name: &str) -> bool {
1793    let mut ctx = CleanContext::new(root);
1794    ctx.is_branch_merged(branch_name)
1795}
1796
1797/// Checks whether a branch's work is on the default branch or any of the extra target refs.
1798pub fn is_branch_merged_with_targets(
1799    root: &Path,
1800    branch_name: &str,
1801    extra_targets: &[&str],
1802) -> bool {
1803    let mut ctx = CleanContext::new(root);
1804    ctx.is_branch_merged_with_targets(branch_name, extra_targets)
1805}
1806
1807/// Checks whether a branch's work is on the default branch or any of the extra target refs.
1808pub fn is_branch_merged_with_extra_targets(
1809    root: &Path,
1810    branch_name: &str,
1811    extra_targets: &[&str],
1812) -> bool {
1813    is_branch_merged_with_targets(root, branch_name, extra_targets)
1814}
1815
1816/// Checks whether a commit's work is on the default branch when any of:
1817/// - `git merge-base --is-ancestor <commit> <default>` succeeds;
1818/// - every commit `git cherry <default> <commit>` lists is marked `-`;
1819/// - merging it would change nothing: `git merge-tree --write-tree <default> <commit>` exits 0
1820///   and the tree id it prints equals `git rev-parse <default>^{tree}`.
1821pub fn is_commit_merged(root: &Path, commit_sha: &str) -> bool {
1822    let mut ctx = CleanContext::new(root);
1823    ctx.is_commit_merged(commit_sha)
1824}
1825
1826/// Checks whether a commit's work is on the default branch or any of the extra target refs.
1827pub fn is_commit_merged_with_targets(
1828    root: &Path,
1829    commit_sha: &str,
1830    extra_targets: &[&str],
1831) -> bool {
1832    let mut ctx = CleanContext::new(root);
1833    ctx.is_commit_merged_with_targets(commit_sha, extra_targets)
1834}
1835
1836fn git_ok(root: &Path, args: &[&str]) -> bool {
1837    std::process::Command::new("git")
1838        .args(args)
1839        .current_dir(root)
1840        .output()
1841        .map(|o| o.status.success())
1842        .unwrap_or(false)
1843}
1844
1845fn is_squash_merged_with_base(root: &Path, commit_sha: &str, target: &str, base: &str) -> bool {
1846    let subj_out = std::process::Command::new("git")
1847        .args([
1848            "log",
1849            "--no-merges",
1850            "--format=%s",
1851            &format!("{target}..{commit_sha}"),
1852        ])
1853        .current_dir(root)
1854        .output();
1855    let Ok(subj_o) = subj_out else {
1856        return false;
1857    };
1858    if !subj_o.status.success() {
1859        return false;
1860    }
1861    let subj_stdout = String::from_utf8_lossy(&subj_o.stdout);
1862    let subjects: Vec<&str> = subj_stdout
1863        .lines()
1864        .map(|l| l.trim())
1865        .filter(|l| !l.is_empty())
1866        .collect();
1867    if subjects.is_empty() {
1868        return false;
1869    }
1870
1871    let hay_out = std::process::Command::new("git")
1872        .args(["log", "--format=%B", &format!("{base}..{target}")])
1873        .current_dir(root)
1874        .output();
1875    let Ok(hay_o) = hay_out else {
1876        return false;
1877    };
1878    if !hay_o.status.success() {
1879        return false;
1880    }
1881    let hay_stdout = String::from_utf8_lossy(&hay_o.stdout);
1882    let mut haystack_lines = HashSet::new();
1883    for line in hay_stdout.lines() {
1884        let trimmed = line.trim();
1885        if trimmed.is_empty() {
1886            continue;
1887        }
1888        haystack_lines.insert(trimmed.to_string());
1889        if let Some(stripped) = trimmed
1890            .strip_prefix("* ")
1891            .or_else(|| trimmed.strip_prefix("- "))
1892        {
1893            let stripped = stripped.trim();
1894            if !stripped.is_empty() {
1895                haystack_lines.insert(stripped.to_string());
1896            }
1897        }
1898    }
1899
1900    subjects.iter().all(|s| haystack_lines.contains(*s))
1901}
1902
1903/// Lists all run IDs that have a corresponding `.wt/<id>.start.json`.
1904pub fn list_all_run_ids(root: &Path) -> Vec<String> {
1905    let wt_dir = root.join(".wt");
1906    let mut ids = Vec::new();
1907    if let Ok(entries) = std::fs::read_dir(&wt_dir) {
1908        for entry in entries.flatten() {
1909            let name = entry.file_name().to_string_lossy().to_string();
1910            if let Some(id) = name.strip_suffix(".start.json") {
1911                ids.push(id.to_string());
1912            }
1913        }
1914    }
1915    ids.sort();
1916    ids
1917}
1918
1919/// Finds a follow-up run that makes `<id>` merged.
1920pub fn find_merged_followup(root: &Path, id: &str) -> Option<String> {
1921    let mut ctx = CleanContext::new(root);
1922    ctx.find_merged_followup(id)
1923}
1924
1925/// Lists all `.wt/<id>` directories that have a corresponding `.wt/<id>.start.json`.
1926pub fn find_blyte_worktrees(root: &Path) -> Vec<String> {
1927    let wt_dir = root.join(".wt");
1928    if !wt_dir.is_dir() {
1929        return Vec::new();
1930    }
1931    let mut ids = Vec::new();
1932    if let Ok(entries) = std::fs::read_dir(&wt_dir) {
1933        for entry in entries.flatten() {
1934            if let Ok(ft) = entry.file_type() {
1935                if ft.is_dir() {
1936                    let name = entry.file_name().to_string_lossy().to_string();
1937                    let start_file = wt_dir.join(format!("{name}.start.json"));
1938                    if start_file.is_file() {
1939                        ids.push(name);
1940                    }
1941                }
1942            }
1943        }
1944    }
1945    ids.sort();
1946    ids
1947}
1948
1949#[derive(Debug, Default)]
1950pub struct CleanRepoStats {
1951    pub removed_worktrees: usize,
1952    pub freed_bytes: u64,
1953    pub had_errors: bool,
1954}
1955
1956/// Default idle threshold in days for session worktrees.
1957pub const DEFAULT_SESSION_IDLE_DAYS: u64 = 7;
1958
1959/// Parses `lsof -a -d cwd -Fn` output into a list of working directory paths.
1960pub fn parse_lsof_cwd_output(stdout: &str) -> Vec<PathBuf> {
1961    stdout
1962        .lines()
1963        .filter_map(|line| line.strip_prefix('n'))
1964        .filter(|path| !path.is_empty())
1965        .map(PathBuf::from)
1966        .collect()
1967}
1968
1969/// Lists the current working directories of all running processes via `lsof -a -d cwd -Fn`.
1970pub fn list_running_process_cwds() -> Result<Vec<PathBuf>, String> {
1971    let out = std::process::Command::new("lsof")
1972        .args(["-a", "-d", "cwd", "-Fn"])
1973        .output()
1974        .map_err(|e| e.to_string())?;
1975    // A failed lsof may have listed only some processes, so its output is not trusted.
1976    if !out.status.success() {
1977        let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string();
1978        if stderr.is_empty() {
1979            return Err(format!("lsof exited with {}", out.status));
1980        }
1981        return Err(format!("lsof exited with {}: {stderr}", out.status));
1982    }
1983    let paths = parse_lsof_cwd_output(&String::from_utf8_lossy(&out.stdout));
1984    if paths.is_empty() {
1985        return Err("lsof listed no working directories".to_string());
1986    }
1987    Ok(paths)
1988}
1989
1990/// Returns true if `wt_path` is a session worktree of `root`:
1991/// - directly under `<root>/.wt/` with no `<root>/.wt/<name>.start.json`, or
1992/// - under `<root>/.claude/worktrees/` (excluding any nested `.wt` run worktrees).
1993pub fn is_session_worktree(root: &Path, wt_path: &Path) -> bool {
1994    let root_canon = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
1995    let wt_canon = wt_path
1996        .canonicalize()
1997        .unwrap_or_else(|_| wt_path.to_path_buf());
1998    let Some(wt_parent) = wt_canon.parent() else {
1999        return false;
2000    };
2001    let Some(wt_name) = wt_canon.file_name().and_then(|n| n.to_str()) else {
2002        return false;
2003    };
2004
2005    let wt_dir_canon = root_canon
2006        .join(".wt")
2007        .canonicalize()
2008        .unwrap_or_else(|_| root_canon.join(".wt"));
2009    if wt_parent == wt_dir_canon {
2010        let start_file = wt_dir_canon.join(format!("{wt_name}.start.json"));
2011        return !start_file.is_file();
2012    }
2013
2014    let claude_wt_dir_canon = root_canon
2015        .join(".claude")
2016        .join("worktrees")
2017        .canonicalize()
2018        .unwrap_or_else(|_| root_canon.join(".claude").join("worktrees"));
2019    if let Ok(rel) = wt_canon.strip_prefix(&claude_wt_dir_canon) {
2020        if !rel.as_os_str().is_empty() && !has_wt_component(rel) {
2021            return true;
2022        }
2023    }
2024
2025    false
2026}
2027
2028/// Returns true if `<wt_path>/.wt/` contains any `*.start.json` file.
2029pub fn has_dispatched_runs(wt_path: &Path) -> bool {
2030    let wt_dir = wt_path.join(".wt");
2031    let Ok(entries) = std::fs::read_dir(&wt_dir) else {
2032        return false;
2033    };
2034    for entry in entries.flatten() {
2035        let name = entry.file_name();
2036        if name.to_string_lossy().ends_with(".start.json")
2037            && entry.file_type().map(|ft| ft.is_file()).unwrap_or(false)
2038        {
2039            return true;
2040        }
2041    }
2042    false
2043}
2044
2045/// Returns true if any process working directory in `cwds` is `wt_path` or a subdirectory of it.
2046/// Compares canonical paths.
2047pub fn is_worktree_in_use(wt_path: &Path, cwds: &[PathBuf]) -> bool {
2048    let wt_canon = wt_path
2049        .canonicalize()
2050        .unwrap_or_else(|_| wt_path.to_path_buf());
2051    cwds.iter().any(|cwd| {
2052        let cwd_canon = cwd.canonicalize().unwrap_or_else(|_| cwd.clone());
2053        cwd_canon.starts_with(&wt_canon)
2054    })
2055}
2056
2057/// Returns whether `index` and `HEAD` in the worktree's git admin directory
2058/// (`git -C <wt> rev-parse --absolute-git-dir`) are both more than `idle_days` days old.
2059/// Errors name what could not be read.
2060pub fn is_worktree_idle(wt_path: &Path, idle_days: u64) -> Result<bool, String> {
2061    let o = std::process::Command::new("git")
2062        .arg("-C")
2063        .arg(wt_path.as_os_str())
2064        .args(["rev-parse", "--absolute-git-dir"])
2065        .output()
2066        .map_err(|e| format!("cannot run git: {e}"))?;
2067    if !o.status.success() {
2068        return Err(format!(
2069            "git rev-parse --absolute-git-dir failed: {}",
2070            String::from_utf8_lossy(&o.stderr).trim()
2071        ));
2072    }
2073    let git_dir_str = String::from_utf8_lossy(&o.stdout).trim().to_string();
2074    if git_dir_str.is_empty() {
2075        return Err("git rev-parse --absolute-git-dir printed nothing".to_string());
2076    }
2077    let git_dir = PathBuf::from(git_dir_str);
2078    let now = std::time::SystemTime::now();
2079    let threshold = std::time::Duration::from_secs(idle_days.saturating_mul(86400));
2080    for name in ["index", "HEAD"] {
2081        let p = git_dir.join(name);
2082        let mtime = std::fs::metadata(&p)
2083            .and_then(|m| m.modified())
2084            .map_err(|e| format!("cannot read the time of {}: {e}", p.display()))?;
2085        let age = now
2086            .duration_since(mtime)
2087            .unwrap_or(std::time::Duration::ZERO);
2088        if idle_days > 0 && age <= threshold {
2089            return Ok(false);
2090        }
2091    }
2092    Ok(true)
2093}
2094
2095fn check_session_worktree_removable_with_ctx(
2096    ctx: &mut CleanContext<'_>,
2097    wt: &GitWorktreeInfo,
2098    cwds: &Result<Vec<PathBuf>, String>,
2099    idle_days: u64,
2100) -> Result<RemovalReason, KeptReason> {
2101    let is_merged = if let Some(ref branch) = wt.branch {
2102        ctx.is_branch_merged(branch)
2103    } else if let Some(ref sha) = wt.head_sha {
2104        ctx.is_commit_merged(sha)
2105    } else {
2106        false
2107    };
2108    if !is_merged {
2109        return Err(KeptReason::NotMergedYet);
2110    }
2111
2112    if has_dispatched_runs(&wt.path) {
2113        let display_path = display_worktree_path(&wt.path, ctx.root);
2114        return Err(KeptReason::HoldsRuns(display_path));
2115    }
2116
2117    if !is_worktree_clean(&wt.path) {
2118        return Err(KeptReason::UncommittedChanges);
2119    }
2120
2121    match cwds {
2122        Ok(list) => {
2123            if is_worktree_in_use(&wt.path, list) {
2124                return Err(KeptReason::InUse);
2125            }
2126        }
2127        Err(err) => {
2128            return Err(KeptReason::CannotCheckInUse(err.clone()));
2129        }
2130    }
2131
2132    match is_worktree_idle(&wt.path, idle_days) {
2133        Ok(true) => {}
2134        Ok(false) => return Err(KeptReason::UsedRecently(idle_days)),
2135        Err(e) => {
2136            return Err(KeptReason::Custom(format!(
2137                "cannot tell when it was last used: {e}"
2138            )))
2139        }
2140    }
2141
2142    let branch_label = wt.branch.clone().unwrap_or_else(|| {
2143        wt.head_sha
2144            .as_deref()
2145            .map(|s| s[..s.len().min(7)].to_string())
2146            .unwrap_or_else(|| "detached".to_string())
2147    });
2148    Ok(RemovalReason::SessionMerged(branch_label))
2149}
2150
2151/// Evaluates whether a session worktree is removable.
2152pub fn check_session_worktree_removable(
2153    root: &Path,
2154    wt: &GitWorktreeInfo,
2155    cwds: &Result<Vec<PathBuf>, String>,
2156    idle_days: u64,
2157) -> Result<RemovalReason, KeptReason> {
2158    let mut ctx = CleanContext::new(root);
2159    check_session_worktree_removable_with_ctx(&mut ctx, wt, cwds, idle_days)
2160}
2161
2162fn branch_checked_out_elsewhere(
2163    worktrees: &[GitWorktreeInfo],
2164    removed_wt_paths: &HashSet<PathBuf>,
2165    current_wt_canon: &Path,
2166    branch_name: &str,
2167) -> bool {
2168    for wt in worktrees {
2169        if !wt.path.exists() {
2170            continue;
2171        }
2172        let wt_canon = wt
2173            .path
2174            .canonicalize()
2175            .unwrap_or_else(|_| wt.path.to_path_buf());
2176        if wt_canon == current_wt_canon || removed_wt_paths.contains(&wt_canon) {
2177            continue;
2178        }
2179        if wt.branch.as_deref() == Some(branch_name) {
2180            return true;
2181        }
2182    }
2183    false
2184}
2185
2186/// Cleans one repository.
2187pub fn clean_repo(
2188    root: &Path,
2189    older_than_days: u64,
2190    dry_run: bool,
2191    skip_id: Option<&str>,
2192    quiet: bool,
2193) -> CleanRepoStats {
2194    clean_repo_with_options(
2195        root,
2196        older_than_days,
2197        dry_run,
2198        skip_id,
2199        quiet,
2200        DEFAULT_SESSION_IDLE_DAYS,
2201        None,
2202    )
2203}
2204
2205/// Cleans one repository with configurable session worktree idle threshold and process cwd list.
2206pub fn clean_repo_with_options(
2207    root: &Path,
2208    older_than_days: u64,
2209    dry_run: bool,
2210    skip_id: Option<&str>,
2211    quiet: bool,
2212    session_idle_days: u64,
2213    process_cwds: Option<Result<Vec<PathBuf>, String>>,
2214) -> CleanRepoStats {
2215    let mut removed_worktrees = 0;
2216    let mut freed_bytes = 0;
2217    let mut had_errors = false;
2218    let mut needs_worktree_prune = false;
2219
2220    let mut ctx = CleanContext::new(root);
2221    let is_linked = is_linked_worktree(root);
2222    let all_worktrees = if !is_linked {
2223        parse_worktree_list(root)
2224    } else {
2225        Vec::new()
2226    };
2227
2228    let ids = find_blyte_worktrees(root);
2229    for id in ids {
2230        if skip_id == Some(&id) {
2231            continue;
2232        }
2233
2234        let wt_path = root.join(".wt").join(&id);
2235        match ctx.check_removable(&id, older_than_days) {
2236            Err(kept_reason) => {
2237                if !quiet {
2238                    println!("kept .wt/{id} ({kept_reason})");
2239                }
2240            }
2241            Ok(removal_reason) => {
2242                let is_res = ctx.is_research_run(&id);
2243                if !is_res && has_uncommitted_changes(&wt_path) {
2244                    if !quiet {
2245                        println!("kept .wt/{id} (uncommitted changes)");
2246                    }
2247                    continue;
2248                }
2249
2250                let size = dir_size(&wt_path);
2251                let branch_name = format!("wip/{id}");
2252                let branch_exists = ctx.get_branch_tip(&branch_name).is_some();
2253                let is_merged = branch_exists
2254                    && (matches!(
2255                        removal_reason,
2256                        RemovalReason::Merged
2257                            | RemovalReason::MergedInto(_)
2258                            | RemovalReason::MergedThrough(_)
2259                    ) || ctx.check_run_merged(&id).is_some());
2260
2261                if dry_run {
2262                    if !quiet {
2263                        println!(
2264                            "would remove .wt/{id} ({removal_reason}, {})",
2265                            format_size(size)
2266                        );
2267                        if is_merged {
2268                            println!("would delete branch {branch_name} (merged)");
2269                        }
2270                    }
2271                    freed_bytes += size;
2272                    removed_worktrees += 1;
2273                } else {
2274                    if removal_reason == RemovalReason::ResearchReportInWorktree {
2275                        let src = wt_path.join("report.md");
2276                        let dst = root.join(".wt").join(format!("{id}.report.md"));
2277                        if let Err(err) = std::fs::copy(&src, &dst) {
2278                            eprintln!(
2279                                "error: could not copy {} to {}: {err}",
2280                                src.display(),
2281                                dst.display()
2282                            );
2283                            if !quiet {
2284                                println!("kept .wt/{id} (report copy failed)");
2285                            }
2286                            continue;
2287                        }
2288                    }
2289
2290                    if let Err(reason) = ctx.check_removable(&id, older_than_days) {
2291                        if !quiet {
2292                            println!("kept .wt/{id} ({reason})");
2293                        }
2294                        continue;
2295                    }
2296
2297                    let removed_ok = if is_res {
2298                        std::fs::remove_dir_all(&wt_path).is_ok()
2299                    } else {
2300                        let rm_out = std::process::Command::new("git")
2301                            .args(["worktree", "remove", wt_path.to_str().unwrap_or("")])
2302                            .current_dir(root)
2303                            .output();
2304                        needs_worktree_prune = true;
2305                        rm_out.map(|o| o.status.success()).unwrap_or(false)
2306                    };
2307
2308                    if removed_ok {
2309                        freed_bytes += size;
2310                        removed_worktrees += 1;
2311                        if !quiet {
2312                            println!("removed .wt/{id} ({removal_reason}, {})", format_size(size));
2313                        }
2314                        if is_merged {
2315                            let del_out = std::process::Command::new("git")
2316                                .args(["branch", "-D", &branch_name])
2317                                .current_dir(root)
2318                                .output();
2319                            if del_out.map(|o| o.status.success()).unwrap_or(false) {
2320                                ctx.remove_branch(&branch_name);
2321                                if !quiet {
2322                                    println!("deleted branch {branch_name} (merged)");
2323                                }
2324                            }
2325                        }
2326                    } else if !quiet {
2327                        println!("kept .wt/{id} (worktree remove failed)");
2328                    }
2329                }
2330            }
2331        }
2332    }
2333
2334    if !is_linked {
2335        let root_canon = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
2336        let main_canon = all_worktrees
2337            .first()
2338            .map(|wt| wt.path.canonicalize().unwrap_or_else(|_| wt.path.clone()));
2339
2340        let mut session_indices: Vec<(String, usize)> = all_worktrees
2341            .iter()
2342            .enumerate()
2343            .skip(1)
2344            .filter_map(|(idx, wt)| {
2345                if wt.is_bare || !wt.path.exists() {
2346                    return None;
2347                }
2348                let wt_canon = wt.path.canonicalize().unwrap_or_else(|_| wt.path.clone());
2349                if wt_canon == root_canon || Some(&wt_canon) == main_canon.as_ref() {
2350                    return None;
2351                }
2352                if !is_session_worktree(root, &wt.path) {
2353                    return None;
2354                }
2355                Some((display_worktree_path(&wt.path, root), idx))
2356            })
2357            .collect();
2358        session_indices.sort_by(|a, b| a.0.cmp(&b.0));
2359
2360        if !session_indices.is_empty() {
2361            let cwds = process_cwds.unwrap_or_else(list_running_process_cwds);
2362            let mut removed_wt_paths = HashSet::new();
2363
2364            for (display_path, idx) in session_indices {
2365                let wt = &all_worktrees[idx];
2366                let wt_canon = wt.path.canonicalize().unwrap_or_else(|_| wt.path.clone());
2367                match check_session_worktree_removable_with_ctx(
2368                    &mut ctx,
2369                    wt,
2370                    &cwds,
2371                    session_idle_days,
2372                ) {
2373                    Err(kept_reason) => {
2374                        if !quiet {
2375                            println!("kept {display_path} ({kept_reason})");
2376                        }
2377                    }
2378                    Ok(removal_reason) => {
2379                        let size = dir_size(&wt.path);
2380                        if dry_run {
2381                            removed_wt_paths.insert(wt_canon.clone());
2382                            if !quiet {
2383                                println!(
2384                                    "would remove {display_path} ({removal_reason}, {})",
2385                                    format_size(size)
2386                                );
2387                                if let Some(ref branch_name) = wt.branch {
2388                                    if !branch_checked_out_elsewhere(
2389                                        &all_worktrees,
2390                                        &removed_wt_paths,
2391                                        &wt_canon,
2392                                        branch_name,
2393                                    ) && ctx.get_branch_tip(branch_name).is_some()
2394                                    {
2395                                        println!("would delete branch {branch_name} (merged)");
2396                                    }
2397                                }
2398                            }
2399                            freed_bytes += size;
2400                            removed_worktrees += 1;
2401                        } else {
2402                            let rm_out = std::process::Command::new("git")
2403                                .arg("worktree")
2404                                .arg("remove")
2405                                .arg(&wt.path)
2406                                .current_dir(root)
2407                                .output();
2408                            match rm_out {
2409                                Ok(o) if o.status.success() => {
2410                                    needs_worktree_prune = true;
2411                                    removed_wt_paths.insert(wt_canon.clone());
2412                                    freed_bytes += size;
2413                                    removed_worktrees += 1;
2414                                    if !quiet {
2415                                        println!(
2416                                            "removed {display_path} ({removal_reason}, {})",
2417                                            format_size(size)
2418                                        );
2419                                    }
2420                                    if let Some(ref branch_name) = wt.branch {
2421                                        if !branch_checked_out_elsewhere(
2422                                            &all_worktrees,
2423                                            &removed_wt_paths,
2424                                            &wt_canon,
2425                                            branch_name,
2426                                        ) && ctx.get_branch_tip(branch_name).is_some()
2427                                        {
2428                                            let del_out = std::process::Command::new("git")
2429                                                .args(["branch", "-D", branch_name])
2430                                                .current_dir(root)
2431                                                .output();
2432                                            match del_out {
2433                                                Ok(o) if o.status.success() => {
2434                                                    ctx.remove_branch(branch_name);
2435                                                    if !quiet {
2436                                                        println!(
2437                                                            "deleted branch {branch_name} (merged)"
2438                                                        );
2439                                                    }
2440                                                }
2441                                                Ok(o) => {
2442                                                    eprintln!(
2443                                                        "error: could not delete branch {branch_name}: {}",
2444                                                        String::from_utf8_lossy(&o.stderr).trim()
2445                                                    );
2446                                                    had_errors = true;
2447                                                }
2448                                                Err(e) => {
2449                                                    eprintln!(
2450                                                        "error: could not delete branch {branch_name}: {e}"
2451                                                    );
2452                                                    had_errors = true;
2453                                                }
2454                                            }
2455                                        }
2456                                    }
2457                                }
2458                                Ok(o) => {
2459                                    let stderr =
2460                                        String::from_utf8_lossy(&o.stderr).trim().to_string();
2461                                    let stdout =
2462                                        String::from_utf8_lossy(&o.stdout).trim().to_string();
2463                                    let msg = if !stderr.is_empty() {
2464                                        stderr
2465                                    } else if !stdout.is_empty() {
2466                                        stdout
2467                                    } else {
2468                                        format!("exit status {}", o.status)
2469                                    };
2470                                    eprintln!("error: could not remove {display_path}: {msg}");
2471                                    had_errors = true;
2472                                }
2473                                Err(e) => {
2474                                    eprintln!("error: could not remove {display_path}: {e}");
2475                                    had_errors = true;
2476                                }
2477                            }
2478                        }
2479                    }
2480                }
2481            }
2482        }
2483    }
2484
2485    if needs_worktree_prune {
2486        let _ = std::process::Command::new("git")
2487            .args(["worktree", "prune"])
2488            .current_dir(root)
2489            .output();
2490    }
2491
2492    if !quiet && !is_linked {
2493        report_other_worktrees_with_ctx(root, &mut ctx, &all_worktrees);
2494    }
2495
2496    CleanRepoStats {
2497        removed_worktrees,
2498        freed_bytes,
2499        had_errors,
2500    }
2501}
2502
2503#[derive(Debug)]
2504pub struct GitWorktreeInfo {
2505    pub path: PathBuf,
2506    pub head_sha: Option<String>,
2507    pub branch: Option<String>,
2508    pub is_detached: bool,
2509    pub is_bare: bool,
2510}
2511
2512/// Parses git worktrees from `git worktree list --porcelain`.
2513pub fn parse_worktree_list(root: &Path) -> Vec<GitWorktreeInfo> {
2514    let out = std::process::Command::new("git")
2515        .args(["worktree", "list", "--porcelain"])
2516        .current_dir(root)
2517        .output();
2518    let Ok(o) = out else {
2519        return Vec::new();
2520    };
2521    if !o.status.success() {
2522        return Vec::new();
2523    }
2524    let text = String::from_utf8_lossy(&o.stdout);
2525
2526    let mut list = Vec::new();
2527    let mut cur_path: Option<PathBuf> = None;
2528    let mut cur_head: Option<String> = None;
2529    let mut cur_branch: Option<String> = None;
2530    let mut cur_detached = false;
2531    let mut cur_bare = false;
2532
2533    let mut finish_entry = |path: &mut Option<PathBuf>,
2534                            head: &mut Option<String>,
2535                            branch: &mut Option<String>,
2536                            detached: &mut bool,
2537                            bare: &mut bool| {
2538        if let Some(p) = path.take() {
2539            list.push(GitWorktreeInfo {
2540                path: p,
2541                head_sha: head.take(),
2542                branch: branch.take(),
2543                is_detached: *detached,
2544                is_bare: *bare,
2545            });
2546            *detached = false;
2547            *bare = false;
2548        }
2549    };
2550
2551    for line in text.lines() {
2552        let line = line.trim();
2553        if line.is_empty() {
2554            finish_entry(
2555                &mut cur_path,
2556                &mut cur_head,
2557                &mut cur_branch,
2558                &mut cur_detached,
2559                &mut cur_bare,
2560            );
2561        } else if let Some(p) = line.strip_prefix("worktree ") {
2562            finish_entry(
2563                &mut cur_path,
2564                &mut cur_head,
2565                &mut cur_branch,
2566                &mut cur_detached,
2567                &mut cur_bare,
2568            );
2569            cur_path = Some(PathBuf::from(p.trim()));
2570        } else if let Some(h) = line.strip_prefix("HEAD ") {
2571            cur_head = Some(h.trim().to_string());
2572        } else if let Some(b) = line.strip_prefix("branch ") {
2573            let b_str = b.trim();
2574            let b_name = b_str.strip_prefix("refs/heads/").unwrap_or(b_str);
2575            cur_branch = Some(b_name.to_string());
2576        } else if line == "detached" {
2577            cur_detached = true;
2578        } else if line == "bare" {
2579            cur_bare = true;
2580        }
2581    }
2582    finish_entry(
2583        &mut cur_path,
2584        &mut cur_head,
2585        &mut cur_branch,
2586        &mut cur_detached,
2587        &mut cur_bare,
2588    );
2589    list
2590}
2591
2592/// Formats a worktree path for display and for git CLI commands:
2593/// relative to `root` if inside `root` or a sibling (same parent directory);
2594/// otherwise absolute.
2595pub fn display_worktree_path(target: &Path, root: &Path) -> String {
2596    let target_canon = target
2597        .canonicalize()
2598        .unwrap_or_else(|_| target.to_path_buf());
2599    let root_canon = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
2600
2601    // Inside the repository root
2602    if let Ok(rel) = target_canon.strip_prefix(&root_canon) {
2603        if !rel.as_os_str().is_empty() {
2604            return rel.to_string_lossy().replace('\\', "/");
2605        }
2606    }
2607
2608    // Sibling (same parent directory, e.g. ../app--side)
2609    if target_canon != root_canon {
2610        if let (Some(root_parent), Some(target_parent)) =
2611            (root_canon.parent(), target_canon.parent())
2612        {
2613            if root_parent == target_parent {
2614                if let Some(file_name) = target_canon.file_name() {
2615                    let rel = Path::new("..").join(file_name);
2616                    return rel.to_string_lossy().replace('\\', "/");
2617                }
2618            }
2619        }
2620    }
2621
2622    // Otherwise show the absolute path
2623    target_canon.to_string_lossy().replace('\\', "/")
2624}
2625
2626/// Returns true if `root` is a linked worktree (its git-dir differs from its git-common-dir).
2627pub fn is_linked_worktree(root: &Path) -> bool {
2628    let out = std::process::Command::new("git")
2629        .args([
2630            "rev-parse",
2631            "--path-format=absolute",
2632            "--git-dir",
2633            "--git-common-dir",
2634        ])
2635        .current_dir(root)
2636        .output();
2637    match out {
2638        Ok(o) if o.status.success() => {
2639            let text = String::from_utf8_lossy(&o.stdout);
2640            let mut lines = text.lines();
2641            let (Some(gd_str), Some(cd_str)) = (lines.next(), lines.next()) else {
2642                return false;
2643            };
2644            let gd_str = gd_str.trim();
2645            let cd_str = cd_str.trim();
2646            if gd_str == cd_str {
2647                return false;
2648            }
2649            let gd_path = PathBuf::from(gd_str);
2650            let cd_path = PathBuf::from(cd_str);
2651            let gd_canon = gd_path.canonicalize().unwrap_or(gd_path);
2652            let cd_canon = cd_path.canonicalize().unwrap_or(cd_path);
2653            gd_canon != cd_canon
2654        }
2655        _ => false,
2656    }
2657}
2658
2659/// Returns true if any path component is `.wt`.
2660pub fn has_wt_component(path: &Path) -> bool {
2661    path.components().any(|c| c.as_os_str() == ".wt")
2662}
2663
2664/// Checks whether a worktree's working tree is clean:
2665/// `git status --porcelain` lists nothing other than `.DS_Store` files, at any depth.
2666pub fn is_worktree_clean(wt_path: &Path) -> bool {
2667    let out = std::process::Command::new("git")
2668        .arg("--no-optional-locks")
2669        .arg("-C")
2670        .arg(wt_path.as_os_str())
2671        .args(["status", "--porcelain", "-u"])
2672        .output();
2673    match out {
2674        Ok(o) if o.status.success() => {
2675            let stdout = String::from_utf8_lossy(&o.stdout);
2676            for line in stdout.lines() {
2677                let trimmed = line.trim();
2678                if trimmed.is_empty() {
2679                    continue;
2680                }
2681                if line.len() < 3 {
2682                    return false;
2683                }
2684                let mut path_part = line[3..].trim();
2685                if let Some((_, new_path)) = path_part.split_once(" -> ") {
2686                    path_part = new_path.trim();
2687                }
2688                let unquoted = path_part
2689                    .strip_prefix('"')
2690                    .and_then(|p| p.strip_suffix('"'))
2691                    .unwrap_or(path_part);
2692                if Path::new(unquoted).file_name() != Some(std::ffi::OsStr::new(".DS_Store")) {
2693                    return false;
2694                }
2695            }
2696            true
2697        }
2698        _ => false,
2699    }
2700}
2701
2702fn report_other_worktrees_with_ctx(
2703    root: &Path,
2704    ctx: &mut CleanContext<'_>,
2705    worktrees: &[GitWorktreeInfo],
2706) {
2707    let root_canon = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
2708    let main_canon = worktrees
2709        .first()
2710        .map(|wt| wt.path.canonicalize().unwrap_or_else(|_| wt.path.clone()));
2711
2712    let mut other_count = 0;
2713    let mut other_bytes = 0;
2714
2715    for (idx, wt) in worktrees.iter().enumerate() {
2716        if idx == 0 {
2717            continue;
2718        }
2719        if wt.is_bare {
2720            continue;
2721        }
2722        if !wt.path.exists() {
2723            continue;
2724        }
2725
2726        let wt_canon = wt.path.canonicalize().unwrap_or_else(|_| wt.path.clone());
2727        if wt_canon == root_canon || wt.path == root {
2728            continue;
2729        }
2730        if Some(&wt_canon) == main_canon.as_ref() {
2731            continue;
2732        }
2733        if has_wt_component(&wt.path)
2734            || has_wt_component(&wt_canon)
2735            || is_session_worktree(root, &wt.path)
2736        {
2737            continue;
2738        }
2739
2740        let is_merged = if let Some(ref branch) = wt.branch {
2741            ctx.is_branch_merged(branch)
2742        } else if let Some(ref sha) = wt.head_sha {
2743            ctx.is_commit_merged(sha)
2744        } else {
2745            false
2746        };
2747
2748        if !is_merged {
2749            continue;
2750        }
2751
2752        if !is_worktree_clean(&wt.path) {
2753            continue;
2754        }
2755
2756        let size = dir_size(&wt.path);
2757        let path_str = display_worktree_path(&wt.path, root);
2758        let branch_label = wt.branch.as_deref().unwrap_or_else(|| {
2759            wt.head_sha
2760                .as_deref()
2761                .map(|s| &s[..s.len().min(7)])
2762                .unwrap_or("detached")
2763        });
2764
2765        println!(
2766            "merged worktree {path_str} ({branch_label}, {}): git worktree remove {path_str}",
2767            format_size(size)
2768        );
2769
2770        other_count += 1;
2771        other_bytes += size;
2772    }
2773
2774    if other_count > 0 {
2775        println!(
2776            "{other_count} other worktrees are merged and clean ({}); remove them with the commands above",
2777            format_size(other_bytes)
2778        );
2779    }
2780}
2781
2782/// Inspects other worktrees (excluding main checkout, linked-worktree roots,
2783/// and blyte's `.wt/<id>` runs), and reports any that are both merged and clean.
2784/// Never deletes them.
2785pub fn report_other_worktrees(root: &Path) {
2786    if is_linked_worktree(root) {
2787        return;
2788    }
2789    let worktrees = parse_worktree_list(root);
2790    let mut ctx = CleanContext::new(root);
2791    report_other_worktrees_with_ctx(root, &mut ctx, &worktrees);
2792}
2793
2794struct CleanLockGuard(PathBuf);
2795
2796impl Drop for CleanLockGuard {
2797    fn drop(&mut self) {
2798        let _ = std::fs::remove_file(&self.0);
2799    }
2800}
2801
2802enum LockOutcome {
2803    Acquired(CleanLockGuard),
2804    AlreadyRunning,
2805    Error(String),
2806}
2807
2808fn acquire_clean_lock(root: &Path) -> LockOutcome {
2809    use std::io::Write;
2810    let wt_dir = root.join(".wt");
2811    if let Err(e) = std::fs::create_dir_all(&wt_dir) {
2812        return LockOutcome::Error(format!("{}: {e}", wt_dir.display()));
2813    }
2814    let lock_path = wt_dir.join("clean.lock");
2815    let pid_str = format!("{}\n", std::process::id());
2816
2817    match std::fs::OpenOptions::new()
2818        .write(true)
2819        .create_new(true)
2820        .open(&lock_path)
2821    {
2822        Ok(mut f) => {
2823            if let Err(e) = f.write_all(pid_str.as_bytes()) {
2824                let _ = std::fs::remove_file(&lock_path);
2825                return LockOutcome::Error(format!("{}: {e}", lock_path.display()));
2826            }
2827            LockOutcome::Acquired(CleanLockGuard(lock_path))
2828        }
2829        Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
2830            let contents = match std::fs::read_to_string(&lock_path) {
2831                Ok(c) => c,
2832                Err(read_err) => {
2833                    return LockOutcome::Error(format!("{}: {read_err}", lock_path.display()));
2834                }
2835            };
2836            let old_pid: i64 = match contents.trim().parse() {
2837                Ok(p) => p,
2838                Err(parse_err) => {
2839                    return LockOutcome::Error(format!(
2840                        "{}: invalid pid: {parse_err}",
2841                        lock_path.display()
2842                    ));
2843                }
2844            };
2845            if is_pid_alive(old_pid) {
2846                return LockOutcome::AlreadyRunning;
2847            }
2848            eprintln!(
2849                "replacing stale {} from dead pid {old_pid}",
2850                lock_path.display()
2851            );
2852            if let Err(rm_err) = std::fs::remove_file(&lock_path) {
2853                return LockOutcome::Error(format!("{}: {rm_err}", lock_path.display()));
2854            }
2855            match std::fs::OpenOptions::new()
2856                .write(true)
2857                .create_new(true)
2858                .open(&lock_path)
2859            {
2860                Ok(mut f) => {
2861                    if let Err(write_err) = f.write_all(pid_str.as_bytes()) {
2862                        let _ = std::fs::remove_file(&lock_path);
2863                        return LockOutcome::Error(format!("{}: {write_err}", lock_path.display()));
2864                    }
2865                    LockOutcome::Acquired(CleanLockGuard(lock_path))
2866                }
2867                Err(open_err) => LockOutcome::Error(format!("{}: {open_err}", lock_path.display())),
2868            }
2869        }
2870        Err(e) => LockOutcome::Error(format!("{}: {e}", lock_path.display())),
2871    }
2872}
2873
2874/// Runs the `blyte clean` command.
2875pub fn run(args: &crate::cli::CleanArgs) -> i32 {
2876    if (args.quiet || args.skip.is_some()) && (args.all || args.dry_run) {
2877        eprintln!("error: --quiet and --skip cannot be combined with --all or --dry-run");
2878        return 2;
2879    }
2880
2881    let repos = if args.all {
2882        let tidy_res = if args.dry_run {
2883            crate::registry::missing_registered()
2884        } else {
2885            crate::registry::prune_missing()
2886        };
2887        match tidy_res {
2888            Ok(removed) if !removed.is_empty() => {
2889                let verb = if args.dry_run {
2890                    "would forget"
2891                } else {
2892                    "forgot"
2893                };
2894                let list = removed
2895                    .iter()
2896                    .map(|p| p.display().to_string())
2897                    .collect::<Vec<_>>()
2898                    .join(", ");
2899                println!(
2900                    "{verb} {} repositories that no longer exist: {list}",
2901                    removed.len()
2902                );
2903            }
2904            Ok(_) => {}
2905            Err(err) => {
2906                let path = crate::registry::state_dir()
2907                    .map(|d| d.join("repos").display().to_string())
2908                    .unwrap_or_default();
2909                eprintln!("error: could not tidy the repository registry {path}: {err}");
2910            }
2911        }
2912        crate::registry::registered()
2913    } else {
2914        match find_repo_root() {
2915            Ok(root) => vec![root],
2916            Err(e) => {
2917                eprintln!("error: {e}");
2918                return 2;
2919            }
2920        }
2921    };
2922
2923    let _lock_guard = if args.quiet {
2924        let Some(root) = repos.first() else {
2925            eprintln!("error: blyte clean --quiet found no repository to clean");
2926            return 1;
2927        };
2928        match acquire_clean_lock(root) {
2929            LockOutcome::Acquired(guard) => Some(guard),
2930            LockOutcome::AlreadyRunning => return 0,
2931            LockOutcome::Error(e) => {
2932                eprintln!("error: {e}");
2933                return 1;
2934            }
2935        }
2936    } else {
2937        None
2938    };
2939
2940    let mut total_freed = 0;
2941    let mut had_errors = false;
2942    for repo in &repos {
2943        let stats = clean_repo(
2944            repo,
2945            args.older_than,
2946            args.dry_run,
2947            args.skip.as_deref(),
2948            args.quiet,
2949        );
2950        total_freed += stats.freed_bytes;
2951        if stats.had_errors {
2952            had_errors = true;
2953        }
2954    }
2955
2956    if !args.quiet {
2957        if args.dry_run {
2958            println!("would free {}", format_size(total_freed));
2959        } else {
2960            println!("freed {}", format_size(total_freed));
2961        }
2962    }
2963
2964    if had_errors {
2965        1
2966    } else {
2967        0
2968    }
2969}
2970
2971fn delete_wip_branch_strict(root: &Path, branch_name: &str) -> Result<(), String> {
2972    let del_out = std::process::Command::new("git")
2973        .args(["branch", "-D", branch_name])
2974        .current_dir(root)
2975        .output()
2976        .map_err(|e| format!("git branch -D {branch_name}: {e}"))?;
2977    if !del_out.status.success() {
2978        return Err(format!(
2979            "git branch -D {branch_name}: {}",
2980            String::from_utf8_lossy(&del_out.stderr).trim()
2981        ));
2982    }
2983    Ok(())
2984}
2985
2986/// Removes a finished run `<id>` when its work is merged (or it made no changes) and its worktree
2987/// has no uncommitted changes.
2988pub fn remove_finished_run(root: &Path, id: &str) -> Result<Option<String>, String> {
2989    let wt_path = root.join(".wt").join(id);
2990    let branch_name = format!("wip/{id}");
2991    let mut ctx = CleanContext::new(root);
2992
2993    if wt_path.exists() {
2994        let reason = match ctx.check_removable(id, u64::MAX) {
2995            Ok(
2996                r @ (RemovalReason::Merged
2997                | RemovalReason::MergedInto(_)
2998                | RemovalReason::MergedThrough(_)
2999                | RemovalReason::NoChanges),
3000            ) => r,
3001            Ok(
3002                RemovalReason::SessionMerged(_)
3003                | RemovalReason::Verdict(_)
3004                | RemovalReason::OlderThan(_)
3005                | RemovalReason::ResearchReport
3006                | RemovalReason::ResearchReportInWorktree
3007                | RemovalReason::ResearchEndedWithoutReport(_)
3008                | RemovalReason::ResearchStoppedWithoutSummary(_),
3009            )
3010            | Err(_) => return Ok(None),
3011        };
3012        if has_uncommitted_changes(&wt_path) {
3013            return Ok(None);
3014        }
3015
3016        let wt_rel = format!(".wt/{id}");
3017        let rm_out = std::process::Command::new("git")
3018            .args(["worktree", "remove", &wt_rel])
3019            .current_dir(root)
3020            .output()
3021            .map_err(|e| format!("git worktree remove {wt_rel}: {e}"))?;
3022        if !rm_out.status.success() {
3023            return Err(format!(
3024                "git worktree remove {wt_rel}: {}",
3025                String::from_utf8_lossy(&rm_out.stderr).trim()
3026            ));
3027        }
3028
3029        if ctx.get_branch_tip(&branch_name).is_some() {
3030            delete_wip_branch_strict(root, &branch_name)?;
3031        }
3032
3033        return Ok(Some(reason.to_string()));
3034    }
3035
3036    if ctx.get_branch_tip(&branch_name).is_some() {
3037        let Some(reason) = ctx.check_run_merged(id) else {
3038            return Ok(None);
3039        };
3040        delete_wip_branch_strict(root, &branch_name)?;
3041        return Ok(Some(reason.to_string()));
3042    }
3043
3044    Ok(None)
3045}
3046
3047/// Starts `blyte clean --quiet [--skip <ID>]` in the background without waiting for it.
3048pub fn spawn_background_clean(root: &Path, skip_id: Option<&str>) {
3049    let res: Result<(), std::io::Error> = (|| {
3050        let wt_dir = root.join(".wt");
3051        std::fs::create_dir_all(&wt_dir)?;
3052        let log_file = std::fs::OpenOptions::new()
3053            .create(true)
3054            .append(true)
3055            .open(wt_dir.join("clean.log"))?;
3056        let stderr_file = log_file.try_clone()?;
3057        let exe = std::env::current_exe()?;
3058        let mut cmd = std::process::Command::new(exe);
3059        cmd.arg("clean").arg("--quiet");
3060        if let Some(id) = skip_id {
3061            cmd.arg("--skip").arg(id);
3062        }
3063        cmd.current_dir(root)
3064            .env_remove(blyte_agent::shell::MODEL_SHELL_ENV)
3065            .stdin(std::process::Stdio::null())
3066            .stdout(std::process::Stdio::from(log_file))
3067            .stderr(std::process::Stdio::from(stderr_file));
3068        let _child = cmd.spawn()?;
3069        Ok(())
3070    })();
3071    if let Err(e) = res {
3072        eprintln!("warning: could not start the background clean: {e}");
3073    }
3074}
3075
3076/// Removes a run's worktree on review after recording the verdict under the same rules.
3077/// Removes the worktree only when the rules allow it now (e.g. redone, or work already merged);
3078/// otherwise prints nothing extra beyond the verdict line, except for accepted/fixed prints
3079/// `worktree .wt/<id> kept until wip/<id> is merged`.
3080pub fn clean_on_review(root: &Path, id: &str) {
3081    let wt_path = root.join(".wt").join(id);
3082    if !wt_path.exists() {
3083        spawn_background_clean(root, Some(id));
3084        return;
3085    }
3086
3087    let mut ctx = CleanContext::new(root);
3088    let branch_name = format!("wip/{id}");
3089    let branch_exists = ctx.get_branch_tip(&branch_name).is_some();
3090
3091    let verdict_path = root.join(".wt").join(format!("{id}.verdict.json"));
3092    let verdict_str = std::fs::read_to_string(&verdict_path)
3093        .ok()
3094        .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
3095        .and_then(|v| {
3096            v.get("verdict")
3097                .and_then(|s| s.as_str())
3098                .map(|s| s.to_string())
3099        })
3100        .unwrap_or_default();
3101
3102    let is_res = ctx.is_research_run(id);
3103    let removal_reason = match ctx.check_removable(id, 14) {
3104        Ok(r) if is_res || !has_uncommitted_changes(&wt_path) => Some(r),
3105        _ => None,
3106    };
3107
3108    let Some(removal_reason) = removal_reason else {
3109        if verdict_str == "accepted" || verdict_str == "fixed" {
3110            println!("worktree .wt/{id} kept until {branch_name} is merged");
3111        }
3112        spawn_background_clean(root, Some(id));
3113        return;
3114    };
3115
3116    if removal_reason == RemovalReason::ResearchReportInWorktree {
3117        let src = wt_path.join("report.md");
3118        let dst = root.join(".wt").join(format!("{id}.report.md"));
3119        if let Err(err) = std::fs::copy(&src, &dst) {
3120            eprintln!(
3121                "error: could not copy {} to {}: {err}",
3122                src.display(),
3123                dst.display()
3124            );
3125            spawn_background_clean(root, Some(id));
3126            return;
3127        }
3128    }
3129
3130    let removed_ok = if is_res {
3131        std::fs::remove_dir_all(&wt_path).is_ok()
3132    } else {
3133        let rm_out = std::process::Command::new("git")
3134            .args(["worktree", "remove", wt_path.to_str().unwrap_or("")])
3135            .current_dir(root)
3136            .output();
3137        let _ = std::process::Command::new("git")
3138            .args(["worktree", "prune"])
3139            .current_dir(root)
3140            .output();
3141        rm_out.map(|o| o.status.success()).unwrap_or(false)
3142    };
3143
3144    if !removed_ok {
3145        if verdict_str == "accepted" || verdict_str == "fixed" {
3146            println!("worktree .wt/{id} kept until {branch_name} is merged");
3147        }
3148        spawn_background_clean(root, Some(id));
3149        return;
3150    }
3151
3152    if branch_exists {
3153        let is_merged = ctx.check_run_merged(id).is_some();
3154        if is_merged {
3155            let del_out = std::process::Command::new("git")
3156                .args(["branch", "-D", &branch_name])
3157                .current_dir(root)
3158                .output();
3159            if del_out.map(|o| o.status.success()).unwrap_or(false) {
3160                ctx.wip_branch_tips.remove(&branch_name);
3161                println!("removed .wt/{id}; branch {branch_name} deleted");
3162            } else {
3163                println!("removed .wt/{id}; branch {branch_name} kept");
3164            }
3165        } else {
3166            println!("removed .wt/{id}; branch {branch_name} kept");
3167        }
3168    } else {
3169        println!("removed .wt/{id}");
3170    }
3171
3172    spawn_background_clean(root, Some(id));
3173}