1use camino::{Utf8Path, Utf8PathBuf};
13use serde::Serialize;
14
15use crate::branches::{Branch, Class, FOR_EACH_REF_FORMAT, merged_request_for};
16use crate::cli::worktree::{WorktreeAction, WorktreeArgs};
17use crate::detect::Forge;
18use crate::diagnostic::{Diagnostic, Reason};
19use crate::error::RkError;
20use crate::maintenance;
21use crate::output::Output;
22use crate::setup::context::resolve_cli;
23use crate::worktree::{Layout, Worktree, WtClass, classify, derived_path, matches_grammar};
24
25const OPERATOR_LINE: &str = "Removing a worktree and deleting its branch are the operator's action: an agent reading this states the command and waits to be asked.";
29
30pub fn run(args: &WorktreeArgs) -> Result<(), RkError> {
39 match &args.action {
40 WorktreeAction::List { target, json } => list(target, Output::new(*json)),
41 WorktreeAction::Add {
42 branch,
43 target,
44 base,
45 apply,
46 json,
47 } => add(target, branch, base.as_deref(), *apply, Output::new(*json)),
48 WorktreeAction::Prune {
49 target,
50 repo,
51 forge,
52 verify,
53 apply,
54 quiet,
55 json,
56 } => prune(
57 target,
58 repo.as_deref(),
59 forge.as_deref(),
60 *verify,
61 *apply,
62 *quiet,
63 Output::new(*json),
64 ),
65 }
66}
67
68fn inventory(target: &Utf8Path) -> Result<Vec<Worktree>, RkError> {
74 if !target.is_dir() {
75 return Err(RkError::missing(
76 Diagnostic::new(
77 Reason::TargetNotFound,
78 format!("target {target} is not a directory"),
79 )
80 .expected("an existing repository to read"),
81 ));
82 }
83 let listed = git(target, &["worktree", "list", "--porcelain", "-z"])?;
84 if !listed.status.success() {
85 return Err(RkError::refusal(
86 Diagnostic::new(
87 Reason::PrerequisiteUnmet,
88 format!("target {target} is not a git repository"),
89 )
90 .expected("a repository whose worktrees git can list"),
91 ));
92 }
93 crate::worktree::parse_worktrees(&listed.stdout).map_err(|detail| {
94 RkError::refusal(
95 Diagnostic::new(
96 Reason::PrerequisiteUnmet,
97 format!("the worktree inventory cannot be trusted: {detail}"),
98 )
99 .expected("a worktree inventory this binary can parse whole")
100 .target_state("unchanged"),
101 )
102 })
103}
104
105fn layout_of(worktrees: &[Worktree]) -> Result<Layout, RkError> {
107 Layout::of(worktrees).map_err(|detail| {
108 RkError::refusal(
109 Diagnostic::new(Reason::PrerequisiteUnmet, detail)
110 .expected("a main worktree the sibling convention composes with"),
111 )
112 })
113}
114
115pub(crate) fn main_checkout(target: &Utf8Path) -> Result<Utf8PathBuf, RkError> {
126 let worktrees = inventory(target)?;
127 Ok(layout_of(&worktrees)?.main)
128}
129
130pub(crate) fn seat_of(target: &Utf8Path, branch: &str) -> Result<Option<Utf8PathBuf>, RkError> {
140 Ok(inventory(target)?
141 .into_iter()
142 .find(|worktree| worktree.branch.as_deref() == Some(branch))
143 .map(|worktree| worktree.path))
144}
145
146fn seats(target: &Utf8Path) -> Vec<Utf8PathBuf> {
151 let toplevel = |output: std::io::Result<std::process::Output>| {
152 output
153 .ok()
154 .filter(|answer| answer.status.success())
155 .map(|answer| String::from_utf8_lossy(&answer.stdout).trim().to_owned())
156 .filter(|path| !path.is_empty())
157 .map(Utf8PathBuf::from)
158 };
159 let scrubbed = || {
160 let mut command = std::process::Command::new(crate::probes::git_bin());
161 for var in maintenance::GIT_HOOK_VARS {
162 command.env_remove(var);
163 }
164 command
165 };
166 let mut seats = Vec::new();
167 if let Some(seat) = toplevel(scrubbed().args(["rev-parse", "--show-toplevel"]).output()) {
168 seats.push(seat);
169 }
170 if let Some(seat) = toplevel(
171 scrubbed()
172 .arg("-C")
173 .arg(target.as_std_path())
174 .args(["rev-parse", "--show-toplevel"])
175 .output(),
176 ) && !seats.contains(&seat)
177 {
178 seats.push(seat);
179 }
180 seats
181}
182
183fn is_dirty(path: &Utf8Path) -> bool {
186 git(path, &["status", "--porcelain"]).map_or(true, |probed| {
187 !probed.status.success() || !probed.stdout.is_empty()
188 })
189}
190
191fn branch_inventory(target: &Utf8Path) -> Result<Vec<Branch>, RkError> {
194 let listed = git(
195 target,
196 &[
197 "for-each-ref",
198 "refs/heads",
199 "--format",
200 FOR_EACH_REF_FORMAT,
201 ],
202 )?;
203 if !listed.status.success() {
204 return Err(RkError::refusal(
205 Diagnostic::new(
206 Reason::PrerequisiteUnmet,
207 format!("target {target} is not a git repository"),
208 )
209 .expected("a repository whose branches git can list"),
210 ));
211 }
212 Ok(crate::branches::parse_branches(&String::from_utf8_lossy(
213 &listed.stdout,
214 )))
215}
216
217#[derive(Debug, Serialize)]
222struct ListRow {
223 path: String,
225 #[serde(skip_serializing_if = "Option::is_none")]
227 branch: Option<String>,
228 head: String,
230 kind: &'static str,
232 state: &'static str,
235 canonical: bool,
237}
238
239#[derive(Debug, Serialize)]
241struct ListReport {
242 schema: &'static str,
244 worktrees: Vec<ListRow>,
246 next: Vec<String>,
248}
249
250fn list(target: &Utf8Path, out: Output) -> Result<(), RkError> {
252 let worktrees = inventory(target)?;
253 let layout = layout_of(&worktrees)?;
254 let rows: Vec<ListRow> = worktrees
255 .iter()
256 .enumerate()
257 .map(|(index, worktree)| {
258 let state = if worktree.locked.is_some() {
262 "locked"
263 } else if worktree.prunable.is_some() {
264 "missing"
265 } else if worktree.branch.is_none() {
266 "detached"
267 } else if is_dirty(&worktree.path) {
268 "dirty"
269 } else {
270 "clean"
271 };
272 let canonical = index == 0
273 || worktree
274 .branch
275 .as_deref()
276 .is_none_or(|branch| derived_path(&layout, branch) == worktree.path);
277 ListRow {
278 path: worktree.path.to_string(),
279 branch: worktree.branch.clone(),
280 head: worktree.head.clone(),
281 kind: if index == 0 { "main" } else { "linked" },
282 state,
283 canonical,
284 }
285 })
286 .collect();
287 let next = vec![
288 "rk worktree add <branch> creates or adopts a branch's worktree".to_owned(),
289 "rk worktree prune reports the worktrees a squash merge retired".to_owned(),
290 ];
291 out.result_line(format!(
292 "{} worktree{} of {}:",
293 rows.len(),
294 if rows.len() == 1 { "" } else { "s" },
295 layout.main
296 ));
297 let width = rows.iter().map(|row| row.path.len()).max().unwrap_or(0);
298 for row in &rows {
299 let head = row.head.get(..8).unwrap_or(&row.head);
300 let mut line = format!(
301 " {:width$} {head} {} {}",
302 row.path,
303 row.branch.as_deref().unwrap_or("(detached)"),
304 row.state
305 );
306 if !row.canonical
307 && let Some(branch) = &row.branch
308 {
309 use std::fmt::Write as _;
310 let expected = derived_path(&layout, branch);
311 let _ = write!(
312 line,
313 " off-path: expected ../{}",
314 expected.file_name().unwrap_or_default()
315 );
316 }
317 out.result_line(line);
318 }
319 out.next(&next);
320 out.emit(&ListReport {
321 schema: "rk.worktree-list/1",
322 worktrees: rows,
323 next,
324 })
325}
326
327#[derive(Debug, Serialize)]
332struct AddReport {
333 schema: &'static str,
335 mode: &'static str,
337 branch: String,
339 path: String,
341 created: &'static str,
345 source: &'static str,
348 #[serde(skip_serializing_if = "Option::is_none")]
350 base: Option<String>,
351 #[serde(skip_serializing_if = "Option::is_none")]
353 upstream: Option<String>,
354 #[serde(skip_serializing_if = "Option::is_none")]
356 detail: Option<String>,
357 next: Vec<String>,
359}
360
361pub(crate) struct Source {
363 pub(crate) kind: &'static str,
365 pub(crate) created: &'static str,
367 pub(crate) base: Option<String>,
369 pub(crate) upstream: Option<String>,
371 pub(crate) command: Vec<String>,
373}
374
375pub(crate) enum Seat {
377 Satisfied {
379 path: Utf8PathBuf,
381 },
382 Fresh {
384 path: Utf8PathBuf,
386 source: Source,
388 detail: Option<String>,
390 },
391}
392
393pub(crate) fn plan_seat(
405 target: &Utf8Path,
406 branch: &str,
407 base: Option<&str>,
408 apply: bool,
409) -> Result<Seat, RkError> {
410 let trunk = crate::config::trunk_of(target.as_std_path())?;
411 let worktrees = inventory(target)?;
412 let layout = layout_of(&worktrees)?;
413
414 if !matches_grammar(branch) {
418 return Err(RkError::Usage(format!(
419 "branch '{branch}' is none of the three forms — <type>/<slug>, <issue-id>-<slug>, or release/<line> — the landed grammar admits"
420 )));
421 }
422 let checked = git(target, &["check-ref-format", "--branch", branch])?;
423 if !checked.status.success() {
424 return Err(RkError::Usage(format!(
425 "git refuses the branch name '{branch}': {}",
426 last_line(&checked.stderr)
427 )));
428 }
429 if branch == trunk {
430 return Err(RkError::refusal(
431 Diagnostic::new(
432 Reason::PrerequisiteUnmet,
433 format!("{trunk} takes no worktree; the main checkout is its seat"),
434 )
435 .expected("a short-lived branch to seat")
436 .target_state("unchanged"),
437 ));
438 }
439 if let Some(base) = base
440 && base.starts_with('-')
441 {
442 return Err(RkError::Usage(format!(
443 "--base '{base}' is option-shaped; pass a commit-ish"
444 )));
445 }
446 let path = derived_path(&layout, branch);
447
448 let registered = worktrees
451 .iter()
452 .find(|worktree| worktree.branch.as_deref() == Some(branch));
453 if let Some(seat) = registered {
454 return judge_registered(seat, branch, &path, &layout.main);
455 }
456 if path.exists() {
457 let occupant = worktrees
458 .iter()
459 .find(|worktree| worktree.path == path)
460 .and_then(|worktree| worktree.branch.clone())
461 .map_or_else(
462 || "a directory this repository does not register".to_owned(),
463 |other| format!("the worktree of branch {other}"),
464 );
465 return Err(RkError::refusal(
466 Diagnostic::new(
467 Reason::StateDrift,
468 format!(
469 "{path} already exists as {occupant}; flattening is not injective and nothing is suffixed silently"
470 ),
471 )
472 .expected("the derived path free, or registered to this branch")
473 .target_state("unchanged"),
474 ));
475 }
476
477 let mut detail = None;
482 if apply {
483 let fetched = git(target, &["fetch", "origin"])?;
484 if !fetched.status.success() {
485 detail = Some(format!(
486 "the fetch failed ({}); the run proceeded on local refs",
487 last_line(&fetched.stderr)
488 ));
489 }
490 }
491 let source = resolve_source(target, branch, base, &path)?;
492 Ok(Seat::Fresh {
493 path,
494 source,
495 detail,
496 })
497}
498
499fn judge_registered(
503 seat: &Worktree,
504 branch: &str,
505 path: &Utf8Path,
506 main: &Utf8Path,
507) -> Result<Seat, RkError> {
508 let trunk = crate::config::trunk_of(main.as_std_path())?;
509 if seat.path == path {
510 if seat.prunable.is_some() || !path.is_dir() {
518 let recovery = if seat.locked.is_some() {
519 format!(
520 "the record is locked, which prune keeps unconditionally: git worktree repair recovers a moved directory, or git worktree unlock {path} — for a lock you own — then rk worktree prune --apply clears it"
521 )
522 } else {
523 "rk worktree prune --apply clears the stale record, then re-run; git worktree repair recovers a moved directory instead".to_owned()
524 };
525 return Err(RkError::refusal(
526 Diagnostic::new(
527 Reason::StateDrift,
528 format!("{path} is registered to {branch} and its directory is missing"),
529 )
530 .expected("the canonical worktree standing, or its stale record cleared")
531 .action(recovery)
532 .target_state("unchanged"),
533 ));
534 }
535 return Ok(Seat::Satisfied {
536 path: path.to_owned(),
537 });
538 }
539 let recovery = if seat.path == main {
543 format!("git switch {trunk} there, then re-run")
544 } else {
545 format!("git worktree move {} {path}", seat.path)
546 };
547 Err(RkError::refusal(
548 Diagnostic::new(
549 Reason::StateDrift,
550 format!(
551 "branch {branch} is checked out at {}, and one branch has one seat",
552 seat.path
553 ),
554 )
555 .expected("the branch free, or already at its derived path")
556 .action(recovery)
557 .target_state("unchanged"),
558 ))
559}
560
561pub(crate) fn create_seat(target: &Utf8Path, source: &Source) -> Result<(), RkError> {
567 let argv: Vec<&str> = source.command.iter().map(String::as_str).collect();
568 let created = git(target, &argv)?;
569 if created.status.success() {
570 return Ok(());
571 }
572 Err(RkError::subprocess(
573 Diagnostic::new(
574 Reason::SubprocessFailed,
575 format!("git worktree add refused: {}", last_line(&created.stderr)),
576 )
577 .expected("the worktree created at the derived path")
578 .target_state("unchanged"),
579 ))
580}
581
582fn add(
584 target: &Utf8Path,
585 branch: &str,
586 base: Option<&str>,
587 apply: bool,
588 out: Output,
589) -> Result<(), RkError> {
590 let (path, source, detail) = match plan_seat(target, branch, base, apply)? {
591 Seat::Satisfied { path } => return report_satisfied(out, branch, &path, apply),
592 Seat::Fresh {
593 path,
594 source,
595 detail,
596 } => (path, source, detail),
597 };
598
599 if !apply {
600 out.result_line(format!(
601 "branch: {branch} ({})",
602 match source.kind {
603 "adopted" => "existing, adopted".to_owned(),
604 "remote" => format!(
605 "remote, from {}",
606 source.upstream.as_deref().unwrap_or("origin")
607 ),
608 _ => format!("new, from {}", source.base.as_deref().unwrap_or("?")),
609 }
610 ));
611 out.result_line(format!(
612 "path: ../{}",
613 path.file_name().unwrap_or_default()
614 ));
615 if let Some(base) = &source.base {
616 out.result_line(format!("base: {base}"));
617 }
618 out.result_line(format!("would run: git {}", source.command.join(" ")));
619 let base_flag = base.map_or_else(String::new, |base| format!(" --base {base}"));
620 let next = vec![format!(
621 "rk worktree add {branch}{base_flag} --target {target} --apply creates it; the apply refreshes the remote refs and re-resolves"
622 )];
623 out.next(&next);
624 return out.emit(&AddReport {
625 schema: "rk.worktree-add/1",
626 mode: "preview",
627 branch: branch.to_owned(),
628 path: path.to_string(),
629 created: source.created,
630 source: source.kind,
631 base: source.base,
632 upstream: source.upstream,
633 detail: Some(
634 "a preview decides from the local refs as they stand; apply refreshes and re-resolves"
635 .to_owned(),
636 ),
637 next,
638 });
639 }
640
641 create_seat(target, &source)?;
642 out.result_line(&path);
643 let next = vec![
644 format!("cd {path}"),
645 "rk worktree list reports every seat".to_owned(),
646 ];
647 out.next(&next);
648 out.emit(&AddReport {
649 schema: "rk.worktree-add/1",
650 mode: "apply",
651 branch: branch.to_owned(),
652 path: path.to_string(),
653 created: source.created,
654 source: source.kind,
655 base: source.base,
656 upstream: source.upstream,
657 detail,
658 next,
659 })
660}
661
662fn report_satisfied(
664 out: Output,
665 branch: &str,
666 path: &Utf8Path,
667 apply: bool,
668) -> Result<(), RkError> {
669 out.result_line(format!("{path} already seats {branch}; nothing to create"));
670 let next = vec![format!("cd {path}")];
671 out.next(&next);
672 out.emit(&AddReport {
673 schema: "rk.worktree-add/1",
674 mode: if apply { "apply" } else { "preview" },
675 branch: branch.to_owned(),
676 path: path.to_string(),
677 created: "nothing",
678 source: "adopted",
679 base: None,
680 upstream: None,
681 detail: None,
682 next,
683 })
684}
685
686fn resolve_source(
695 target: &Utf8Path,
696 branch: &str,
697 base: Option<&str>,
698 path: &Utf8Path,
699) -> Result<Source, RkError> {
700 let trunk = crate::config::trunk_of(target.as_std_path())?;
701 let resolve = |name: &str| -> Result<Option<String>, RkError> {
702 let resolved = git(
703 target,
704 &[
705 "rev-parse",
706 "--verify",
707 "--quiet",
708 "--end-of-options",
709 &format!("{name}^{{commit}}"),
710 ],
711 )?;
712 Ok(resolved
713 .status
714 .success()
715 .then(|| String::from_utf8_lossy(&resolved.stdout).trim().to_owned()))
716 };
717
718 if resolve(&format!("refs/heads/{branch}"))?.is_some() {
721 return Ok(Source {
722 kind: "adopted",
723 created: "worktree",
724 base: None,
725 upstream: None,
726 command: vec![
727 "worktree".into(),
728 "add".into(),
729 path.to_string(),
730 branch.to_owned(),
731 ],
732 });
733 }
734
735 let remote_ref = format!("refs/remotes/origin/{branch}");
738 if resolve(&remote_ref)?.is_some() {
739 return Ok(Source {
740 kind: "remote",
741 created: "branch",
742 base: Some(format!("origin/{branch}")),
743 upstream: Some(format!("origin/{branch}")),
744 command: vec![
745 "worktree".into(),
746 "add".into(),
747 "--track".into(),
748 "-b".into(),
749 branch.to_owned(),
750 path.to_string(),
751 remote_ref,
752 ],
753 });
754 }
755
756 if branch.starts_with(crate::branches::PROTECTED_PREFIX) && base.is_none() {
760 return Err(RkError::refusal(
761 Diagnostic::new(
762 Reason::PrerequisiteUnmet,
763 format!(
764 "release line {branch} takes an explicit --base; a line is cut from a tag, never the tip"
765 ),
766 )
767 .expected("--base \"v<version>\" naming the tag the line patches")
768 .target_state("unchanged"),
769 ));
770 }
771 let (kind, shown) = base.map_or_else(
772 || ("trunk", format!("origin/{trunk}")),
773 |base| ("base", base.to_owned()),
774 );
775 let resolved = match resolve(&shown)? {
776 Some(oid) => Some(oid),
777 None if kind == "trunk" => resolve(&trunk)?,
779 None => None,
780 };
781 let oid = resolved.ok_or_else(|| {
782 RkError::refusal(
783 Diagnostic::new(
784 Reason::PrerequisiteUnmet,
785 format!("{shown} does not resolve to a commit"),
786 )
787 .expected("a commit-ish the new branch can start from")
788 .target_state("unchanged"),
789 )
790 })?;
791 Ok(Source {
792 kind,
793 created: "branch",
794 base: Some(shown),
795 upstream: None,
796 command: vec![
797 "worktree".into(),
798 "add".into(),
799 path.to_string(),
800 "-b".into(),
801 branch.to_owned(),
802 oid,
803 ],
804 })
805}
806
807#[derive(Debug, Serialize)]
812struct PruneRow {
813 path: String,
815 #[serde(skip_serializing_if = "Option::is_none")]
817 branch: Option<String>,
818 #[serde(skip_serializing_if = "Option::is_none")]
820 tip: Option<String>,
821 status: &'static str,
824 #[serde(skip_serializing_if = "Option::is_none")]
827 proof: Option<String>,
828 #[serde(skip_serializing_if = "Option::is_none")]
830 proof_kind: Option<&'static str>,
831 #[serde(skip_serializing_if = "Option::is_none")]
833 detail: Option<String>,
834}
835
836impl PruneRow {
837 fn describe(&self) -> String {
839 match self.status {
840 "kept" => format!("kept: {}", self.detail.as_deref().unwrap_or("")),
841 "stale" => {
842 "stale: the registered directory is missing; apply clears the record".to_owned()
843 }
844 "confirmed" => format!(
845 "confirmed: {} matches this tip",
846 self.proof.as_deref().unwrap_or("")
847 ),
848 "unconfirmed" => format!("unconfirmed: {}", self.detail.as_deref().unwrap_or("")),
849 "unknown" => format!("unknown: {}", self.detail.as_deref().unwrap_or("")),
850 "pruned" => {
851 let mut line = self
852 .proof
853 .as_deref()
854 .map_or_else(|| "pruned".to_owned(), |proof| format!("pruned ({proof})"));
855 if let Some(detail) = &self.detail {
856 line.push_str("; ");
857 line.push_str(detail);
858 }
859 line
860 }
861 "remove-failed" => format!("remove failed: {}", self.detail.as_deref().unwrap_or("")),
862 "branch-delete-failed" => format!(
863 "branch delete failed: {}",
864 self.detail.as_deref().unwrap_or("")
865 ),
866 _ => "candidate".to_owned(),
867 }
868 }
869}
870
871#[derive(Debug, Serialize)]
873struct PruneReport {
874 schema: &'static str,
876 mode: &'static str,
878 worktrees: Vec<PruneRow>,
880 next: Vec<String>,
882}
883
884struct Judged {
886 worktree: Worktree,
887 tip: Option<String>,
889 class: WtClass,
890}
891
892#[allow(
897 clippy::too_many_lines,
898 reason = "the prune order is the safety property, so report, confirm, and remove worktree before branch stay in one body where the order cannot drift"
899)]
900fn prune(
901 target: &Utf8Path,
902 repo_flag: Option<&str>,
903 forge_flag: Option<&str>,
904 verify: bool,
905 apply: bool,
906 quiet: bool,
907 out: Output,
908) -> Result<(), RkError> {
909 let trunk = crate::config::trunk_of(target.as_std_path())?;
910 let worktrees = inventory(target)?;
911 let layout = layout_of(&worktrees)?;
912 let branches = branch_inventory(target)?;
913 if branches.is_empty() && worktrees.iter().any(|worktree| worktree.branch.is_some()) {
917 return Err(RkError::refusal(
918 Diagnostic::new(
919 Reason::PrerequisiteUnmet,
920 "the branch inventory did not parse, and no worktree is judged without its branch observation",
921 )
922 .expected("a branch listing covering the checked-out branches")
923 .target_state("unchanged"),
924 ));
925 }
926 let ledger = crate::maintenance::integration_ledger(target, &trunk);
927 let seat_paths = seats(target);
928 let seat_refs: Vec<&Utf8Path> = seat_paths.iter().map(Utf8PathBuf::as_path).collect();
929
930 let mut judged: Vec<Judged> = Vec::new();
934 for worktree in worktrees.iter().skip(1) {
935 let observation = worktree
936 .branch
937 .as_deref()
938 .and_then(|name| branches.iter().find(|branch| branch.name == name));
939 let local = observation.and_then(|branch| ledger.proof(&branch.name, &branch.tip));
942 let reportable = worktree.prunable.is_some()
943 || local.is_some()
944 || worktree
945 .branch
946 .as_deref()
947 .is_some_and(|_| observation.is_none_or(|branch| branch.gone));
948 if !reportable {
949 continue;
950 }
951 let dirty = worktree.prunable.is_none() && is_dirty(&worktree.path);
952 let class = classify(
953 worktree,
954 observation,
955 &layout,
956 &seat_refs,
957 &trunk,
958 dirty,
959 local,
960 );
961 judged.push(Judged {
962 worktree: worktree.clone(),
963 tip: observation.map(|branch| branch.tip.clone()),
964 class,
965 });
966 }
967
968 if (verify || apply)
970 && judged
971 .iter()
972 .any(|row| matches!(row.class, WtClass::Candidate))
973 {
974 let resolved = crate::landing::resolve(target, forge_flag, repo_flag)?;
975 let forge = Forge::parse(&resolved.forge)
976 .ok_or_else(|| RkError::Usage(format!("unknown forge '{}'", resolved.forge)))?;
977 let repo = resolved.repo.ok_or_else(crate::landing::repo_unresolved)?;
978 let cli = resolve_cli(forge)?;
979 for row in &mut judged {
980 if matches!(row.class, WtClass::Candidate) {
981 let Some(tip) = row.tip.as_deref() else {
982 continue;
983 };
984 row.class = WtClass::Judged(merged_request_for(
985 &cli,
986 target.as_std_path(),
987 forge,
988 &repo,
989 tip,
990 ));
991 }
992 }
993 }
994
995 let mut rows: Vec<PruneRow> = judged
996 .iter()
997 .map(|row| {
998 let (status, proof, detail) = match &row.class {
999 WtClass::Kept { reason } => ("kept", None, Some(reason.clone())),
1000 WtClass::Candidate => ("candidate", None, None),
1001 WtClass::Stale => ("stale", None, None),
1002 WtClass::Judged(Class::Confirmed { proof }) => {
1003 ("confirmed", Some(proof.clone()), None)
1004 }
1005 WtClass::Judged(Class::Unconfirmed { detail }) => {
1006 ("unconfirmed", None, Some(detail.clone()))
1007 }
1008 WtClass::Judged(Class::Unknown { detail }) => {
1009 ("unknown", None, Some(detail.clone()))
1010 }
1011 WtClass::Judged(_) => ("kept", None, Some("guarded".to_owned())),
1012 };
1013 PruneRow {
1014 path: row.worktree.path.to_string(),
1015 branch: row.worktree.branch.clone(),
1016 tip: row.tip.clone(),
1017 status,
1018 proof_kind: proof.as_ref().map(crate::branches::Proof::kind),
1019 proof: proof.as_ref().map(crate::branches::Proof::detail),
1020 detail,
1021 }
1022 })
1023 .collect();
1024
1025 let mut failures = 0usize;
1026 if apply {
1027 for row in &mut rows {
1028 if row.status != "confirmed" {
1029 continue;
1030 }
1031 if let Err(count) = retire(target, row) {
1032 failures += count;
1033 }
1034 }
1035 failures += sweep_stale(target, &mut rows)?;
1036 }
1037
1038 let mode = if apply {
1039 "apply"
1040 } else if verify {
1041 "verify"
1042 } else {
1043 "preview"
1044 };
1045 let next = next_lines(mode);
1046 render(out, &rows, &next, quiet);
1047 out.emit(&PruneReport {
1048 schema: "rk.worktree-prune/2",
1049 mode,
1050 worktrees: rows,
1051 next,
1052 })?;
1053 if failures > 0 {
1054 return Err(RkError::subprocess(
1055 Diagnostic::new(
1056 Reason::SubprocessFailed,
1057 format!("git refused {failures} cleanup actions"),
1058 )
1059 .expected("every confirmed worktree removed; the report names each outcome"),
1060 ));
1061 }
1062 Ok(())
1063}
1064
1065fn retire(target: &Utf8Path, row: &mut PruneRow) -> Result<(), usize> {
1071 let Some(branch) = row.branch.clone() else {
1072 return Ok(());
1073 };
1074 let Some(tip) = row.tip.clone() else {
1075 return Ok(());
1076 };
1077 let keep = |row: &mut PruneRow, moved: &str| {
1078 row.status = "kept";
1079 row.detail = Some(format!(
1080 "{moved} after verification; rk worktree prune --verify re-confirms"
1081 ));
1082 };
1083 let reread = git(
1084 target,
1085 &[
1086 "for-each-ref",
1087 &format!("refs/heads/{branch}"),
1088 "--format",
1089 "%(objectname)",
1090 ],
1091 )
1092 .map_err(|_| 1usize)?;
1093 let fresh_tip = String::from_utf8_lossy(&reread.stdout).trim().to_owned();
1094 if !reread.status.success() || fresh_tip != tip {
1095 keep(row, "the tip moved");
1096 return Ok(());
1097 }
1098 let path = Utf8PathBuf::from(&row.path);
1102 let fresh = git(target, &["worktree", "list", "--porcelain", "-z"]).map_err(|_| 1usize)?;
1103 if !fresh.status.success() {
1104 keep(row, "the worktree inventory could not be re-read");
1105 return Ok(());
1106 }
1107 let Ok(inventory) = crate::worktree::parse_worktrees(&fresh.stdout) else {
1108 keep(row, "the worktree inventory could not be re-read");
1109 return Ok(());
1110 };
1111 let seat = inventory.iter().find(|worktree| worktree.path == path);
1112 if let Some(reason) = crate::worktree::reobservation(seat, &branch) {
1113 keep(row, &reason);
1114 return Ok(());
1115 }
1116 if is_dirty(&path) {
1117 keep(row, "uncommitted changes arrived");
1118 return Ok(());
1119 }
1120 let removed = git(target, &["worktree", "remove", row.path.as_str()]).map_err(|_| 1usize)?;
1121 if !removed.status.success() {
1122 row.status = "remove-failed";
1123 row.detail = Some(format!(
1124 "{}; clear what holds it — the dirt, the lock, the process in the directory — and re-run rk worktree prune --apply",
1125 last_line(&removed.stderr)
1126 ));
1127 return Err(1);
1128 }
1129 match maintenance::delete_branch(target, &branch, &tip) {
1130 maintenance::Deletion::Deleted => {
1131 maintenance::forget_integration(target, &branch);
1132 row.status = "pruned";
1133 Ok(())
1134 }
1135 maintenance::Deletion::ConfigSurvived { detail } => {
1136 maintenance::forget_integration(target, &branch);
1137 row.status = "pruned";
1138 row.detail = Some(detail);
1139 Ok(())
1140 }
1141 maintenance::Deletion::Refused { detail } => {
1142 row.status = "branch-delete-failed";
1145 row.detail = Some(format!(
1146 "{detail}; the worktree is removed and the branch survives with its work: rk worktree add {branch} --apply re-seats it"
1147 ));
1148 Err(1)
1149 }
1150 }
1151}
1152
1153fn sweep_stale(target: &Utf8Path, rows: &mut [PruneRow]) -> Result<usize, RkError> {
1160 if !rows.iter().any(|row| row.status == "stale") {
1161 return Ok(0);
1162 }
1163 let mut failures = 0usize;
1164 let swept = git(target, &["worktree", "prune", "--expire", "now"])?;
1165 let survivors: Option<Vec<Utf8PathBuf>> =
1169 git(target, &["worktree", "list", "--porcelain", "-z"])
1170 .ok()
1171 .filter(|fresh| fresh.status.success())
1172 .and_then(|fresh| crate::worktree::parse_worktrees(&fresh.stdout).ok())
1173 .map(|inventory| {
1174 inventory
1175 .into_iter()
1176 .map(|worktree| worktree.path)
1177 .collect()
1178 });
1179 for row in rows.iter_mut().filter(|row| row.status == "stale") {
1180 let survived = survivors
1181 .as_ref()
1182 .is_none_or(|paths| paths.iter().any(|path| *path == row.path));
1183 if survived {
1184 row.status = "remove-failed";
1185 row.detail = Some(if survivors.is_none() {
1186 "the record's fate could not be observed; re-run rk worktree prune --apply"
1187 .to_owned()
1188 } else if swept.status.success() {
1189 "the record survived the sweep; re-run rk worktree prune --apply".to_owned()
1190 } else {
1191 format!(
1192 "{}; re-run rk worktree prune --apply",
1193 last_line(&swept.stderr)
1194 )
1195 });
1196 failures += 1;
1197 } else {
1198 row.status = "pruned";
1199 }
1200 }
1201 if !swept.status.success() && failures == 0 {
1202 failures = 1;
1203 }
1204 Ok(failures)
1205}
1206
1207fn next_lines(mode: &str) -> Vec<String> {
1209 let verify = "rk worktree prune --verify confirms each candidate against the forge";
1210 let apply = "rk worktree prune --apply verifies, then removes each worktree before its branch";
1211 match mode {
1212 "preview" => vec![verify.to_owned(), apply.to_owned()],
1213 "verify" => vec![apply.to_owned()],
1214 _ => Vec::new(),
1215 }
1216}
1217
1218fn render(out: Output, rows: &[PruneRow], next: &[String], quiet: bool) {
1223 if quiet && rows.is_empty() {
1224 return;
1225 }
1226 if rows.is_empty() {
1227 out.result_line("no worktree needs cleanup");
1228 } else {
1229 out.result_line(header(
1230 rows.len(),
1231 rows.iter()
1232 .filter(|row| row.proof_kind == Some("local-integration"))
1233 .count(),
1234 ));
1235 let width = rows.iter().map(|row| row.path.len()).max().unwrap_or(0);
1236 for row in rows {
1237 let tip = row
1238 .tip
1239 .as_deref()
1240 .map_or(" ", |tip| tip.get(..8).unwrap_or(tip));
1241 out.result_line(format!(" {:width$} {tip} {}", row.path, row.describe()));
1242 }
1243 }
1244 out.next(next);
1245 if rows
1246 .iter()
1247 .any(|row| maintenance::row_owes(row.status, row.detail.as_deref()))
1248 {
1249 out.result_line(OPERATOR_LINE);
1250 }
1251}
1252
1253fn header(count: usize, local: usize) -> String {
1259 let (noun, reports, carry) = if count == 1 {
1260 ("1 worktree".to_owned(), "reports", "carries")
1261 } else {
1262 (format!("{count} worktrees"), "report", "carry")
1263 };
1264 match (local, count - local) {
1265 (0, _) => format!("{noun} {reports} cleanup (a candidate, not proof):"),
1266 (_, 0) => format!("{noun} {carry} a local integration this clone recorded:"),
1267 (_, other) => {
1268 format!("{noun}: {other} reporting cleanup, {local} locally integrated:")
1269 }
1270 }
1271}
1272
1273pub(crate) fn git(target: &Utf8Path, args: &[&str]) -> Result<std::process::Output, RkError> {
1284 let mut command = std::process::Command::new(crate::probes::git_bin());
1285 for var in maintenance::GIT_HOOK_VARS {
1286 command.env_remove(var);
1287 }
1288 command
1289 .arg("-C")
1290 .arg(target.as_std_path())
1291 .args(args)
1292 .output()
1293 .map_err(|source| {
1294 RkError::subprocess(
1295 Diagnostic::new(
1296 Reason::SubprocessSpawn,
1297 format!("git did not run: {source}"),
1298 )
1299 .expected("git installed and on PATH"),
1300 )
1301 })
1302}
1303
1304fn last_line(bytes: &[u8]) -> String {
1306 maintenance::last_line(bytes)
1307}
1308
1309#[cfg(test)]
1310mod tests {
1311 use super::{ListReport, ListRow, PruneReport, PruneRow};
1312
1313 #[test]
1316 fn the_worktree_list_schema_snapshot_holds() {
1317 let populated = ListReport {
1318 schema: "rk.worktree-list/1",
1319 worktrees: vec![
1320 ListRow {
1321 path: "/srv/widget".into(),
1322 branch: Some("master".into()),
1323 head: "aaaabbbbccccddddaaaabbbbccccddddaaaabbbb".into(),
1324 kind: "main",
1325 state: "clean",
1326 canonical: true,
1327 },
1328 ListRow {
1329 path: "/srv/elsewhere".into(),
1330 branch: None,
1331 head: "bbbbccccddddaaaabbbbccccddddaaaabbbbcccc".into(),
1332 kind: "linked",
1333 state: "detached",
1334 canonical: true,
1335 },
1336 ],
1337 next: vec!["rk worktree prune reports the worktrees a squash merge retired".into()],
1338 };
1339 assert_eq!(
1340 serde_json::to_string(&populated).expect("a report serializes"),
1341 r#"{"schema":"rk.worktree-list/1","worktrees":[{"path":"/srv/widget","branch":"master","head":"aaaabbbbccccddddaaaabbbbccccddddaaaabbbb","kind":"main","state":"clean","canonical":true},{"path":"/srv/elsewhere","head":"bbbbccccddddaaaabbbbccccddddaaaabbbbcccc","kind":"linked","state":"detached","canonical":true}],"next":["rk worktree prune reports the worktrees a squash merge retired"]}"#,
1342 "a detached row must omit branch rather than serializing null"
1343 );
1344 }
1345
1346 #[test]
1351 fn the_worktree_add_schema_snapshot_holds() {
1352 let apply = super::AddReport {
1353 schema: "rk.worktree-add/1",
1354 mode: "apply",
1355 branch: "feat/x".into(),
1356 path: "/srv/widget@feat-x".into(),
1357 created: "branch",
1358 source: "remote",
1359 base: Some("origin/feat/x".into()),
1360 upstream: Some("origin/feat/x".into()),
1361 detail: Some("the fetch failed; the run proceeded on local refs".into()),
1362 next: vec!["cd /srv/widget@feat-x".into()],
1363 };
1364 assert_eq!(
1365 serde_json::to_string(&apply).expect("a report serializes"),
1366 r#"{"schema":"rk.worktree-add/1","mode":"apply","branch":"feat/x","path":"/srv/widget@feat-x","created":"branch","source":"remote","base":"origin/feat/x","upstream":"origin/feat/x","detail":"the fetch failed; the run proceeded on local refs","next":["cd /srv/widget@feat-x"]}"#
1367 );
1368 let preview = super::AddReport {
1369 mode: "preview",
1370 created: "nothing",
1371 source: "adopted",
1372 base: None,
1373 upstream: None,
1374 detail: None,
1375 ..apply
1376 };
1377 assert_eq!(
1378 serde_json::to_string(&preview).expect("a report serializes"),
1379 r#"{"schema":"rk.worktree-add/1","mode":"preview","branch":"feat/x","path":"/srv/widget@feat-x","created":"nothing","source":"adopted","next":["cd /srv/widget@feat-x"]}"#,
1380 "an absent option must be omitted rather than serializing null"
1381 );
1382 }
1383
1384 #[test]
1387 fn the_worktree_prune_schema_snapshot_holds() {
1388 let populated = PruneReport {
1389 schema: "rk.worktree-prune/2",
1390 mode: "verify",
1391 worktrees: vec![
1392 PruneRow {
1393 path: "/srv/widget@feat-x".into(),
1394 branch: Some("feat/x".into()),
1395 tip: Some("aaaabbbbccccddddaaaabbbbccccddddaaaabbbb".into()),
1396 status: "confirmed",
1397 proof: Some("#8".into()),
1398 proof_kind: Some("request"),
1399 detail: None,
1400 },
1401 PruneRow {
1402 path: "/srv/widget@fix-y".into(),
1403 branch: None,
1404 tip: None,
1405 status: "stale",
1406 proof: None,
1407 proof_kind: None,
1408 detail: None,
1409 },
1410 ],
1411 next: vec![
1412 "rk worktree prune --apply verifies, then removes each worktree before its branch"
1413 .into(),
1414 ],
1415 };
1416 assert_eq!(
1417 serde_json::to_string(&populated).expect("a report serializes"),
1418 r##"{"schema":"rk.worktree-prune/2","mode":"verify","worktrees":[{"path":"/srv/widget@feat-x","branch":"feat/x","tip":"aaaabbbbccccddddaaaabbbbccccddddaaaabbbb","status":"confirmed","proof":"#8","proof_kind":"request"},{"path":"/srv/widget@fix-y","status":"stale"}],"next":["rk worktree prune --apply verifies, then removes each worktree before its branch"]}"##
1419 );
1420 let clean = PruneReport {
1421 schema: "rk.worktree-prune/2",
1422 mode: "preview",
1423 worktrees: vec![],
1424 next: vec![
1425 "rk worktree prune --verify confirms each candidate against the forge".into(),
1426 ],
1427 };
1428 assert_eq!(
1429 serde_json::to_string(&clean).expect("a report serializes"),
1430 r#"{"schema":"rk.worktree-prune/2","mode":"preview","worktrees":[],"next":["rk worktree prune --verify confirms each candidate against the forge"]}"#,
1431 "a clean clone reports one empty list a caller can branch on"
1432 );
1433 }
1434}