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