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