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