1use 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
91pub 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
125pub 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
153pub 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
166pub fn find_repo_root() -> Result<PathBuf, String> {
168 let out = std::process::Command::new("git")
169 .args(["rev-parse", "--show-toplevel"])
170 .output()
171 .map_err(|e| format!("git not found: {e}"))?;
172 if !out.status.success() {
173 return Err("not a git repository".to_string());
174 }
175 let root = PathBuf::from(String::from_utf8_lossy(&out.stdout).trim());
176 let dirs = std::process::Command::new("git")
179 .args([
180 "rev-parse",
181 "--path-format=absolute",
182 "--git-dir",
183 "--git-common-dir",
184 ])
185 .current_dir(&root)
186 .output()
187 .map_err(|e| format!("git not found: {e}"))?;
188 if !dirs.status.success() {
189 return Err(format!(
190 "cannot read the git dirs of {}: {}",
191 root.display(),
192 String::from_utf8_lossy(&dirs.stderr).trim()
193 ));
194 }
195 let dirs = String::from_utf8_lossy(&dirs.stdout);
196 let mut lines = dirs.lines();
197 let (Some(git_dir), Some(common_dir)) = (lines.next(), lines.next()) else {
198 return Err(format!("cannot read the git dirs of {}", root.display()));
199 };
200 if git_dir != common_dir {
201 crate::config::main_checkout(&root).ok_or_else(|| {
202 format!(
203 "cannot find main checkout for linked worktree {}",
204 root.display()
205 )
206 })
207 } else {
208 Ok(root)
209 }
210}
211
212pub fn is_research(root: &Path, id: &str) -> bool {
214 let start_path = root.join(".wt").join(format!("{id}.start.json"));
215 if let Ok(s) = std::fs::read_to_string(&start_path) {
216 if let Ok(val) = serde_json::from_str::<serde_json::Value>(&s) {
217 return val
218 .get("research")
219 .and_then(|r| r.as_bool())
220 .unwrap_or(false);
221 }
222 }
223 false
224}
225
226pub fn has_uncommitted_changes(wt_path: &Path) -> bool {
228 let out = std::process::Command::new("git")
229 .args([
230 "-C",
231 wt_path.to_str().unwrap_or(""),
232 "status",
233 "--porcelain",
234 ])
235 .output();
236 match out {
237 Ok(o) if o.status.success() => {
238 !o.stdout.is_empty() && !String::from_utf8_lossy(&o.stdout).trim().is_empty()
239 }
240 _ => true,
241 }
242}
243
244fn git_tree_sha(root: &Path, ref_name: &str) -> Option<String> {
245 let out = std::process::Command::new("git")
246 .args(["rev-parse", &format!("{ref_name}^{{tree}}")])
247 .current_dir(root)
248 .output()
249 .ok()?;
250 if out.status.success() {
251 Some(String::from_utf8_lossy(&out.stdout).trim().to_string())
252 } else {
253 None
254 }
255}
256
257fn is_cherry_merged_into_target(root: &Path, commit_sha: &str, target: &str) -> bool {
258 let cherry_out = std::process::Command::new("git")
259 .args(["cherry", target, commit_sha])
260 .current_dir(root)
261 .output();
262 if let Ok(o) = cherry_out {
263 if o.status.success() {
264 let s = String::from_utf8_lossy(&o.stdout);
265 let lines: Vec<&str> = s
266 .lines()
267 .map(|l| l.trim())
268 .filter(|l| !l.is_empty())
269 .collect();
270 if !lines.is_empty() && lines.iter().all(|l| l.starts_with('-')) {
271 return true;
272 }
273 }
274 }
275 false
276}
277
278fn is_merge_tree_merged_into_target(
279 root: &Path,
280 commit_sha: &str,
281 target: &str,
282 target_tree: Option<&str>,
283) -> bool {
284 let target_tree_sha = match target_tree {
285 Some(t) => Some(t.to_string()),
286 None => git_tree_sha(root, target),
287 };
288 if let Some(target_tree_sha) = target_tree_sha {
289 let merge_tree_out = std::process::Command::new("git")
290 .args(["merge-tree", "--write-tree", target, commit_sha])
291 .current_dir(root)
292 .output();
293 if let Ok(mt_o) = merge_tree_out {
294 if mt_o.status.success() {
295 let mt_stdout = String::from_utf8_lossy(&mt_o.stdout);
296 if let Some(first_line) = mt_stdout.lines().next() {
297 if first_line.trim() == target_tree_sha {
298 return true;
299 }
300 }
301 }
302 }
303 }
304 false
305}
306
307fn parse_started_at(val: &serde_json::Value) -> Option<u64> {
308 let s = val.get("started_at")?;
309 if let Some(n) = s.as_u64() {
310 Some(n)
311 } else if let Some(n) = s.as_i64() {
312 if n >= 0 {
313 Some(n as u64)
314 } else {
315 None
316 }
317 } else if let Some(f) = s.as_f64() {
318 if f >= 0.0 {
319 Some(f as u64)
320 } else {
321 None
322 }
323 } else if let Some(st) = s.as_str() {
324 st.parse::<u64>().ok()
325 } else {
326 None
327 }
328}
329
330fn check_history_merged(
331 root: &Path,
332 tip_sha: &str,
333 target: &str,
334 started_at: Option<&serde_json::Value>,
335) -> bool {
336 let mb_out = std::process::Command::new("git")
337 .args(["merge-base", target, tip_sha])
338 .current_dir(root)
339 .output();
340 let Ok(mb_o) = mb_out else {
341 return false;
342 };
343 if !mb_o.status.success() {
344 return false;
345 }
346 let merge_base = String::from_utf8_lossy(&mb_o.stdout).trim().to_string();
347 if merge_base.is_empty() {
348 return false;
349 }
350
351 let diff_out = std::process::Command::new("git")
352 .args(["diff", "--name-only", &merge_base, tip_sha])
353 .current_dir(root)
354 .output();
355 let Ok(diff_o) = diff_out else {
356 return false;
357 };
358 if !diff_o.status.success() {
359 return false;
360 }
361 let files: Vec<String> = String::from_utf8_lossy(&diff_o.stdout)
362 .lines()
363 .map(|l| l.trim().to_string())
364 .filter(|l| !l.is_empty())
365 .collect();
366
367 if files.is_empty() {
368 return false;
369 }
370
371 let since_arg = started_at
372 .and_then(|v| {
373 if let Some(n) = v.as_i64() {
374 if n >= 100_000_000 {
375 Some(format!("--since={n}"))
376 } else {
377 Some("--since=1970-01-01T00:00:00Z".to_string())
378 }
379 } else if let Some(n) = v.as_u64() {
380 if n >= 100_000_000 {
381 Some(format!("--since={n}"))
382 } else {
383 Some("--since=1970-01-01T00:00:00Z".to_string())
384 }
385 } else {
386 v.as_str().map(|s| format!("--since={s}"))
387 }
388 })
389 .unwrap_or_else(|| "--since=1970-01-01T00:00:00Z".to_string());
390
391 let mut cmd = std::process::Command::new("git");
392 cmd.args([
393 "rev-list",
394 "--first-parent",
395 &since_arg,
396 "-n",
397 "20",
398 target,
399 "--",
400 ]);
401 for f in &files {
402 cmd.arg(f);
403 }
404 cmd.current_dir(root);
405 let Ok(rev_o) = cmd.output() else {
406 return false;
407 };
408 if !rev_o.status.success() {
409 return false;
410 }
411
412 let commits: Vec<String> = String::from_utf8_lossy(&rev_o.stdout)
413 .lines()
414 .map(|l| l.trim().to_string())
415 .filter(|l| !l.is_empty())
416 .collect();
417
418 for c in commits {
419 let mt_out = std::process::Command::new("git")
420 .args(["merge-tree", "--write-tree", &c, tip_sha])
421 .current_dir(root)
422 .output();
423 let Ok(mt_o) = mt_out else {
424 continue;
425 };
426 if !mt_o.status.success() {
427 continue;
428 }
429 let mt_stdout = String::from_utf8_lossy(&mt_o.stdout);
430 let Some(first_line) = mt_stdout.lines().next() else {
431 continue;
432 };
433 let mt_tree = first_line.trim();
434
435 if let Some(c_tree) = git_tree_sha(root, &c) {
436 if mt_tree == c_tree {
437 return true;
438 }
439 }
440 }
441
442 false
443}
444
445pub fn read_start_record(root: &Path, id: &str) -> Result<Option<serde_json::Value>, String> {
450 let path = root.join(".wt").join(format!("{id}.start.json"));
451 let content = match std::fs::read_to_string(&path) {
452 Ok(content) => content,
453 Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(None),
454 Err(err) => return Err(format!("{}: {err}", path.display())),
455 };
456 match serde_json::from_str::<serde_json::Value>(&content) {
457 Ok(value) if value.is_object() => Ok(Some(value)),
458 Ok(_) => Err(format!("{}: not a JSON object", path.display())),
459 Err(err) => Err(format!("{}: {err}", path.display())),
460 }
461}
462
463pub struct CleanContext<'a> {
465 pub root: &'a Path,
466 pub start_files: HashMap<String, serde_json::Value>,
467 pub all_run_ids: Vec<String>,
468 pub wip_branch_tips: HashMap<String, String>,
469 pub default_branch: String,
470 pub origin_default: Option<String>,
471 pub default_tree: Option<String>,
472 pub origin_default_tree: Option<String>,
473 pub wip_contains_cache: HashMap<String, Vec<String>>,
474 pub merged_cache: HashMap<String, Option<RemovalReason>>,
475 pub branch_contains_calls: usize,
476 pub cherry_pick_set: Option<HashSet<String>>,
477 pub rev_list_cache: HashMap<String, Vec<String>>,
478 pub ancestor_cache: HashMap<(String, String), bool>,
479}
480
481impl<'a> CleanContext<'a> {
482 pub fn new(root: &'a Path) -> Self {
483 let mut start_files = HashMap::new();
484 let mut all_run_ids = Vec::new();
485 let wt_dir = root.join(".wt");
486 if let Ok(entries) = std::fs::read_dir(&wt_dir) {
487 for entry in entries.flatten() {
488 let name = entry.file_name().to_string_lossy().to_string();
489 if let Some(id) = name.strip_suffix(".start.json") {
490 all_run_ids.push(id.to_string());
491 if let Ok(content) = std::fs::read_to_string(entry.path()) {
492 if let Ok(val) = serde_json::from_str::<serde_json::Value>(&content) {
493 start_files.insert(id.to_string(), val);
494 }
495 }
496 }
497 }
498 }
499 all_run_ids.sort();
500
501 let mut wip_branch_tips = HashMap::new();
502 let ref_out = std::process::Command::new("git")
503 .args([
504 "for-each-ref",
505 "--format=%(refname:short) %(objectname)",
506 "refs/heads/wip/",
507 ])
508 .current_dir(root)
509 .output();
510 if let Ok(o) = ref_out {
511 if o.status.success() {
512 for line in String::from_utf8_lossy(&o.stdout).lines() {
513 let mut parts = line.split_whitespace();
514 if let (Some(refname), Some(sha)) = (parts.next(), parts.next()) {
515 wip_branch_tips.insert(refname.to_string(), sha.to_string());
516 }
517 }
518 }
519 }
520
521 let default_branch = find_default_branch(root);
522 let name = default_branch
523 .strip_prefix("origin/")
524 .unwrap_or(&default_branch);
525 let remote = format!("origin/{name}");
526 let origin_default = if remote != default_branch
527 && git_ok(root, &["rev-parse", "--verify", "--quiet", &remote])
528 {
529 Some(remote)
530 } else {
531 None
532 };
533
534 let default_tree = git_tree_sha(root, &default_branch);
535 let origin_default_tree = origin_default
536 .as_deref()
537 .and_then(|r| git_tree_sha(root, r));
538
539 Self {
540 root,
541 start_files,
542 all_run_ids,
543 wip_branch_tips,
544 default_branch,
545 origin_default,
546 default_tree,
547 origin_default_tree,
548 wip_contains_cache: HashMap::new(),
549 merged_cache: HashMap::new(),
550 branch_contains_calls: 0,
551 cherry_pick_set: None,
552 rev_list_cache: HashMap::new(),
553 ancestor_cache: HashMap::new(),
554 }
555 }
556
557 fn compute_cherry_pick_set(&self) -> HashSet<String> {
558 let unremoved_ids = find_blyte_worktrees(self.root);
559 let candidate_ids: &[String] = if unremoved_ids.is_empty() {
560 &self.all_run_ids
561 } else {
562 &unremoved_ids
563 };
564
565 let mut min_started_at: Option<u64> = None;
566 let mut all_valid = true;
567
568 for id in candidate_ids {
569 let start_val = self.start_files.get(id);
570 let parsed = start_val.and_then(parse_started_at);
571 match parsed {
572 Some(ts) => {
573 min_started_at = Some(min_started_at.map_or(ts, |m| m.min(ts)));
574 }
575 None => {
576 all_valid = false;
577 }
578 }
579 }
580
581 let since_arg = if let (true, Some(min_ts)) = (all_valid, min_started_at) {
582 if min_ts >= 86_400 + 100_000_000 {
583 format!("--since={}", min_ts - 86_400)
584 } else {
585 "--since=1970-01-01T00:00:00Z".to_string()
586 }
587 } else {
588 "--since=1970-01-01T00:00:00Z".to_string()
589 };
590
591 let mut targets = Vec::new();
592 let mut seen = HashSet::new();
593
594 if git_ok(
595 self.root,
596 &["rev-parse", "--verify", "--quiet", &self.default_branch],
597 ) && seen.insert(self.default_branch.clone())
598 {
599 targets.push(self.default_branch.clone());
600 }
601
602 if let Some(ref origin_def) = self.origin_default {
603 if git_ok(self.root, &["rev-parse", "--verify", "--quiet", origin_def])
604 && seen.insert(origin_def.clone())
605 {
606 targets.push(origin_def.clone());
607 }
608 }
609
610 for id in &self.all_run_ids {
611 if let Some(base_str) = self
612 .start_files
613 .get(id)
614 .and_then(|s| s.get("base"))
615 .and_then(|b| b.as_str())
616 {
617 if let Some((_, base_targets)) = resolve_base_targets(self.root, base_str) {
618 for bt in base_targets {
619 if seen.insert(bt.clone()) {
620 targets.push(bt);
621 }
622 }
623 }
624 }
625 }
626
627 if targets.is_empty() {
628 return HashSet::new();
629 }
630
631 let mut cmd = std::process::Command::new("git");
632 cmd.args(["log", "--format=%B", &since_arg]);
633 for t in &targets {
634 cmd.arg(t);
635 }
636 cmd.current_dir(self.root);
637
638 let mut set = HashSet::new();
639 if let Ok(o) = cmd.output() {
640 if o.status.success() {
641 let text = String::from_utf8_lossy(&o.stdout);
642 for line in text.lines() {
643 let trimmed = line.trim();
644 if let Some(rest) = trimmed.strip_prefix("(cherry picked from commit ") {
645 if let Some(sha) = rest.strip_suffix(')') {
646 let sha = sha.trim();
647 if is_commit_id(sha) {
648 set.insert(sha.to_lowercase());
649 }
650 }
651 }
652 }
653 }
654 }
655
656 set
657 }
658
659 pub fn get_cherry_pick_set(&mut self) -> &HashSet<String> {
660 if self.cherry_pick_set.is_none() {
661 let set = self.compute_cherry_pick_set();
662 self.cherry_pick_set = Some(set);
663 }
664 self.cherry_pick_set.as_ref().unwrap()
665 }
666
667 fn is_ancestor_of_target(&mut self, commit_sha: &str, target: &str) -> bool {
668 let key = (commit_sha.to_string(), target.to_string());
669 if let Some(&cached) = self.ancestor_cache.get(&key) {
670 return cached;
671 }
672 let is_anc = std::process::Command::new("git")
673 .args(["merge-base", "--is-ancestor", commit_sha, target])
674 .current_dir(self.root)
675 .output()
676 .map(|c| c.status.success())
677 .unwrap_or(false);
678 self.ancestor_cache.insert(key, is_anc);
679 is_anc
680 }
681
682 fn is_ancestor_of_default(&mut self, commit_sha: &str) -> bool {
683 let def = self.default_branch.clone();
684 if self.is_ancestor_of_target(commit_sha, &def) {
685 return true;
686 }
687 if let Some(origin_def) = self.origin_default.clone() {
688 if self.is_ancestor_of_target(commit_sha, &origin_def) {
689 return true;
690 }
691 }
692 false
693 }
694
695 fn get_run_commits_against_default(&mut self, tip_sha: &str) -> Vec<String> {
696 if let Some(cached) = self.rev_list_cache.get(tip_sha) {
697 return cached.clone();
698 }
699 let out = std::process::Command::new("git")
700 .args(["rev-list", &format!("{}..{}", self.default_branch, tip_sha)])
701 .current_dir(self.root)
702 .output();
703 let commits: Vec<String> = match out {
704 Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout)
705 .lines()
706 .map(|l| l.trim().to_lowercase())
707 .filter(|l| !l.is_empty())
708 .collect(),
709 _ => Vec::new(),
710 };
711 self.rev_list_cache
712 .insert(tip_sha.to_string(), commits.clone());
713 commits
714 }
715
716 fn is_in_cherry_pick_record(&mut self, tip_sha: &str) -> bool {
717 let commits = self.get_run_commits_against_default(tip_sha);
718 if commits.is_empty() {
719 return false;
720 }
721 let cherry_set = self.get_cherry_pick_set();
722 commits.iter().all(|c| cherry_set.contains(c))
723 }
724
725 pub fn get_branch_tip(&self, branch_name: &str) -> Option<String> {
726 if let Some(sha) = self.wip_branch_tips.get(branch_name) {
727 return Some(sha.clone());
728 }
729 get_branch_tip(self.root, branch_name)
730 }
731
732 pub fn is_research_run(&self, id: &str) -> bool {
733 self.start_files
734 .get(id)
735 .and_then(|v| v.get("research"))
736 .and_then(|r| r.as_bool())
737 .unwrap_or_else(|| is_research(self.root, id))
738 }
739
740 pub fn get_wip_branches_containing(&mut self, tip_sha: &str) -> Vec<String> {
741 if let Some(cached) = self.wip_contains_cache.get(tip_sha) {
742 return cached.clone();
743 }
744
745 self.branch_contains_calls += 1;
746
747 let out = std::process::Command::new("git")
748 .args([
749 "branch",
750 "--list",
751 "--format=%(refname:short)",
752 "wip/*",
753 "--contains",
754 tip_sha,
755 ])
756 .current_dir(self.root)
757 .output();
758
759 let mut branches = Vec::new();
760 if let Ok(o) = out {
761 if o.status.success() {
762 for line in String::from_utf8_lossy(&o.stdout).lines() {
763 let trimmed = line.trim().trim_start_matches(['*', '+', ' ']).trim();
764 if !trimmed.is_empty() {
765 branches.push(trimmed.to_string());
766 }
767 }
768 }
769 }
770 self.wip_contains_cache
771 .insert(tip_sha.to_string(), branches.clone());
772 branches
773 }
774
775 pub fn get_children_of(&mut self, id: &str, tip_sha: &str) -> Vec<String> {
776 let mut children = Vec::new();
777 let mut seen = HashSet::new();
778
779 for (candidate_id, start_val) in &self.start_files {
781 if candidate_id == id {
782 continue;
783 }
784 if let Some(base_str) = start_val.get("base").and_then(|v| v.as_str()) {
785 let base_str = base_str.trim().trim_end_matches('/');
786 let target1 = format!("wip/{id}");
787 let target2 = format!("refs/heads/wip/{id}");
788 if (base_str == target1 || base_str == target2) && seen.insert(candidate_id.clone())
789 {
790 children.push(candidate_id.clone());
791 }
792 }
793 }
794
795 if !tip_sha.is_empty() {
797 let tip_sha_owned = tip_sha.to_string();
798 let containing_branches = self.get_wip_branches_containing(&tip_sha_owned);
799 for b in containing_branches {
800 let clean_b = b.strip_prefix("refs/heads/").unwrap_or(&b);
801 if let Some(candidate_id) = clean_b.strip_prefix("wip/") {
802 if candidate_id == id {
803 continue;
804 }
805 if !self.start_files.contains_key(candidate_id) {
806 continue;
807 }
808 let has_base = self
809 .start_files
810 .get(candidate_id)
811 .and_then(|val| val.get("base"))
812 .is_some_and(|b| !b.is_null());
813 if !has_base && seen.insert(candidate_id.to_string()) {
814 children.push(candidate_id.to_string());
815 }
816 }
817 }
818 }
819
820 children.sort();
821 children
822 }
823
824 pub fn is_child_run_merged(&mut self, child: &str, visited: &mut HashSet<String>) -> bool {
825 if self.is_research_run(child) {
826 return false;
827 }
828
829 let branch_name = format!("wip/{child}");
830 let tip = self.get_branch_tip(&branch_name);
831
832 if tip.is_none() {
833 let verdict_path = self.root.join(".wt").join(format!("{child}.verdict.json"));
834 let (has_accepted_verdict, is_redone) = if verdict_path.is_file() {
835 let v = std::fs::read_to_string(&verdict_path)
836 .ok()
837 .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
838 .and_then(|v| {
839 v.get("verdict")
840 .and_then(|s| s.as_str())
841 .map(|s| s.to_string())
842 })
843 .unwrap_or_default();
844 (v == "accepted" || v == "fixed", v == "redone")
845 } else {
846 (false, false)
847 };
848
849 if is_redone {
850 return false;
851 }
852
853 let summary_path = self.root.join(".wt").join(format!("{child}.json"));
854 let is_verified = std::fs::read_to_string(&summary_path)
855 .ok()
856 .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
857 .and_then(|v| {
858 v.get("outcome")
859 .and_then(|s| s.as_str())
860 .map(|s| s == "verified")
861 })
862 .unwrap_or(false);
863
864 let wt_gone = !self.root.join(".wt").join(child).is_dir();
865
866 return has_accepted_verdict || (is_verified && wt_gone);
867 }
868
869 self.check_run_merged_internal(child, visited).is_some()
870 }
871
872 pub fn check_run_merged(&mut self, id: &str) -> Option<RemovalReason> {
873 let mut visited = HashSet::new();
874 self.check_run_merged_internal(id, &mut visited)
875 }
876
877 fn check_run_merged_internal(
878 &mut self,
879 id: &str,
880 visited: &mut HashSet<String>,
881 ) -> Option<RemovalReason> {
882 if visited.contains(id) {
883 return None;
884 }
885
886 if let Some(cached) = self.merged_cache.get(id) {
887 return cached.clone();
888 }
889
890 visited.insert(id.to_string());
891
892 let branch_name = format!("wip/{id}");
893 let tip_sha = self.get_branch_tip(&branch_name);
894
895 let result = self.decide_run_merged(id, tip_sha.as_deref(), visited);
896
897 visited.remove(id);
898
899 self.merged_cache.insert(id.to_string(), result.clone());
900 result
901 }
902
903 fn decide_run_merged(
904 &mut self,
905 id: &str,
906 tip_sha: Option<&str>,
907 visited: &mut HashSet<String>,
908 ) -> Option<RemovalReason> {
909 let base_opt = self.start_files.get(id).and_then(|s| {
910 s.get("base")
911 .and_then(|b| b.as_str())
912 .map(|b| b.to_string())
913 });
914 let base_targets = base_opt
915 .as_deref()
916 .and_then(|b| resolve_base_targets(self.root, b));
917 let started_at = self
918 .start_files
919 .get(id)
920 .and_then(|s| s.get("started_at"))
921 .cloned();
922
923 if let Some(tip_sha) = tip_sha {
924 if self.is_ancestor_of_default(tip_sha) {
926 return Some(RemovalReason::Merged);
927 }
928
929 if self.is_in_cherry_pick_record(tip_sha) {
931 return Some(RemovalReason::Merged);
932 }
933
934 if let Some((ref display_name, ref targets)) = base_targets {
936 for target in targets {
937 if self.is_ancestor_of_target(tip_sha, target) {
938 return Some(RemovalReason::MergedInto(display_name.clone()));
939 }
940 if is_cherry_merged_into_target(self.root, tip_sha, target) {
941 return Some(RemovalReason::MergedInto(display_name.clone()));
942 }
943 if is_merge_tree_merged_into_target(self.root, tip_sha, target, None) {
944 return Some(RemovalReason::MergedInto(display_name.clone()));
945 }
946 }
947 }
948 }
949
950 let children = self.get_children_of(id, tip_sha.unwrap_or(""));
952 for child in children {
953 if visited.contains(&child) {
954 continue;
955 }
956 if self.is_child_run_merged(&child, visited) {
957 return Some(RemovalReason::MergedThrough(child));
958 }
959 }
960
961 if let Some(tip_sha) = tip_sha {
962 if is_cherry_merged_into_target(self.root, tip_sha, &self.default_branch) {
964 return Some(RemovalReason::Merged);
965 }
966 if let Some(ref origin_def) = self.origin_default {
967 if is_cherry_merged_into_target(self.root, tip_sha, origin_def) {
968 return Some(RemovalReason::Merged);
969 }
970 }
971
972 if is_merge_tree_merged_into_target(
974 self.root,
975 tip_sha,
976 &self.default_branch,
977 self.default_tree.as_deref(),
978 ) {
979 return Some(RemovalReason::Merged);
980 }
981 if let Some(ref origin_def) = self.origin_default {
982 if is_merge_tree_merged_into_target(
983 self.root,
984 tip_sha,
985 origin_def,
986 self.origin_default_tree.as_deref(),
987 ) {
988 return Some(RemovalReason::Merged);
989 }
990 }
991
992 if check_history_merged(
994 self.root,
995 tip_sha,
996 &self.default_branch,
997 started_at.as_ref(),
998 ) {
999 return Some(RemovalReason::Merged);
1000 }
1001 if let Some(ref origin_def) = self.origin_default {
1002 if check_history_merged(self.root, tip_sha, origin_def, started_at.as_ref()) {
1003 return Some(RemovalReason::Merged);
1004 }
1005 }
1006 if let Some((ref display_name, ref targets)) = base_targets {
1007 for target in targets {
1008 if check_history_merged(self.root, tip_sha, target, started_at.as_ref()) {
1009 return Some(RemovalReason::MergedInto(display_name.clone()));
1010 }
1011 }
1012 }
1013
1014 if let Some(reason) = self.squash_merged_reason(tip_sha, &base_targets) {
1016 return Some(reason);
1017 }
1018 }
1019
1020 None
1021 }
1022
1023 fn squash_merged_reason(
1024 &self,
1025 tip_sha: &str,
1026 base_targets: &Option<(String, Vec<String>)>,
1027 ) -> Option<RemovalReason> {
1028 if is_squash_merged_into_target(self.root, tip_sha, &self.default_branch) {
1029 return Some(RemovalReason::Merged);
1030 }
1031 if let Some(ref origin_def) = self.origin_default {
1032 if is_squash_merged_into_target(self.root, tip_sha, origin_def) {
1033 return Some(RemovalReason::Merged);
1034 }
1035 }
1036 if let Some((ref display_name, ref targets)) = base_targets {
1037 for target in targets {
1038 if is_squash_merged_into_target(self.root, tip_sha, target) {
1039 return Some(RemovalReason::MergedInto(display_name.clone()));
1040 }
1041 }
1042 }
1043 None
1044 }
1045
1046 pub fn find_merged_followup(&mut self, id: &str) -> Option<String> {
1047 let branch_name = format!("wip/{id}");
1048 let tip_sha = self.get_branch_tip(&branch_name);
1049 let mut visited = HashSet::new();
1050 visited.insert(id.to_string());
1051 let children = self.get_children_of(id, tip_sha.as_deref().unwrap_or(""));
1052 children
1053 .into_iter()
1054 .find(|child| self.is_child_run_merged(child, &mut visited))
1055 }
1056
1057 pub fn check_removable(
1058 &mut self,
1059 id: &str,
1060 older_than_days: u64,
1061 ) -> Result<RemovalReason, KeptReason> {
1062 let wt_dir = self.root.join(".wt");
1063 let summary_path = wt_dir.join(format!("{id}.json"));
1064 let verdict_path = wt_dir.join(format!("{id}.verdict.json"));
1065 let report_path = wt_dir.join(format!("{id}.report.md"));
1066
1067 match read_start_record(self.root, id) {
1068 Err(reason) => return Err(KeptReason::UnreadableStartRecord(reason)),
1069 Ok(Some(value)) => {
1070 self.start_files.insert(id.to_string(), value);
1071 }
1072 Ok(None) => {
1073 self.start_files.remove(id);
1074 }
1075 }
1076 let start_json = self.start_files.get(id);
1077 let summary_exists = summary_path.is_file();
1078
1079 if let Some(start) = start_json {
1081 if let Some(pid) = start.get("pid").and_then(|p| p.as_i64()) {
1082 if is_pid_alive(pid) {
1083 if !summary_exists {
1084 return Err(KeptReason::Running);
1085 }
1086 let Some(started_at) = parse_started_at(start) else {
1087 return Err(KeptReason::Running);
1088 };
1089 let summary_mtime = std::fs::metadata(&summary_path)
1090 .ok()
1091 .and_then(|m| m.modified().ok())
1092 .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
1093 .map(|d| d.as_secs());
1094 if summary_mtime.is_none_or(|mtime| mtime < started_at) {
1095 return Err(KeptReason::Running);
1096 }
1097 }
1098 }
1099 }
1100
1101 let is_res = self.is_research_run(id);
1102
1103 let verdict_str = if verdict_path.is_file() {
1105 std::fs::read_to_string(&verdict_path)
1106 .ok()
1107 .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
1108 .and_then(|v| {
1109 v.get("verdict")
1110 .and_then(|s| s.as_str())
1111 .map(|s| s.to_string())
1112 })
1113 .unwrap_or_default()
1114 } else {
1115 String::new()
1116 };
1117
1118 if verdict_str == "redone" {
1119 return Ok(RemovalReason::Verdict("redone".to_string()));
1120 }
1121
1122 if summary_exists {
1123 if let Ok(summary_str) = std::fs::read_to_string(&summary_path) {
1124 if let Ok(val) = serde_json::from_str::<serde_json::Value>(&summary_str) {
1125 if val.get("outcome").and_then(|o| o.as_str()) == Some("no_changes") {
1126 return Ok(RemovalReason::NoChanges);
1127 }
1128 }
1129 }
1130 }
1131
1132 if is_res && report_path.is_file() {
1134 return Ok(RemovalReason::ResearchReport);
1135 }
1136
1137 if is_res {
1138 let wt_report_path = wt_dir.join(id).join("report.md");
1139 if wt_report_path.is_file() && !report_path.is_file() {
1140 return Ok(RemovalReason::ResearchReportInWorktree);
1141 }
1142 if summary_exists {
1143 let outcome = std::fs::read_to_string(&summary_path)
1144 .ok()
1145 .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
1146 .and_then(|v| {
1147 v.get("outcome")
1148 .and_then(|o| o.as_str())
1149 .filter(|s| !s.is_empty())
1150 .map(|s| s.to_string())
1151 });
1152 return match outcome {
1153 Some(outcome) => Ok(RemovalReason::ResearchEndedWithoutReport(outcome)),
1154 None => Err(KeptReason::UnreadableSummary),
1155 };
1156 }
1157 let start_path = wt_dir.join(format!("{id}.start.json"));
1158 if let Ok(meta) = std::fs::metadata(&start_path) {
1159 if let Ok(mtime) = meta.modified() {
1160 let age = std::time::SystemTime::now()
1161 .duration_since(mtime)
1162 .unwrap_or(std::time::Duration::ZERO);
1163 if age >= std::time::Duration::from_secs(older_than_days.saturating_mul(86400))
1164 {
1165 return Ok(RemovalReason::ResearchStoppedWithoutSummary(
1166 older_than_days,
1167 ));
1168 }
1169 }
1170 }
1171 }
1172
1173 if !is_res {
1175 if let Some(reason) = self.check_run_merged(id) {
1176 return Ok(reason);
1177 }
1178 }
1179
1180 if summary_exists {
1182 if let Ok(meta) = std::fs::metadata(&summary_path) {
1183 if let Ok(mtime) = meta.modified() {
1184 let age = std::time::SystemTime::now()
1185 .duration_since(mtime)
1186 .unwrap_or(std::time::Duration::ZERO);
1187 if age >= std::time::Duration::from_secs(older_than_days.saturating_mul(86400))
1188 {
1189 return Ok(RemovalReason::OlderThan(older_than_days));
1190 }
1191 }
1192 }
1193 }
1194
1195 if !verdict_str.is_empty() {
1197 return Err(KeptReason::NotMergedYet);
1198 }
1199
1200 if is_res {
1201 Err(KeptReason::NoReport)
1202 } else {
1203 Err(KeptReason::NoVerdict)
1204 }
1205 }
1206}
1207
1208pub fn check_removable(
1210 root: &Path,
1211 id: &str,
1212 older_than_days: u64,
1213) -> Result<RemovalReason, KeptReason> {
1214 let mut ctx = CleanContext::new(root);
1215 ctx.check_removable(id, older_than_days)
1216}
1217
1218pub fn find_default_branch(root: &Path) -> String {
1220 let sym_out = std::process::Command::new("git")
1221 .args(["symbolic-ref", "--short", "refs/remotes/origin/HEAD"])
1222 .current_dir(root)
1223 .output();
1224 if let Ok(o) = sym_out {
1225 if o.status.success() {
1226 let target = String::from_utf8_lossy(&o.stdout);
1227 let target = target.trim();
1228 let branch_name = target.strip_prefix("origin/").unwrap_or(target);
1229 let local_check = std::process::Command::new("git")
1230 .args([
1231 "rev-parse",
1232 "--verify",
1233 &format!("refs/heads/{branch_name}"),
1234 ])
1235 .current_dir(root)
1236 .output();
1237 if local_check.map(|c| c.status.success()).unwrap_or(false) {
1238 return branch_name.to_string();
1239 }
1240 let remote_check = std::process::Command::new("git")
1241 .args(["rev-parse", "--verify", target])
1242 .current_dir(root)
1243 .output();
1244 if remote_check.map(|c| c.status.success()).unwrap_or(false) {
1245 return target.to_string();
1246 }
1247 return branch_name.to_string();
1248 }
1249 }
1250
1251 let main_check = std::process::Command::new("git")
1252 .args(["rev-parse", "--verify", "refs/heads/main"])
1253 .current_dir(root)
1254 .output();
1255 if main_check.map(|c| c.status.success()).unwrap_or(false) {
1256 return "main".to_string();
1257 }
1258
1259 let master_check = std::process::Command::new("git")
1260 .args(["rev-parse", "--verify", "refs/heads/master"])
1261 .current_dir(root)
1262 .output();
1263 if master_check.map(|c| c.status.success()).unwrap_or(false) {
1264 return "master".to_string();
1265 }
1266
1267 "main".to_string()
1268}
1269
1270fn is_commit_id(s: &str) -> bool {
1272 (s.len() >= 7 && s.len() <= 64) && s.chars().all(|c| c.is_ascii_hexdigit())
1273}
1274
1275pub fn resolve_base_targets(root: &Path, base: &str) -> Option<(String, Vec<String>)> {
1280 let base = base.trim();
1281 if base.is_empty() {
1282 return None;
1283 }
1284
1285 if base == "HEAD"
1286 || base.starts_with("HEAD~")
1287 || base.starts_with("HEAD^")
1288 || base.starts_with("HEAD@")
1289 || base.starts_with("HEAD:")
1290 {
1291 return None;
1292 }
1293
1294 if base == "FETCH_HEAD" || base == "ORIG_HEAD" || base == "MERGE_HEAD" {
1295 return None;
1296 }
1297
1298 if is_commit_id(base) {
1299 return None;
1300 }
1301
1302 let clean = if let Some(stripped) = base.strip_prefix("refs/heads/") {
1303 stripped
1304 } else if let Some(stripped) = base.strip_prefix("refs/remotes/") {
1305 stripped
1306 } else {
1307 base
1308 };
1309
1310 let is_wip = clean == "wip"
1311 || clean.starts_with("wip/")
1312 || clean == "origin/wip"
1313 || clean.starts_with("origin/wip/");
1314 if is_wip {
1315 return None;
1316 }
1317
1318 let (display_name, candidates) = if let Some(without_origin) = clean.strip_prefix("origin/") {
1319 if without_origin.is_empty()
1320 || without_origin == "wip"
1321 || without_origin.starts_with("wip/")
1322 || without_origin == "HEAD"
1323 || without_origin.starts_with("HEAD~")
1324 || without_origin.starts_with("HEAD^")
1325 || is_commit_id(without_origin)
1326 {
1327 return None;
1328 }
1329 let cand1 = format!("refs/remotes/{clean}");
1330 let cand2 = format!("refs/heads/{without_origin}");
1331 (without_origin.to_string(), vec![cand1, cand2])
1332 } else {
1333 let cand1 = format!("refs/heads/{clean}");
1334 let cand2 = format!("refs/remotes/origin/{clean}");
1335 (clean.to_string(), vec![cand1, cand2])
1336 };
1337
1338 let mut resolved = Vec::new();
1339 for cand in candidates {
1340 if git_ok(root, &["rev-parse", "--verify", "--quiet", &cand]) {
1341 resolved.push(cand);
1342 }
1343 }
1344
1345 if resolved.is_empty() {
1346 None
1347 } else {
1348 Some((display_name, resolved))
1349 }
1350}
1351
1352pub fn read_run_base(root: &Path, id: &str) -> Option<String> {
1354 let start_path = root.join(".wt").join(format!("{id}.start.json"));
1355 std::fs::read_to_string(&start_path)
1356 .ok()
1357 .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
1358 .and_then(|v| {
1359 v.get("base")
1360 .and_then(|b| b.as_str())
1361 .map(|s| s.to_string())
1362 })
1363}
1364
1365pub fn get_branch_tip(root: &Path, branch_name: &str) -> Option<String> {
1367 let check = std::process::Command::new("git")
1368 .args([
1369 "rev-parse",
1370 "--verify",
1371 &format!("refs/heads/{branch_name}"),
1372 ])
1373 .current_dir(root)
1374 .output()
1375 .ok()?;
1376 if !check.status.success() {
1377 return None;
1378 }
1379
1380 let tip_out = std::process::Command::new("git")
1381 .args(["rev-parse", &format!("refs/heads/{branch_name}")])
1382 .current_dir(root)
1383 .output()
1384 .ok()?;
1385 if tip_out.status.success() {
1386 Some(String::from_utf8_lossy(&tip_out.stdout).trim().to_string())
1387 } else {
1388 None
1389 }
1390}
1391
1392pub fn is_branch_merged(root: &Path, branch_name: &str) -> bool {
1399 let mut ctx = CleanContext::new(root);
1400 if let Some(id) = branch_name.strip_prefix("wip/") {
1401 ctx.check_run_merged(id).is_some()
1402 } else {
1403 is_branch_merged_with_targets(root, branch_name, &[])
1404 }
1405}
1406
1407pub fn is_branch_merged_with_targets(
1409 root: &Path,
1410 branch_name: &str,
1411 extra_targets: &[&str],
1412) -> bool {
1413 let Some(tip_sha) = get_branch_tip(root, branch_name) else {
1414 return false;
1415 };
1416
1417 is_commit_merged_with_targets(root, &tip_sha, extra_targets)
1418}
1419
1420pub fn is_branch_merged_with_extra_targets(
1422 root: &Path,
1423 branch_name: &str,
1424 extra_targets: &[&str],
1425) -> bool {
1426 is_branch_merged_with_targets(root, branch_name, extra_targets)
1427}
1428
1429pub fn is_commit_merged(root: &Path, commit_sha: &str) -> bool {
1435 is_commit_merged_with_targets(root, commit_sha, &[])
1436}
1437
1438pub fn is_commit_merged_with_targets(
1440 root: &Path,
1441 commit_sha: &str,
1442 extra_targets: &[&str],
1443) -> bool {
1444 let default_branch = find_default_branch(root);
1445 let name = default_branch
1448 .strip_prefix("origin/")
1449 .unwrap_or(&default_branch);
1450 let remote = format!("origin/{name}");
1451 let mut targets = vec![default_branch.clone()];
1452 if remote != default_branch && git_ok(root, &["rev-parse", "--verify", "--quiet", &remote]) {
1453 targets.push(remote);
1454 }
1455 for extra in extra_targets {
1456 if git_ok(root, &["rev-parse", "--verify", "--quiet", extra]) {
1457 targets.push(extra.to_string());
1458 }
1459 }
1460 targets
1461 .iter()
1462 .any(|target| merged_into(root, commit_sha, target))
1463}
1464
1465fn git_ok(root: &Path, args: &[&str]) -> bool {
1466 std::process::Command::new("git")
1467 .args(args)
1468 .current_dir(root)
1469 .output()
1470 .map(|o| o.status.success())
1471 .unwrap_or(false)
1472}
1473
1474fn merged_into(root: &Path, commit_sha: &str, default_branch: &str) -> bool {
1476 let ancestor_check = std::process::Command::new("git")
1478 .args(["merge-base", "--is-ancestor", commit_sha, default_branch])
1479 .current_dir(root)
1480 .output();
1481 if ancestor_check.map(|c| c.status.success()).unwrap_or(false) {
1482 return true;
1483 }
1484
1485 let cherry_out = std::process::Command::new("git")
1487 .args(["cherry", default_branch, commit_sha])
1488 .current_dir(root)
1489 .output();
1490 if let Ok(o) = cherry_out {
1491 if o.status.success() {
1492 let s = String::from_utf8_lossy(&o.stdout);
1493 let lines: Vec<&str> = s
1494 .lines()
1495 .map(|l| l.trim())
1496 .filter(|l| !l.is_empty())
1497 .collect();
1498 if !lines.is_empty() && lines.iter().all(|l| l.starts_with('-')) {
1499 return true;
1500 }
1501 }
1502 }
1503
1504 let default_tree_out = std::process::Command::new("git")
1507 .args(["rev-parse", &format!("{default_branch}^{{tree}}")])
1508 .current_dir(root)
1509 .output();
1510 if let Ok(tree_o) = default_tree_out {
1511 if tree_o.status.success() {
1512 let default_tree = String::from_utf8_lossy(&tree_o.stdout).trim().to_string();
1513 let merge_tree_out = std::process::Command::new("git")
1514 .args(["merge-tree", "--write-tree", default_branch, commit_sha])
1515 .current_dir(root)
1516 .output();
1517 if let Ok(mt_o) = merge_tree_out {
1518 if mt_o.status.success() {
1519 let mt_stdout = String::from_utf8_lossy(&mt_o.stdout);
1520 if let Some(first_line) = mt_stdout.lines().next() {
1521 if first_line.trim() == default_tree {
1522 return true;
1523 }
1524 }
1525 }
1526 }
1527 }
1528 }
1529
1530 is_squash_merged_into_target(root, commit_sha, default_branch)
1533}
1534
1535fn is_squash_merged_into_target(root: &Path, commit_sha: &str, target: &str) -> bool {
1536 let mb_out = std::process::Command::new("git")
1537 .args(["merge-base", target, commit_sha])
1538 .current_dir(root)
1539 .output();
1540 let Ok(mb_o) = mb_out else {
1541 return false;
1542 };
1543 if !mb_o.status.success() {
1544 return false;
1545 }
1546 let base = String::from_utf8_lossy(&mb_o.stdout).trim().to_string();
1547 if base.is_empty() {
1548 return false;
1549 }
1550
1551 let subj_out = std::process::Command::new("git")
1552 .args([
1553 "log",
1554 "--no-merges",
1555 "--format=%s",
1556 &format!("{target}..{commit_sha}"),
1557 ])
1558 .current_dir(root)
1559 .output();
1560 let Ok(subj_o) = subj_out else {
1561 return false;
1562 };
1563 if !subj_o.status.success() {
1564 return false;
1565 }
1566 let subj_stdout = String::from_utf8_lossy(&subj_o.stdout);
1567 let subjects: Vec<&str> = subj_stdout
1568 .lines()
1569 .map(|l| l.trim())
1570 .filter(|l| !l.is_empty())
1571 .collect();
1572 if subjects.is_empty() {
1573 return false;
1574 }
1575
1576 let hay_out = std::process::Command::new("git")
1577 .args(["log", "--format=%B", &format!("{base}..{target}")])
1578 .current_dir(root)
1579 .output();
1580 let Ok(hay_o) = hay_out else {
1581 return false;
1582 };
1583 if !hay_o.status.success() {
1584 return false;
1585 }
1586 let hay_stdout = String::from_utf8_lossy(&hay_o.stdout);
1587 let mut haystack_lines = HashSet::new();
1588 for line in hay_stdout.lines() {
1589 let trimmed = line.trim();
1590 if trimmed.is_empty() {
1591 continue;
1592 }
1593 haystack_lines.insert(trimmed.to_string());
1594 if let Some(stripped) = trimmed
1595 .strip_prefix("* ")
1596 .or_else(|| trimmed.strip_prefix("- "))
1597 {
1598 let stripped = stripped.trim();
1599 if !stripped.is_empty() {
1600 haystack_lines.insert(stripped.to_string());
1601 }
1602 }
1603 }
1604
1605 subjects.iter().all(|s| haystack_lines.contains(*s))
1606}
1607
1608pub fn list_all_run_ids(root: &Path) -> Vec<String> {
1610 let wt_dir = root.join(".wt");
1611 let mut ids = Vec::new();
1612 if let Ok(entries) = std::fs::read_dir(&wt_dir) {
1613 for entry in entries.flatten() {
1614 let name = entry.file_name().to_string_lossy().to_string();
1615 if let Some(id) = name.strip_suffix(".start.json") {
1616 ids.push(id.to_string());
1617 }
1618 }
1619 }
1620 ids.sort();
1621 ids
1622}
1623
1624pub fn find_merged_followup(root: &Path, id: &str) -> Option<String> {
1626 let mut ctx = CleanContext::new(root);
1627 ctx.find_merged_followup(id)
1628}
1629
1630pub fn find_blyte_worktrees(root: &Path) -> Vec<String> {
1632 let wt_dir = root.join(".wt");
1633 if !wt_dir.is_dir() {
1634 return Vec::new();
1635 }
1636 let mut ids = Vec::new();
1637 if let Ok(entries) = std::fs::read_dir(&wt_dir) {
1638 for entry in entries.flatten() {
1639 if let Ok(ft) = entry.file_type() {
1640 if ft.is_dir() {
1641 let name = entry.file_name().to_string_lossy().to_string();
1642 let start_file = wt_dir.join(format!("{name}.start.json"));
1643 if start_file.is_file() {
1644 ids.push(name);
1645 }
1646 }
1647 }
1648 }
1649 }
1650 ids.sort();
1651 ids
1652}
1653
1654#[derive(Debug, Default)]
1655pub struct CleanRepoStats {
1656 pub removed_worktrees: usize,
1657 pub freed_bytes: u64,
1658 pub had_errors: bool,
1659}
1660
1661pub const DEFAULT_SESSION_IDLE_DAYS: u64 = 7;
1663
1664pub fn parse_lsof_cwd_output(stdout: &str) -> Vec<PathBuf> {
1666 stdout
1667 .lines()
1668 .filter_map(|line| line.strip_prefix('n'))
1669 .filter(|path| !path.is_empty())
1670 .map(PathBuf::from)
1671 .collect()
1672}
1673
1674pub fn list_running_process_cwds() -> Result<Vec<PathBuf>, String> {
1676 let out = std::process::Command::new("lsof")
1677 .args(["-a", "-d", "cwd", "-Fn"])
1678 .output()
1679 .map_err(|e| e.to_string())?;
1680 if !out.status.success() {
1682 let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string();
1683 if stderr.is_empty() {
1684 return Err(format!("lsof exited with {}", out.status));
1685 }
1686 return Err(format!("lsof exited with {}: {stderr}", out.status));
1687 }
1688 let paths = parse_lsof_cwd_output(&String::from_utf8_lossy(&out.stdout));
1689 if paths.is_empty() {
1690 return Err("lsof listed no working directories".to_string());
1691 }
1692 Ok(paths)
1693}
1694
1695pub fn is_session_worktree(root: &Path, wt_path: &Path) -> bool {
1699 let root_canon = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
1700 let wt_canon = wt_path
1701 .canonicalize()
1702 .unwrap_or_else(|_| wt_path.to_path_buf());
1703 let Some(wt_parent) = wt_canon.parent() else {
1704 return false;
1705 };
1706 let Some(wt_name) = wt_canon.file_name().and_then(|n| n.to_str()) else {
1707 return false;
1708 };
1709
1710 let wt_dir_canon = root_canon
1711 .join(".wt")
1712 .canonicalize()
1713 .unwrap_or_else(|_| root_canon.join(".wt"));
1714 if wt_parent == wt_dir_canon {
1715 let start_file = wt_dir_canon.join(format!("{wt_name}.start.json"));
1716 return !start_file.is_file();
1717 }
1718
1719 let claude_wt_dir_canon = root_canon
1720 .join(".claude")
1721 .join("worktrees")
1722 .canonicalize()
1723 .unwrap_or_else(|_| root_canon.join(".claude").join("worktrees"));
1724 if let Ok(rel) = wt_canon.strip_prefix(&claude_wt_dir_canon) {
1725 if !rel.as_os_str().is_empty() && !has_wt_component(rel) {
1726 return true;
1727 }
1728 }
1729
1730 false
1731}
1732
1733pub fn has_dispatched_runs(wt_path: &Path) -> bool {
1735 let wt_dir = wt_path.join(".wt");
1736 let Ok(entries) = std::fs::read_dir(&wt_dir) else {
1737 return false;
1738 };
1739 for entry in entries.flatten() {
1740 let name = entry.file_name();
1741 if name.to_string_lossy().ends_with(".start.json")
1742 && entry.file_type().map(|ft| ft.is_file()).unwrap_or(false)
1743 {
1744 return true;
1745 }
1746 }
1747 false
1748}
1749
1750pub fn is_worktree_in_use(wt_path: &Path, cwds: &[PathBuf]) -> bool {
1753 let wt_canon = wt_path
1754 .canonicalize()
1755 .unwrap_or_else(|_| wt_path.to_path_buf());
1756 cwds.iter().any(|cwd| {
1757 let cwd_canon = cwd.canonicalize().unwrap_or_else(|_| cwd.clone());
1758 cwd_canon.starts_with(&wt_canon)
1759 })
1760}
1761
1762pub fn is_worktree_idle(wt_path: &Path, idle_days: u64) -> Result<bool, String> {
1766 let o = std::process::Command::new("git")
1767 .arg("-C")
1768 .arg(wt_path.as_os_str())
1769 .args(["rev-parse", "--absolute-git-dir"])
1770 .output()
1771 .map_err(|e| format!("cannot run git: {e}"))?;
1772 if !o.status.success() {
1773 return Err(format!(
1774 "git rev-parse --absolute-git-dir failed: {}",
1775 String::from_utf8_lossy(&o.stderr).trim()
1776 ));
1777 }
1778 let git_dir_str = String::from_utf8_lossy(&o.stdout).trim().to_string();
1779 if git_dir_str.is_empty() {
1780 return Err("git rev-parse --absolute-git-dir printed nothing".to_string());
1781 }
1782 let git_dir = PathBuf::from(git_dir_str);
1783 let now = std::time::SystemTime::now();
1784 let threshold = std::time::Duration::from_secs(idle_days.saturating_mul(86400));
1785 for name in ["index", "HEAD"] {
1786 let p = git_dir.join(name);
1787 let mtime = std::fs::metadata(&p)
1788 .and_then(|m| m.modified())
1789 .map_err(|e| format!("cannot read the time of {}: {e}", p.display()))?;
1790 let age = now
1791 .duration_since(mtime)
1792 .unwrap_or(std::time::Duration::ZERO);
1793 if idle_days > 0 && age <= threshold {
1794 return Ok(false);
1795 }
1796 }
1797 Ok(true)
1798}
1799
1800pub fn check_session_worktree_removable(
1802 root: &Path,
1803 wt: &GitWorktreeInfo,
1804 cwds: &Result<Vec<PathBuf>, String>,
1805 idle_days: u64,
1806) -> Result<RemovalReason, KeptReason> {
1807 let is_merged = if let Some(ref branch) = wt.branch {
1808 is_branch_merged(root, branch)
1809 } else if let Some(ref sha) = wt.head_sha {
1810 is_commit_merged(root, sha)
1811 } else {
1812 false
1813 };
1814 if !is_merged {
1815 return Err(KeptReason::NotMergedYet);
1816 }
1817
1818 if has_dispatched_runs(&wt.path) {
1819 let display_path = display_worktree_path(&wt.path, root);
1820 return Err(KeptReason::HoldsRuns(display_path));
1821 }
1822
1823 if !is_worktree_clean(&wt.path) {
1824 return Err(KeptReason::UncommittedChanges);
1825 }
1826
1827 match cwds {
1828 Ok(list) => {
1829 if is_worktree_in_use(&wt.path, list) {
1830 return Err(KeptReason::InUse);
1831 }
1832 }
1833 Err(err) => {
1834 return Err(KeptReason::CannotCheckInUse(err.clone()));
1835 }
1836 }
1837
1838 match is_worktree_idle(&wt.path, idle_days) {
1839 Ok(true) => {}
1840 Ok(false) => return Err(KeptReason::UsedRecently(idle_days)),
1841 Err(e) => {
1842 return Err(KeptReason::Custom(format!(
1843 "cannot tell when it was last used: {e}"
1844 )))
1845 }
1846 }
1847
1848 let branch_label = wt.branch.clone().unwrap_or_else(|| {
1849 wt.head_sha
1850 .as_deref()
1851 .map(|s| s[..s.len().min(7)].to_string())
1852 .unwrap_or_else(|| "detached".to_string())
1853 });
1854 Ok(RemovalReason::SessionMerged(branch_label))
1855}
1856
1857fn branch_checked_out_elsewhere(
1858 worktrees: &[GitWorktreeInfo],
1859 removed_wt_paths: &HashSet<PathBuf>,
1860 current_wt_canon: &Path,
1861 branch_name: &str,
1862) -> bool {
1863 for wt in worktrees {
1864 if !wt.path.exists() {
1865 continue;
1866 }
1867 let wt_canon = wt
1868 .path
1869 .canonicalize()
1870 .unwrap_or_else(|_| wt.path.to_path_buf());
1871 if wt_canon == current_wt_canon || removed_wt_paths.contains(&wt_canon) {
1872 continue;
1873 }
1874 if wt.branch.as_deref() == Some(branch_name) {
1875 return true;
1876 }
1877 }
1878 false
1879}
1880
1881pub fn clean_repo(
1883 root: &Path,
1884 older_than_days: u64,
1885 dry_run: bool,
1886 skip_id: Option<&str>,
1887 quiet: bool,
1888) -> CleanRepoStats {
1889 clean_repo_with_options(
1890 root,
1891 older_than_days,
1892 dry_run,
1893 skip_id,
1894 quiet,
1895 DEFAULT_SESSION_IDLE_DAYS,
1896 None,
1897 )
1898}
1899
1900pub fn clean_repo_with_options(
1902 root: &Path,
1903 older_than_days: u64,
1904 dry_run: bool,
1905 skip_id: Option<&str>,
1906 quiet: bool,
1907 session_idle_days: u64,
1908 process_cwds: Option<Result<Vec<PathBuf>, String>>,
1909) -> CleanRepoStats {
1910 let mut removed_worktrees = 0;
1911 let mut freed_bytes = 0;
1912 let mut had_errors = false;
1913
1914 let mut ctx = CleanContext::new(root);
1915 let ids = find_blyte_worktrees(root);
1916 for id in ids {
1917 if skip_id == Some(&id) {
1918 continue;
1919 }
1920
1921 let wt_path = root.join(".wt").join(&id);
1922 match ctx.check_removable(&id, older_than_days) {
1923 Err(kept_reason) => {
1924 if !quiet {
1925 println!("kept .wt/{id} ({kept_reason})");
1926 }
1927 }
1928 Ok(removal_reason) => {
1929 let is_res = ctx.is_research_run(&id);
1930 if !is_res && has_uncommitted_changes(&wt_path) {
1931 if !quiet {
1932 println!("kept .wt/{id} (uncommitted changes)");
1933 }
1934 continue;
1935 }
1936
1937 let size = dir_size(&wt_path);
1938 let branch_name = format!("wip/{id}");
1939 let branch_exists = ctx.get_branch_tip(&branch_name).is_some();
1940 let is_merged = branch_exists
1941 && (matches!(
1942 removal_reason,
1943 RemovalReason::Merged
1944 | RemovalReason::MergedInto(_)
1945 | RemovalReason::MergedThrough(_)
1946 ) || ctx.check_run_merged(&id).is_some());
1947
1948 if dry_run {
1949 if !quiet {
1950 println!(
1951 "would remove .wt/{id} ({removal_reason}, {})",
1952 format_size(size)
1953 );
1954 if is_merged {
1955 println!("would delete branch {branch_name} (merged)");
1956 }
1957 }
1958 freed_bytes += size;
1959 removed_worktrees += 1;
1960 } else {
1961 if removal_reason == RemovalReason::ResearchReportInWorktree {
1962 let src = wt_path.join("report.md");
1963 let dst = root.join(".wt").join(format!("{id}.report.md"));
1964 if let Err(err) = std::fs::copy(&src, &dst) {
1965 eprintln!(
1966 "error: could not copy {} to {}: {err}",
1967 src.display(),
1968 dst.display()
1969 );
1970 if !quiet {
1971 println!("kept .wt/{id} (report copy failed)");
1972 }
1973 continue;
1974 }
1975 }
1976
1977 if let Err(reason) = ctx.check_removable(&id, older_than_days) {
1978 if !quiet {
1979 println!("kept .wt/{id} ({reason})");
1980 }
1981 continue;
1982 }
1983
1984 let removed_ok = if is_res {
1985 std::fs::remove_dir_all(&wt_path).is_ok()
1986 } else {
1987 let rm_out = std::process::Command::new("git")
1988 .args(["worktree", "remove", wt_path.to_str().unwrap_or("")])
1989 .current_dir(root)
1990 .output();
1991 let _ = std::process::Command::new("git")
1992 .args(["worktree", "prune"])
1993 .current_dir(root)
1994 .output();
1995 rm_out.map(|o| o.status.success()).unwrap_or(false)
1996 };
1997
1998 if removed_ok {
1999 freed_bytes += size;
2000 removed_worktrees += 1;
2001 if !quiet {
2002 println!("removed .wt/{id} ({removal_reason}, {})", format_size(size));
2003 }
2004 if is_merged {
2005 let del_out = std::process::Command::new("git")
2006 .args(["branch", "-D", &branch_name])
2007 .current_dir(root)
2008 .output();
2009 if del_out.map(|o| o.status.success()).unwrap_or(false) {
2010 ctx.wip_branch_tips.remove(&branch_name);
2011 if !quiet {
2012 println!("deleted branch {branch_name} (merged)");
2013 }
2014 }
2015 }
2016 } else if !quiet {
2017 println!("kept .wt/{id} (worktree remove failed)");
2018 }
2019 }
2020 }
2021 }
2022 }
2023
2024 if !is_linked_worktree(root) {
2025 let all_worktrees = parse_worktree_list(root);
2026 let root_canon = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
2027 let main_canon = all_worktrees
2028 .first()
2029 .map(|wt| wt.path.canonicalize().unwrap_or_else(|_| wt.path.clone()));
2030
2031 let mut session_indices: Vec<(String, usize)> = all_worktrees
2032 .iter()
2033 .enumerate()
2034 .skip(1)
2035 .filter_map(|(idx, wt)| {
2036 if wt.is_bare || !wt.path.exists() {
2037 return None;
2038 }
2039 let wt_canon = wt.path.canonicalize().unwrap_or_else(|_| wt.path.clone());
2040 if wt_canon == root_canon || Some(&wt_canon) == main_canon.as_ref() {
2041 return None;
2042 }
2043 if !is_session_worktree(root, &wt.path) {
2044 return None;
2045 }
2046 Some((display_worktree_path(&wt.path, root), idx))
2047 })
2048 .collect();
2049 session_indices.sort_by(|a, b| a.0.cmp(&b.0));
2050
2051 if !session_indices.is_empty() {
2052 let cwds = process_cwds.unwrap_or_else(list_running_process_cwds);
2053 let mut removed_wt_paths = HashSet::new();
2054
2055 for (display_path, idx) in session_indices {
2056 let wt = &all_worktrees[idx];
2057 let wt_canon = wt.path.canonicalize().unwrap_or_else(|_| wt.path.clone());
2058 match check_session_worktree_removable(root, wt, &cwds, session_idle_days) {
2059 Err(kept_reason) => {
2060 if !quiet {
2061 println!("kept {display_path} ({kept_reason})");
2062 }
2063 }
2064 Ok(removal_reason) => {
2065 let size = dir_size(&wt.path);
2066 if dry_run {
2067 removed_wt_paths.insert(wt_canon.clone());
2068 if !quiet {
2069 println!(
2070 "would remove {display_path} ({removal_reason}, {})",
2071 format_size(size)
2072 );
2073 if let Some(ref branch_name) = wt.branch {
2074 if !branch_checked_out_elsewhere(
2075 &all_worktrees,
2076 &removed_wt_paths,
2077 &wt_canon,
2078 branch_name,
2079 ) && get_branch_tip(root, branch_name).is_some()
2080 {
2081 println!("would delete branch {branch_name} (merged)");
2082 }
2083 }
2084 }
2085 freed_bytes += size;
2086 removed_worktrees += 1;
2087 } else {
2088 let rm_out = std::process::Command::new("git")
2089 .arg("worktree")
2090 .arg("remove")
2091 .arg(&wt.path)
2092 .current_dir(root)
2093 .output();
2094 match rm_out {
2095 Ok(o) if o.status.success() => {
2096 let _ = std::process::Command::new("git")
2097 .args(["worktree", "prune"])
2098 .current_dir(root)
2099 .output();
2100 removed_wt_paths.insert(wt_canon.clone());
2101 freed_bytes += size;
2102 removed_worktrees += 1;
2103 if !quiet {
2104 println!(
2105 "removed {display_path} ({removal_reason}, {})",
2106 format_size(size)
2107 );
2108 }
2109 if let Some(ref branch_name) = wt.branch {
2110 if !branch_checked_out_elsewhere(
2111 &all_worktrees,
2112 &removed_wt_paths,
2113 &wt_canon,
2114 branch_name,
2115 ) && get_branch_tip(root, branch_name).is_some()
2116 {
2117 let del_out = std::process::Command::new("git")
2118 .args(["branch", "-D", branch_name])
2119 .current_dir(root)
2120 .output();
2121 match del_out {
2122 Ok(o) if o.status.success() => {
2123 ctx.wip_branch_tips.remove(branch_name);
2124 if !quiet {
2125 println!(
2126 "deleted branch {branch_name} (merged)"
2127 );
2128 }
2129 }
2130 Ok(o) => {
2131 eprintln!(
2132 "error: could not delete branch {branch_name}: {}",
2133 String::from_utf8_lossy(&o.stderr).trim()
2134 );
2135 had_errors = true;
2136 }
2137 Err(e) => {
2138 eprintln!(
2139 "error: could not delete branch {branch_name}: {e}"
2140 );
2141 had_errors = true;
2142 }
2143 }
2144 }
2145 }
2146 }
2147 Ok(o) => {
2148 let stderr =
2149 String::from_utf8_lossy(&o.stderr).trim().to_string();
2150 let stdout =
2151 String::from_utf8_lossy(&o.stdout).trim().to_string();
2152 let msg = if !stderr.is_empty() {
2153 stderr
2154 } else if !stdout.is_empty() {
2155 stdout
2156 } else {
2157 format!("exit status {}", o.status)
2158 };
2159 eprintln!("error: could not remove {display_path}: {msg}");
2160 had_errors = true;
2161 }
2162 Err(e) => {
2163 eprintln!("error: could not remove {display_path}: {e}");
2164 had_errors = true;
2165 }
2166 }
2167 }
2168 }
2169 }
2170 }
2171 }
2172 }
2173
2174 if !quiet {
2175 report_other_worktrees(root);
2176 }
2177
2178 CleanRepoStats {
2179 removed_worktrees,
2180 freed_bytes,
2181 had_errors,
2182 }
2183}
2184
2185#[derive(Debug)]
2186pub struct GitWorktreeInfo {
2187 pub path: PathBuf,
2188 pub head_sha: Option<String>,
2189 pub branch: Option<String>,
2190 pub is_detached: bool,
2191 pub is_bare: bool,
2192}
2193
2194pub fn parse_worktree_list(root: &Path) -> Vec<GitWorktreeInfo> {
2196 let out = std::process::Command::new("git")
2197 .args(["worktree", "list", "--porcelain"])
2198 .current_dir(root)
2199 .output();
2200 let Ok(o) = out else {
2201 return Vec::new();
2202 };
2203 if !o.status.success() {
2204 return Vec::new();
2205 }
2206 let text = String::from_utf8_lossy(&o.stdout);
2207
2208 let mut list = Vec::new();
2209 let mut cur_path: Option<PathBuf> = None;
2210 let mut cur_head: Option<String> = None;
2211 let mut cur_branch: Option<String> = None;
2212 let mut cur_detached = false;
2213 let mut cur_bare = false;
2214
2215 let mut finish_entry = |path: &mut Option<PathBuf>,
2216 head: &mut Option<String>,
2217 branch: &mut Option<String>,
2218 detached: &mut bool,
2219 bare: &mut bool| {
2220 if let Some(p) = path.take() {
2221 list.push(GitWorktreeInfo {
2222 path: p,
2223 head_sha: head.take(),
2224 branch: branch.take(),
2225 is_detached: *detached,
2226 is_bare: *bare,
2227 });
2228 *detached = false;
2229 *bare = false;
2230 }
2231 };
2232
2233 for line in text.lines() {
2234 let line = line.trim();
2235 if line.is_empty() {
2236 finish_entry(
2237 &mut cur_path,
2238 &mut cur_head,
2239 &mut cur_branch,
2240 &mut cur_detached,
2241 &mut cur_bare,
2242 );
2243 } else if let Some(p) = line.strip_prefix("worktree ") {
2244 finish_entry(
2245 &mut cur_path,
2246 &mut cur_head,
2247 &mut cur_branch,
2248 &mut cur_detached,
2249 &mut cur_bare,
2250 );
2251 cur_path = Some(PathBuf::from(p.trim()));
2252 } else if let Some(h) = line.strip_prefix("HEAD ") {
2253 cur_head = Some(h.trim().to_string());
2254 } else if let Some(b) = line.strip_prefix("branch ") {
2255 let b_str = b.trim();
2256 let b_name = b_str.strip_prefix("refs/heads/").unwrap_or(b_str);
2257 cur_branch = Some(b_name.to_string());
2258 } else if line == "detached" {
2259 cur_detached = true;
2260 } else if line == "bare" {
2261 cur_bare = true;
2262 }
2263 }
2264 finish_entry(
2265 &mut cur_path,
2266 &mut cur_head,
2267 &mut cur_branch,
2268 &mut cur_detached,
2269 &mut cur_bare,
2270 );
2271 list
2272}
2273
2274pub fn display_worktree_path(target: &Path, root: &Path) -> String {
2278 let target_canon = target
2279 .canonicalize()
2280 .unwrap_or_else(|_| target.to_path_buf());
2281 let root_canon = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
2282
2283 if let Ok(rel) = target_canon.strip_prefix(&root_canon) {
2285 if !rel.as_os_str().is_empty() {
2286 return rel.to_string_lossy().replace('\\', "/");
2287 }
2288 }
2289
2290 if target_canon != root_canon {
2292 if let (Some(root_parent), Some(target_parent)) =
2293 (root_canon.parent(), target_canon.parent())
2294 {
2295 if root_parent == target_parent {
2296 if let Some(file_name) = target_canon.file_name() {
2297 let rel = Path::new("..").join(file_name);
2298 return rel.to_string_lossy().replace('\\', "/");
2299 }
2300 }
2301 }
2302 }
2303
2304 target_canon.to_string_lossy().replace('\\', "/")
2306}
2307
2308pub fn is_linked_worktree(root: &Path) -> bool {
2310 let git_dir_out = std::process::Command::new("git")
2311 .args(["rev-parse", "--git-dir"])
2312 .current_dir(root)
2313 .output();
2314 let common_dir_out = std::process::Command::new("git")
2315 .args(["rev-parse", "--git-common-dir"])
2316 .current_dir(root)
2317 .output();
2318 match (git_dir_out, common_dir_out) {
2319 (Ok(gd), Ok(cd)) if gd.status.success() && cd.status.success() => {
2320 let gd_str = String::from_utf8_lossy(&gd.stdout).trim().to_string();
2321 let cd_str = String::from_utf8_lossy(&cd.stdout).trim().to_string();
2322 if gd_str == cd_str {
2323 return false;
2324 }
2325 let gd_path = if Path::new(&gd_str).is_absolute() {
2326 PathBuf::from(&gd_str)
2327 } else {
2328 root.join(&gd_str)
2329 };
2330 let cd_path = if Path::new(&cd_str).is_absolute() {
2331 PathBuf::from(&cd_str)
2332 } else {
2333 root.join(&cd_str)
2334 };
2335 let gd_canon = gd_path.canonicalize().unwrap_or(gd_path);
2336 let cd_canon = cd_path.canonicalize().unwrap_or(cd_path);
2337 gd_canon != cd_canon
2338 }
2339 _ => false,
2340 }
2341}
2342
2343pub fn has_wt_component(path: &Path) -> bool {
2345 path.components().any(|c| c.as_os_str() == ".wt")
2346}
2347
2348pub fn is_worktree_clean(wt_path: &Path) -> bool {
2351 let out = std::process::Command::new("git")
2352 .arg("--no-optional-locks")
2353 .arg("-C")
2354 .arg(wt_path.as_os_str())
2355 .args(["status", "--porcelain", "-u"])
2356 .output();
2357 match out {
2358 Ok(o) if o.status.success() => {
2359 let stdout = String::from_utf8_lossy(&o.stdout);
2360 for line in stdout.lines() {
2361 let trimmed = line.trim();
2362 if trimmed.is_empty() {
2363 continue;
2364 }
2365 if line.len() < 3 {
2366 return false;
2367 }
2368 let mut path_part = line[3..].trim();
2369 if let Some((_, new_path)) = path_part.split_once(" -> ") {
2370 path_part = new_path.trim();
2371 }
2372 let unquoted = path_part
2373 .strip_prefix('"')
2374 .and_then(|p| p.strip_suffix('"'))
2375 .unwrap_or(path_part);
2376 if Path::new(unquoted).file_name() != Some(std::ffi::OsStr::new(".DS_Store")) {
2377 return false;
2378 }
2379 }
2380 true
2381 }
2382 _ => false,
2383 }
2384}
2385
2386pub fn report_other_worktrees(root: &Path) {
2390 if is_linked_worktree(root) {
2393 return;
2394 }
2395
2396 let worktrees = parse_worktree_list(root);
2397 let root_canon = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
2398 let main_canon = worktrees
2399 .first()
2400 .map(|wt| wt.path.canonicalize().unwrap_or_else(|_| wt.path.clone()));
2401
2402 let mut other_count = 0;
2403 let mut other_bytes = 0;
2404
2405 for (idx, wt) in worktrees.into_iter().enumerate() {
2406 if idx == 0 {
2408 continue;
2409 }
2410 if wt.is_bare {
2411 continue;
2412 }
2413 if !wt.path.exists() {
2414 continue;
2415 }
2416
2417 let wt_canon = wt.path.canonicalize().unwrap_or_else(|_| wt.path.clone());
2418 if wt_canon == root_canon || wt.path == root {
2420 continue;
2421 }
2422 if Some(&wt_canon) == main_canon.as_ref() {
2423 continue;
2424 }
2425 if has_wt_component(&wt.path)
2427 || has_wt_component(&wt_canon)
2428 || is_session_worktree(root, &wt.path)
2429 {
2430 continue;
2431 }
2432
2433 let is_merged = if let Some(ref branch) = wt.branch {
2435 is_branch_merged(root, branch)
2436 } else if let Some(ref sha) = wt.head_sha {
2437 is_commit_merged(root, sha)
2438 } else {
2439 false
2440 };
2441
2442 if !is_merged {
2443 continue;
2444 }
2445
2446 if !is_worktree_clean(&wt.path) {
2448 continue;
2449 }
2450
2451 let size = dir_size(&wt.path);
2452 let path_str = display_worktree_path(&wt.path, root);
2453 let branch_label = wt.branch.as_deref().unwrap_or_else(|| {
2454 wt.head_sha
2455 .as_deref()
2456 .map(|s| &s[..s.len().min(7)])
2457 .unwrap_or("detached")
2458 });
2459
2460 println!(
2461 "merged worktree {path_str} ({branch_label}, {}): git worktree remove {path_str}",
2462 format_size(size)
2463 );
2464
2465 other_count += 1;
2466 other_bytes += size;
2467 }
2468
2469 if other_count > 0 {
2470 println!(
2471 "{other_count} other worktrees are merged and clean ({}); remove them with the commands above",
2472 format_size(other_bytes)
2473 );
2474 }
2475}
2476
2477struct CleanLockGuard(PathBuf);
2478
2479impl Drop for CleanLockGuard {
2480 fn drop(&mut self) {
2481 let _ = std::fs::remove_file(&self.0);
2482 }
2483}
2484
2485enum LockOutcome {
2486 Acquired(CleanLockGuard),
2487 AlreadyRunning,
2488 Error(String),
2489}
2490
2491fn acquire_clean_lock(root: &Path) -> LockOutcome {
2492 use std::io::Write;
2493 let wt_dir = root.join(".wt");
2494 if let Err(e) = std::fs::create_dir_all(&wt_dir) {
2495 return LockOutcome::Error(format!("{}: {e}", wt_dir.display()));
2496 }
2497 let lock_path = wt_dir.join("clean.lock");
2498 let pid_str = format!("{}\n", std::process::id());
2499
2500 match std::fs::OpenOptions::new()
2501 .write(true)
2502 .create_new(true)
2503 .open(&lock_path)
2504 {
2505 Ok(mut f) => {
2506 if let Err(e) = f.write_all(pid_str.as_bytes()) {
2507 let _ = std::fs::remove_file(&lock_path);
2508 return LockOutcome::Error(format!("{}: {e}", lock_path.display()));
2509 }
2510 LockOutcome::Acquired(CleanLockGuard(lock_path))
2511 }
2512 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
2513 let contents = match std::fs::read_to_string(&lock_path) {
2514 Ok(c) => c,
2515 Err(read_err) => {
2516 return LockOutcome::Error(format!("{}: {read_err}", lock_path.display()));
2517 }
2518 };
2519 let old_pid: i64 = match contents.trim().parse() {
2520 Ok(p) => p,
2521 Err(parse_err) => {
2522 return LockOutcome::Error(format!(
2523 "{}: invalid pid: {parse_err}",
2524 lock_path.display()
2525 ));
2526 }
2527 };
2528 if is_pid_alive(old_pid) {
2529 return LockOutcome::AlreadyRunning;
2530 }
2531 eprintln!(
2532 "replacing stale {} from dead pid {old_pid}",
2533 lock_path.display()
2534 );
2535 if let Err(rm_err) = std::fs::remove_file(&lock_path) {
2536 return LockOutcome::Error(format!("{}: {rm_err}", lock_path.display()));
2537 }
2538 match std::fs::OpenOptions::new()
2539 .write(true)
2540 .create_new(true)
2541 .open(&lock_path)
2542 {
2543 Ok(mut f) => {
2544 if let Err(write_err) = f.write_all(pid_str.as_bytes()) {
2545 let _ = std::fs::remove_file(&lock_path);
2546 return LockOutcome::Error(format!("{}: {write_err}", lock_path.display()));
2547 }
2548 LockOutcome::Acquired(CleanLockGuard(lock_path))
2549 }
2550 Err(open_err) => LockOutcome::Error(format!("{}: {open_err}", lock_path.display())),
2551 }
2552 }
2553 Err(e) => LockOutcome::Error(format!("{}: {e}", lock_path.display())),
2554 }
2555}
2556
2557pub fn run(args: &crate::cli::CleanArgs) -> i32 {
2559 if (args.quiet || args.skip.is_some()) && (args.all || args.dry_run) {
2560 eprintln!("error: --quiet and --skip cannot be combined with --all or --dry-run");
2561 return 2;
2562 }
2563
2564 let repos = if args.all {
2565 let tidy_res = if args.dry_run {
2566 crate::registry::missing_registered()
2567 } else {
2568 crate::registry::prune_missing()
2569 };
2570 match tidy_res {
2571 Ok(removed) if !removed.is_empty() => {
2572 let verb = if args.dry_run {
2573 "would forget"
2574 } else {
2575 "forgot"
2576 };
2577 let list = removed
2578 .iter()
2579 .map(|p| p.display().to_string())
2580 .collect::<Vec<_>>()
2581 .join(", ");
2582 println!(
2583 "{verb} {} repositories that no longer exist: {list}",
2584 removed.len()
2585 );
2586 }
2587 Ok(_) => {}
2588 Err(err) => {
2589 let path = crate::registry::state_dir()
2590 .map(|d| d.join("repos").display().to_string())
2591 .unwrap_or_default();
2592 eprintln!("error: could not tidy the repository registry {path}: {err}");
2593 }
2594 }
2595 crate::registry::registered()
2596 } else {
2597 match find_repo_root() {
2598 Ok(root) => vec![root],
2599 Err(e) => {
2600 eprintln!("error: {e}");
2601 return 2;
2602 }
2603 }
2604 };
2605
2606 let _lock_guard = if args.quiet {
2607 let Some(root) = repos.first() else {
2608 eprintln!("error: blyte clean --quiet found no repository to clean");
2609 return 1;
2610 };
2611 match acquire_clean_lock(root) {
2612 LockOutcome::Acquired(guard) => Some(guard),
2613 LockOutcome::AlreadyRunning => return 0,
2614 LockOutcome::Error(e) => {
2615 eprintln!("error: {e}");
2616 return 1;
2617 }
2618 }
2619 } else {
2620 None
2621 };
2622
2623 let mut total_freed = 0;
2624 let mut had_errors = false;
2625 for repo in &repos {
2626 let stats = clean_repo(
2627 repo,
2628 args.older_than,
2629 args.dry_run,
2630 args.skip.as_deref(),
2631 args.quiet,
2632 );
2633 total_freed += stats.freed_bytes;
2634 if stats.had_errors {
2635 had_errors = true;
2636 }
2637 }
2638
2639 if !args.quiet {
2640 if args.dry_run {
2641 println!("would free {}", format_size(total_freed));
2642 } else {
2643 println!("freed {}", format_size(total_freed));
2644 }
2645 }
2646
2647 if had_errors {
2648 1
2649 } else {
2650 0
2651 }
2652}
2653
2654fn delete_wip_branch_strict(root: &Path, branch_name: &str) -> Result<(), String> {
2655 let del_out = std::process::Command::new("git")
2656 .args(["branch", "-D", branch_name])
2657 .current_dir(root)
2658 .output()
2659 .map_err(|e| format!("git branch -D {branch_name}: {e}"))?;
2660 if !del_out.status.success() {
2661 return Err(format!(
2662 "git branch -D {branch_name}: {}",
2663 String::from_utf8_lossy(&del_out.stderr).trim()
2664 ));
2665 }
2666 Ok(())
2667}
2668
2669pub fn remove_finished_run(root: &Path, id: &str) -> Result<Option<String>, String> {
2672 let wt_path = root.join(".wt").join(id);
2673 let branch_name = format!("wip/{id}");
2674 let mut ctx = CleanContext::new(root);
2675
2676 if wt_path.exists() {
2677 let reason = match ctx.check_removable(id, u64::MAX) {
2678 Ok(
2679 r @ (RemovalReason::Merged
2680 | RemovalReason::MergedInto(_)
2681 | RemovalReason::MergedThrough(_)
2682 | RemovalReason::NoChanges),
2683 ) => r,
2684 Ok(
2685 RemovalReason::SessionMerged(_)
2686 | RemovalReason::Verdict(_)
2687 | RemovalReason::OlderThan(_)
2688 | RemovalReason::ResearchReport
2689 | RemovalReason::ResearchReportInWorktree
2690 | RemovalReason::ResearchEndedWithoutReport(_)
2691 | RemovalReason::ResearchStoppedWithoutSummary(_),
2692 )
2693 | Err(_) => return Ok(None),
2694 };
2695 if has_uncommitted_changes(&wt_path) {
2696 return Ok(None);
2697 }
2698
2699 let wt_rel = format!(".wt/{id}");
2700 let rm_out = std::process::Command::new("git")
2701 .args(["worktree", "remove", &wt_rel])
2702 .current_dir(root)
2703 .output()
2704 .map_err(|e| format!("git worktree remove {wt_rel}: {e}"))?;
2705 if !rm_out.status.success() {
2706 return Err(format!(
2707 "git worktree remove {wt_rel}: {}",
2708 String::from_utf8_lossy(&rm_out.stderr).trim()
2709 ));
2710 }
2711
2712 if ctx.get_branch_tip(&branch_name).is_some() {
2713 delete_wip_branch_strict(root, &branch_name)?;
2714 }
2715
2716 return Ok(Some(reason.to_string()));
2717 }
2718
2719 if ctx.get_branch_tip(&branch_name).is_some() {
2720 if !is_branch_merged(root, &branch_name) {
2721 return Ok(None);
2722 }
2723 let reason = ctx
2724 .check_run_merged(id)
2725 .unwrap_or(RemovalReason::Merged)
2726 .to_string();
2727 delete_wip_branch_strict(root, &branch_name)?;
2728 return Ok(Some(reason));
2729 }
2730
2731 Ok(None)
2732}
2733
2734pub fn spawn_background_clean(root: &Path, skip_id: Option<&str>) {
2736 let res: Result<(), std::io::Error> = (|| {
2737 let wt_dir = root.join(".wt");
2738 std::fs::create_dir_all(&wt_dir)?;
2739 let log_file = std::fs::OpenOptions::new()
2740 .create(true)
2741 .append(true)
2742 .open(wt_dir.join("clean.log"))?;
2743 let stderr_file = log_file.try_clone()?;
2744 let exe = std::env::current_exe()?;
2745 let mut cmd = std::process::Command::new(exe);
2746 cmd.arg("clean").arg("--quiet");
2747 if let Some(id) = skip_id {
2748 cmd.arg("--skip").arg(id);
2749 }
2750 cmd.current_dir(root)
2751 .stdin(std::process::Stdio::null())
2752 .stdout(std::process::Stdio::from(log_file))
2753 .stderr(std::process::Stdio::from(stderr_file));
2754 let _child = cmd.spawn()?;
2755 Ok(())
2756 })();
2757 if let Err(e) = res {
2758 eprintln!("warning: could not start the background clean: {e}");
2759 }
2760}
2761
2762pub fn clean_on_review(root: &Path, id: &str) {
2767 let wt_path = root.join(".wt").join(id);
2768 if !wt_path.exists() {
2769 spawn_background_clean(root, Some(id));
2770 return;
2771 }
2772
2773 let mut ctx = CleanContext::new(root);
2774 let branch_name = format!("wip/{id}");
2775 let branch_exists = ctx.get_branch_tip(&branch_name).is_some();
2776
2777 let verdict_path = root.join(".wt").join(format!("{id}.verdict.json"));
2778 let verdict_str = std::fs::read_to_string(&verdict_path)
2779 .ok()
2780 .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
2781 .and_then(|v| {
2782 v.get("verdict")
2783 .and_then(|s| s.as_str())
2784 .map(|s| s.to_string())
2785 })
2786 .unwrap_or_default();
2787
2788 let is_res = ctx.is_research_run(id);
2789 let removal_reason = match ctx.check_removable(id, 14) {
2790 Ok(r) if is_res || !has_uncommitted_changes(&wt_path) => Some(r),
2791 _ => None,
2792 };
2793
2794 let Some(removal_reason) = removal_reason else {
2795 if verdict_str == "accepted" || verdict_str == "fixed" {
2796 println!("worktree .wt/{id} kept until {branch_name} is merged");
2797 }
2798 spawn_background_clean(root, Some(id));
2799 return;
2800 };
2801
2802 if removal_reason == RemovalReason::ResearchReportInWorktree {
2803 let src = wt_path.join("report.md");
2804 let dst = root.join(".wt").join(format!("{id}.report.md"));
2805 if let Err(err) = std::fs::copy(&src, &dst) {
2806 eprintln!(
2807 "error: could not copy {} to {}: {err}",
2808 src.display(),
2809 dst.display()
2810 );
2811 spawn_background_clean(root, Some(id));
2812 return;
2813 }
2814 }
2815
2816 let removed_ok = if is_res {
2817 std::fs::remove_dir_all(&wt_path).is_ok()
2818 } else {
2819 let rm_out = std::process::Command::new("git")
2820 .args(["worktree", "remove", wt_path.to_str().unwrap_or("")])
2821 .current_dir(root)
2822 .output();
2823 let _ = std::process::Command::new("git")
2824 .args(["worktree", "prune"])
2825 .current_dir(root)
2826 .output();
2827 rm_out.map(|o| o.status.success()).unwrap_or(false)
2828 };
2829
2830 if !removed_ok {
2831 if verdict_str == "accepted" || verdict_str == "fixed" {
2832 println!("worktree .wt/{id} kept until {branch_name} is merged");
2833 }
2834 spawn_background_clean(root, Some(id));
2835 return;
2836 }
2837
2838 if branch_exists {
2839 let is_merged = ctx.check_run_merged(id).is_some();
2840 if is_merged {
2841 let del_out = std::process::Command::new("git")
2842 .args(["branch", "-D", &branch_name])
2843 .current_dir(root)
2844 .output();
2845 if del_out.map(|o| o.status.success()).unwrap_or(false) {
2846 ctx.wip_branch_tips.remove(&branch_name);
2847 println!("removed .wt/{id}; branch {branch_name} deleted");
2848 } else {
2849 println!("removed .wt/{id}; branch {branch_name} kept");
2850 }
2851 } else {
2852 println!("removed .wt/{id}; branch {branch_name} kept");
2853 }
2854 } else {
2855 println!("removed .wt/{id}");
2856 }
2857
2858 spawn_background_clean(root, Some(id));
2859}