Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
refactor(remove): report a removal's branch fate, not its plan's intent (#3637)
Maximilian Roosc90c4b1b771e
diff --git a/src/commands/hook_plan.rs b/src/commands/hook_plan.rsindex 95068c404..918a3026c 100644--- a/src/commands/hook_plan.rs+++ b/src/commands/hook_plan.rs@@ -331,7 +331,7 @@ impl ApprovedHookPlan {/// The frozen selection for `(hook_type, anchor)`, by exact match.////// Every covered gate anchors at the identical path its executor passes:- /// the `RemoveResult` worktree/destination path threaded unchanged, the+ /// the `RemovalPlan` worktree/destination path threaded unchanged, the/// `SwitchPlan`/`SwitchResult` destination, or the merge feature root/// (`current_worktree().root()` on the same `Repository`, cached, so the/// gate and `finish_after_merge` produce the same `PathBuf`). The invariantdiff --git a/src/commands/merge.rs b/src/commands/merge.rsindex d8e717f53..6781dcd3f 100644--- a/src/commands/merge.rs+++ b/src/commands/merge.rs@@ -116,7 +116,7 @@ fn approve_merge_plan(// Every feature-worktree hook shares one anchor: the feature worktree's// canonical root, the exact path `finish_after_merge` records as- // `RemoveResult::worktree_path` and `handle_merge` passes as the+ // `RemovalPlan::worktree_path` and `handle_merge` passes as the// `pre-merge` executor anchor, so every plan lookup is an exact match.// `pre-commit`/`post-commit` run via the unchanged `execute_hook` path and// are listed only so the single prompt is complete; their anchor is never@@ -281,7 +281,7 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {// (by-then-rebased / merged) on-disk config is structurally impossible.let project_id = repo.project_identifier()?;// One anchor for every feature-worktree hook: the canonical root, the same- // value `finish_after_merge` records as `RemoveResult::worktree_path`.+ // value `finish_after_merge` records as `RemovalPlan::worktree_path`.let feature_root = current_wt.root()?;let plan = approve_merge_plan(repo,diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rsindex a5a9f1498..b5604a007 100644--- a/src/commands/picker/mod.rs+++ b/src/commands/picker/mod.rs@@ -133,10 +133,10 @@ use super::list::model::{BranchScope, ItemKind, ListItem};use super::list::progressive::RenderTarget;use super::list::render::PLACEHOLDER;use super::repository_ext::{RemoveTarget, RepositoryCliExt};-use super::worktree::{RemoveResult, SwitchPipeline};+use super::worktree::{RemovalPlan, SwitchPipeline};use crate::cli::SwitchFormat;-use crate::output::{BackgroundFallbackMode, handle_remove_output};-use worktrunk::git::{BranchDeletionMode, delete_branch_if_safe};+use crate::output::{RemovalExecution, handle_remove_output};+use worktrunk::git::{BranchDeletionMode, execute_branch_deletion};use items::{LocalContent, LocalContentSlot, PreviewCache, ShortcutTable, WORKTREE_OUTPUT_PREFIX};use preview::{PreviewLayout, PreviewMode, PreviewState, PreviewStateData};@@ -328,7 +328,7 @@ impl AltXRemover {fn prepare_removal(&self,target: &PickerRemovalTarget,- ) -> anyhow::Result<(Repository, RemoveResult)> {+ ) -> anyhow::Result<(Repository, RemovalPlan)> {let repo = Repository::at(self.repo.discovery_path())?;// Validate removal before touching the list. prepare_worktree_removal@@ -356,7 +356,7 @@ impl AltXRemover {/// Execute a queued removal in the background.///- /// A `RemovedWorktree` result goes through [`handle_remove_output`] in its+ /// A `Worktree` result goes through [`handle_remove_output`] in its/// silent (TUI) mode — the git worktree removal with no `wt`-generated/// messages, spinner, or `cd` directive (skim owns the terminal). Its/// `pre-remove` / `post-remove` / `post-switch` hooks run only when they're@@ -386,16 +386,16 @@ impl AltXRemover {////// `repo` is the worktree the picker is operating from — the config source/// for the removal hooks (see [`approved_removal_plan`]) and the target of- /// a `BranchOnly` deletion. `RemovedWorktree` removal itself is rooted at+ /// a `BranchOnly` deletion. `Worktree` removal itself is rooted at/// `main_path` (which may differ from the picker's startup repo in bare-repo/// setups).fn do_removal(repo: &Repository,- result: &RemoveResult,+ result: &RemovalPlan,approvals: &Approvals,) -> anyhow::Result<()> {match result {- RemoveResult::RemovedWorktree {+ RemovalPlan::Worktree {main_path,worktree_path,..@@ -403,18 +403,19 @@ impl AltXRemover {let main_repo = Repository::at(main_path)?;let plan = approved_removal_plan(repo, main_path, worktree_path, approvals)?;let mut announcer = HookAnnouncer::new(&main_repo, false);+ // The fate is dropped: the picker infers success by observing+ // whether the target survived (`removal_target_still_present`),+ // never from what the executor reports.handle_remove_output(result,- /* foreground */ true,+ RemovalExecution::Silent,&plan,/* quiet */ true,- /* silent */ true,&mut announcer,- BackgroundFallbackMode::Detached,)?;announcer.flush()?;}- RemoveResult::BranchOnly {+ RemovalPlan::BranchOnly {branch_name,deletion_mode,..@@ -422,14 +423,8 @@ impl AltXRemover {if !deletion_mode.should_keep() {let default_branch = repo.default_branch();let target = default_branch.as_deref().unwrap_or("HEAD");- if let Ok(snapshot) = repo.capture_refs()- && let Err(e) = delete_branch_if_safe(- repo,- &snapshot,- branch_name,- target,- deletion_mode.is_force(),- )+ if let Err(e) =+ execute_branch_deletion(repo, branch_name, target, deletion_mode.is_force()){// A safe-delete refusal is `Ok(NotDeleted)`, not an error;// this is a genuine `git branch -D` failure. The row is@@ -464,7 +459,7 @@ impl AltXRemover {&self,selected_output: String,planning_repo: Repository,- result: RemoveResult,+ result: RemovalPlan,) {// Capture the removed row (and its position) before dropping it: the// position is handed to the background thread so it can put the row back@@ -546,8 +541,8 @@ impl AltXRemover {// The canonical "retained; unmerged" info + hint `wt remove` prints,// shared so the picker copy can't drift (see// `stash_retained_unmerged_branch`). Taking the branch name (not the whole- // `RemoveResult`) makes it unrepresentable for this keep path to be handed- // a `RemovedWorktree`, which always removes — see the dispatch in+ // `RemovalPlan`) makes it unrepresentable for this keep path to be handed+ // a `Worktree`, which always removes — see the dispatch in// [`apply`](Self::apply) and [`removal_will_remove_target`].// A by-design retain, not a failure — info (○), matching the canonical// `info_message` this path stashes (see `stash_retained_unmerged_branch`).@@ -578,7 +573,7 @@ impl AltXRemover {/// Morph the selected worktree row into a `/ branch` row in place, then remove/// the worktree on a background thread.///- /// For a `RemovedWorktree` removal that [`worktree_removal_keeps_branch`]+ /// For a `Worktree` removal that [`worktree_removal_keeps_branch`]/// predicts will keep its (unmerged) branch. The row never leaves its slot:/// the morph rewrites the row's shared `rendered` line to the branch line/// (rendered on the live layout — gutter `+` → `/`, path blank), flips the@@ -606,7 +601,7 @@ impl AltXRemover {selected_output: String,branch: String,planning_repo: Repository,- result: RemoveResult,+ result: RemovalPlan,) -> RemovalEffect {// Gather the row's shared morph handles and render the branch line on the// live layout. Any gap (row not morphable, layout not yet handed over)@@ -724,11 +719,11 @@ impl AltXRemover {} else {// The only non-removing outcome: `removal_will_remove_target`// returns false solely for an unmerged `BranchOnly` row (a- // `RemovedWorktree` always removes, so it never reaches here), so+ // `Worktree` always removes, so it never reaches here), so// this arm is always that row — keep it, explained.// `keep_unremovable_row` taking the branch name — not the whole// result — keeps that narrowing at the type level.- if let RemoveResult::BranchOnly { branch_name, .. } = &result {+ if let RemovalPlan::BranchOnly { branch_name, .. } = &result {self.keep_unremovable_row(branch_name);}RemovalEffect::Kept@@ -1021,27 +1016,27 @@ fn run_preview_when_settled(/// A removal's user-facing subject for the `kept` warning: a `(label, noun)`/// pair where `noun` is `worktree` or `branch` and `label` is the branch name/// (or the worktree's display path for a detached worktree). Computed before the-/// `RemoveResult` moves into the background thread; surfaced by+/// `RemovalPlan` moves into the background thread; surfaced by/// [`restore_failed_removal`].-fn removal_failure_subject(result: &RemoveResult) -> (String, &'static str) {+fn removal_failure_subject(result: &RemovalPlan) -> (String, &'static str) {match result {- RemoveResult::RemovedWorktree {+ RemovalPlan::Worktree {branch_name: Some(branch),..} => (branch.clone(), "worktree"),- RemoveResult::RemovedWorktree { worktree_path, .. } => {+ RemovalPlan::Worktree { worktree_path, .. } => {(format_path_for_display(worktree_path), "worktree")}- RemoveResult::BranchOnly { branch_name, .. } => (branch_name.clone(), "branch"),+ RemovalPlan::BranchOnly { branch_name, .. } => (branch_name.clone(), "branch"),}}/// Whether `do_removal` will actually remove the target — predicted up front from-/// `prepare_removal`'s already-computed [`RemoveResult`], before the row is+/// `prepare_removal`'s already-computed [`RemovalPlan`], before the row is/// dropped. The dual of [`removal_target_still_present`]: this decides whether to/// drop the row, that confirms the drop afterward.///-/// A `RemovedWorktree` result has passed `ensure_clean` (Phase 5 of+/// A `Worktree` result has passed `ensure_clean` (Phase 5 of/// `prepare_worktree_removal`), so the worktree removes — the only failures left/// are async and rare (a clean-check race, a failing approved `pre-remove` hook),/// which the background restore still catches. A `BranchOnly` result deletes only@@ -1050,10 +1045,10 @@ fn removal_failure_subject(result: &RemoveResult) -> (String, &'static str) {/// `Repository::integration_reason` the later delete consults, so they can't/// drift). An unmerged branch-only row is thus kept, and predicting it here means/// it never drops (no flicker) — see [`AltXRemover::keep_unremovable_row`].-fn removal_will_remove_target(result: &RemoveResult) -> bool {+fn removal_will_remove_target(result: &RemovalPlan) -> bool {match result {- RemoveResult::RemovedWorktree { .. } => true,- RemoveResult::BranchOnly {+ RemovalPlan::Worktree { .. } => true,+ RemovalPlan::BranchOnly {deletion_mode,integration_reason,..@@ -1076,22 +1071,23 @@ fn removal_will_remove_target(result: &RemoveResult) -> bool {/// removing the now-non-current row is the clean path, so alt-x on the current/// worktree keeps the row and explains. `BranchOnly` rows have no worktree to be/// standing in, so this is always `false` for them.-fn removal_targets_current_worktree(result: &RemoveResult) -> bool {+fn removal_targets_current_worktree(result: &RemovalPlan) -> bool {matches!(result,- RemoveResult::RemovedWorktree {+ RemovalPlan::Worktree {changed_directory: true,..})}-/// The branch a `RemovedWorktree` removal will **keep** — worktree gone, branch+/// The branch a `Worktree` removal will **keep** — worktree gone, branch/// retained — or `None` if the removal will delete the branch (or there's no/// branch). Drives the `alt-x` in-place morph: a kept branch turns the row into/// a `/ branch` row rather than dropping it.///-/// Mirrors [`delete_branch_if_safe`] exactly so the prediction can't drift from+/// Mirrors [`delete_branch_if_safe`](worktrunk::git::delete_branch_if_safe)+/// exactly so the prediction can't drift from/// the deletion the background `do_removal` performs: force always deletes; a/// `Keep` flag always retains; otherwise the branch is kept precisely when it is/// **not** integrated into the same `target_branch.unwrap_or("HEAD")` the actual@@ -1099,8 +1095,8 @@ fn removal_targets_current_worktree(result: &RemoveResult) -> bool {/// or integration error yields `None` (fall back to the drop path) — never a/// morph the removal won't back up. Runs a couple of git commands on skim's/// event loop, like `prepare_removal`'s own validation.-fn worktree_removal_keeps_branch(repo: &Repository, result: &RemoveResult) -> Option<String> {- let RemoveResult::RemovedWorktree {+fn worktree_removal_keeps_branch(repo: &Repository, result: &RemovalPlan) -> Option<String> {+ let RemovalPlan::Worktree {branch_name: Some(branch),deletion_mode,target_branch,@@ -1126,7 +1122,7 @@ fn worktree_removal_keeps_branch(repo: &Repository, result: &RemoveResult) -> Op/// primary evidence for "was this actually removed," used in place of inferring/// from `do_removal`'s `Result`.///-/// A `Result` is the wrong signal in two directions: a `RemovedWorktree` removal+/// A `Result` is the wrong signal in two directions: a `Worktree` removal/// can return `Err` *after* the worktree is already trashed (rendering or/// spawning a `post-remove`/`post-switch` hook fails during the announcer flush),/// and a `BranchOnly` safe-delete that raced from integrated to unmerged returns@@ -1143,10 +1139,10 @@ fn worktree_removal_keeps_branch(repo: &Repository, result: &RemoveResult) -> Op/// created only when removing the worktree the shell is sitting in — see/// [`crate::output::handlers`]). A successful removal renames the whole tree away;/// a failed one leaves it intact.-fn removal_target_still_present(repo: &Repository, result: &RemoveResult) -> bool {+fn removal_target_still_present(repo: &Repository, result: &RemovalPlan) -> bool {match result {- RemoveResult::RemovedWorktree { worktree_path, .. } => worktree_path.exists(),- RemoveResult::BranchOnly { branch_name, .. } => {+ RemovalPlan::Worktree { worktree_path, .. } => worktree_path.exists(),+ RemovalPlan::BranchOnly { branch_name, .. } => {repo.branch(branch_name).exists_locally().unwrap_or(false)}}@@ -2532,7 +2528,7 @@ pub mod tests {resolve_identifier, resolve_shortcut_branch, resolve_shortcut_url, switch_pipeline_repo,};use crate::commands::list::model::{BranchScope, ItemKind, ListItem, WorktreeData};- use crate::commands::worktree::RemoveResult;+ use crate::commands::worktree::RemovalPlan;use skim::prelude::SkimItem;use std::fs;use std::path::Path;@@ -2793,7 +2789,7 @@ pub mod tests {.unwrap();assert!(wt_path.exists());- let result = RemoveResult::RemovedWorktree {+ let result = RemovalPlan::Worktree {main_path: test.path().to_path_buf(),worktree_path: wt_path.clone(),changed_directory: false,@@ -2821,7 +2817,7 @@ pub mod tests {// Create a branch at the same commit (fully integrated into main)repo.run_command(&["branch", "feature"]).unwrap();- let result = RemoveResult::BranchOnly {+ let result = RemovalPlan::BranchOnly {branch_name: "feature".to_string(),deletion_mode: BranchDeletionMode::SafeDelete,pruned: false,@@ -2848,7 +2844,7 @@ pub mod tests {.unwrap();repo.run_command(&["checkout", "main"]).unwrap();- let result = RemoveResult::BranchOnly {+ let result = RemovalPlan::BranchOnly {branch_name: "unmerged".to_string(),deletion_mode: BranchDeletionMode::SafeDelete,pruned: false,@@ -2891,7 +2887,7 @@ pub mod tests {assert!(wt_path.exists());- let result = RemoveResult::RemovedWorktree {+ let result = RemovalPlan::Worktree {main_path: test.path().to_path_buf(),worktree_path: wt_path.clone(),changed_directory: false,@@ -2925,11 +2921,34 @@ pub mod tests {let target = PickerRemovalTarget::from_signal("branch-only-feature").unwrap();let (_planning_repo, result) = remover.prepare_removal(&target).unwrap();assert!(- matches!(&result, RemoveResult::BranchOnly { branch_name, .. } if branch_name == "branch-only-feature"),+ matches!(&result, RemovalPlan::BranchOnly { branch_name, .. } if branch_name == "branch-only-feature"),"a branch with no worktree should resolve to BranchOnly");}+ /// `do_removal` on a branch-only plan deletes the branch through+ /// `execute_branch_deletion` — the same fresh-refs CAS path every planned+ /// deletion takes — with no worktree involved.+ #[test]+ fn test_do_removal_deletes_branch_only_plan() {+ let test = worktrunk::testing::TestRepo::with_initial_commit();+ let repo = worktrunk::git::Repository::at(test.path()).unwrap();++ // Integrated (same commit as main), no worktree → safe to delete.+ repo.run_command(&["branch", "row-branch"]).unwrap();++ let remover = test_remover(Arc::new(Mutex::new(Vec::new())), repo.clone());+ let target = PickerRemovalTarget::from_signal("row-branch").unwrap();+ let (planning_repo, plan) = remover.prepare_removal(&target).unwrap();++ AltXRemover::do_removal(&planning_repo, &plan, &Approvals::default()).unwrap();+ assert!(+ repo.run_command(&["rev-parse", "--verify", "refs/heads/row-branch"])+ .is_err(),+ "an integrated branch-only row should be deleted"+ );+ }+/// A branch-only row whose branch has since acquired a worktree — someone/// ran `wt switch` elsewhere while the picker sat open. The row's signal/// still decodes to `Branch`, and removing it would take out a worktree@@ -2968,7 +2987,7 @@ pub mod tests {let remover = test_remover(Arc::new(Mutex::new(Vec::new())), repo);- // `RemoveResult` isn't `Debug`; drop the Ok payload so `unwrap_err`+ // `RemovalPlan` isn't `Debug`; drop the Ok payload so `unwrap_err`// (which needs `T: Debug`) can report a failure cleanly.let target = PickerRemovalTarget::from_signal("no-such-branch").unwrap();let err = remover@@ -3011,7 +3030,7 @@ pub mod tests {).unwrap();- let result = RemoveResult::RemovedWorktree {+ let result = RemovalPlan::Worktree {main_path: test.path().to_path_buf(),worktree_path: wt_path.clone(),changed_directory: false,@@ -3699,7 +3718,7 @@ pub mod tests {/// `worktree` for a worktree removal, `branch` for a branch-only deletion.#[test]fn test_removal_failure_subject() {- let branched = RemoveResult::RemovedWorktree {+ let branched = RemovalPlan::Worktree {main_path: std::path::PathBuf::from("/tmp/main"),worktree_path: std::path::PathBuf::from("/tmp/wt-feature"),changed_directory: false,@@ -3716,7 +3735,7 @@ pub mod tests {("feature".to_string(), "worktree"));- let detached = RemoveResult::RemovedWorktree {+ let detached = RemovalPlan::Worktree {main_path: std::path::PathBuf::from("/tmp/main"),worktree_path: std::path::PathBuf::from("/tmp/wt-detached"),changed_directory: false,@@ -3733,7 +3752,7 @@ pub mod tests {("/tmp/wt-detached".to_string(), "worktree"));- let branch_only = RemoveResult::BranchOnly {+ let branch_only = RemovalPlan::BranchOnly {branch_name: "orphan".to_string(),deletion_mode: BranchDeletionMode::SafeDelete,pruned: false,@@ -4049,7 +4068,7 @@ pub mod tests {assert!(!reported_path.exists(), "the worktree is removed");}- /// `worktree_removal_keeps_branch` predicts the morph: a `RemovedWorktree`+ /// `worktree_removal_keeps_branch` predicts the morph: a `Worktree`/// whose `SafeDelete` would retain the branch (unmerged) yields the branch/// name; an integrated one (deletes the branch) and a force-delete both yield/// `None`. Built from real refs so the prediction runs the same@@ -4066,7 +4085,7 @@ pub mod tests {repo.run_command(&["commit", "-m", "work"]).unwrap();repo.run_command(&["checkout", "main"]).unwrap();- let result = |branch: &str, mode| RemoveResult::RemovedWorktree {+ let result = |branch: &str, mode| RemovalPlan::Worktree {main_path: test.path().to_path_buf(),worktree_path: test.path().join("gone"),changed_directory: false,@@ -4165,7 +4184,7 @@ pub mod tests {let test = worktrunk::testing::TestRepo::with_initial_commit();let repo = worktrunk::git::Repository::at(test.path()).unwrap();- let worktree_result = |path: std::path::PathBuf| RemoveResult::RemovedWorktree {+ let worktree_result = |path: std::path::PathBuf| RemovalPlan::Worktree {main_path: test.path().to_path_buf(),worktree_path: path,changed_directory: false,@@ -4187,7 +4206,7 @@ pub mod tests {));repo.run_command(&["branch", "live-branch"]).unwrap();- let present_branch = RemoveResult::BranchOnly {+ let present_branch = RemovalPlan::BranchOnly {branch_name: "live-branch".to_string(),deletion_mode: BranchDeletionMode::SafeDelete,pruned: false,@@ -4197,7 +4216,7 @@ pub mod tests {};assert!(super::removal_target_still_present(&repo, &present_branch));- let gone_branch = RemoveResult::BranchOnly {+ let gone_branch = RemovalPlan::BranchOnly {branch_name: "no-such-branch".to_string(),deletion_mode: BranchDeletionMode::SafeDelete,pruned: false,@@ -4218,7 +4237,7 @@ pub mod tests {use worktrunk::git::IntegrationReason;let branch_only = |mode: BranchDeletionMode, integration: Option<IntegrationReason>| {- RemoveResult::BranchOnly {+ RemovalPlan::BranchOnly {branch_name: "b".to_string(),deletion_mode: mode,pruned: false,@@ -4228,7 +4247,7 @@ pub mod tests {}};- let worktree = RemoveResult::RemovedWorktree {+ let worktree = RemovalPlan::Worktree {main_path: std::path::PathBuf::from("/repo"),worktree_path: std::path::PathBuf::from("/repo.feature"),changed_directory: false,@@ -4269,13 +4288,13 @@ pub mod tests {);}- /// `removal_targets_current_worktree` fires only for a `RemovedWorktree` whose+ /// `removal_targets_current_worktree` fires only for a `Worktree` whose/// `changed_directory` flag is set (the worktree the picker was launched from);/// a non-current worktree and any `BranchOnly` row read as `false`.#[test]fn test_removal_targets_current_worktree() {let path = std::path::PathBuf::from("/repo.feature");- let worktree = |changed_directory| RemoveResult::RemovedWorktree {+ let worktree = |changed_directory| RemovalPlan::Worktree {main_path: std::path::PathBuf::from("/repo"),worktree_path: path.clone(),changed_directory,@@ -4296,7 +4315,7 @@ pub mod tests {"removing some other worktree");assert!(- !super::removal_targets_current_worktree(&RemoveResult::BranchOnly {+ !super::removal_targets_current_worktree(&RemovalPlan::BranchOnly {branch_name: "feature".to_string(),deletion_mode: BranchDeletionMode::SafeDelete,pruned: false,diff --git a/src/commands/remove.rs b/src/commands/remove.rsindex 875ca995a..5e2a91c4f 100644--- a/src/commands/remove.rs+++ b/src/commands/remove.rs@@ -11,22 +11,32 @@ use worktrunk::git::{BranchDeletionMode, ErrorExt, Repository, ResolvedWorktree}use worktrunk::styling::{eprintln, info_message};use crate::cli::{RemoveArgs, SwitchFormat};-use crate::output::{BackgroundFallbackMode, handle_remove_output};+use crate::output::{BackgroundFallbackMode, RemovalExecution, handle_remove_output};use super::hook_plan::{ApprovedHookPlan, HookPlanBuilder};use super::hooks::HookAnnouncer;use super::repository_ext::RepositoryCliExt;-use super::worktree::RemoveResult;+use super::worktree::{BranchFate, RemovalPlan};use super::{RemoveTarget, flag_pair};+/// The execution mode `--foreground` selects; the background default falls+/// back to the standard detached `git worktree remove`.+fn removal_execution(foreground: bool) -> RemovalExecution {+ if foreground {+ RemovalExecution::Foreground+ } else {+ RemovalExecution::Background(BackgroundFallbackMode::Detached)+ }+}+/// Validated removal plans, categorized for ordered execution.////// Multi-worktree removal validates all targets upfront, then executes in order:/// other worktrees first, branch-only cases next, current worktree last.struct RemovePlans {- others: Vec<RemoveResult>,- branch_only: Vec<RemoveResult>,- current: Option<RemoveResult>,+ others: Vec<RemovalPlan>,+ branch_only: Vec<RemovalPlan>,+ current: Option<RemovalPlan>,errors: Vec<anyhow::Error>,}@@ -214,7 +224,7 @@ fn reap_worktree_processes(worktree_path: &Path, label: &str) {/// removed a worktree (branch-only deletions have no directory to scope by)./// The display label prefers the branch name, falling back to the worktree/// directory name. No-op on non-Unix, where `--reap` is rejected up front.-fn maybe_reap_result(result: &RemoveResult, reap_enabled: bool) {+fn maybe_reap_result(result: &RemovalPlan, reap_enabled: bool) {#[cfg(unix)]if reap_enabled && let Some(path) = result.removed_worktree_path() {let label = result@@ -356,18 +366,16 @@ pub fn handle_remove_command(args: RemoveArgs, yes: bool) -> anyhow::Result<()>maybe_reap_result(&result, args.reap);let mut announcer = HookAnnouncer::new(&repo, false);- handle_remove_output(+ let fate = handle_remove_output(&result,- args.foreground,+ removal_execution(args.foreground),&plan,false,- false,&mut announcer,- BackgroundFallbackMode::Detached,)?;announcer.flush()?;if json_mode {- let json = serde_json::json!([result.to_json()]);+ let json = serde_json::json!([result.to_json(fate)]);println!("{}", serde_json::to_string_pretty(&json)?);}// Fire-and-forget repo-wide internal cleanup (stale trash +@@ -416,28 +424,29 @@ pub fn handle_remove_command(args: RemoveArgs, yes: bool) -> anyhow::Result<()>// Execute all validated plans: others first, branch-only next, current lastlet show_branch =plans.others.len() + plans.branch_only.len() + plans.current.iter().len() > 1;- let run = |result: &RemoveResult| -> anyhow::Result<()> {+ let run = |result: &RemovalPlan| -> anyhow::Result<BranchFate> {maybe_reap_result(result, args.reap);let mut announcer = HookAnnouncer::new(&repo, show_branch);- handle_remove_output(+ let fate = handle_remove_output(result,- args.foreground,+ removal_execution(args.foreground),&plan,false,- false,&mut announcer,- BackgroundFallbackMode::Detached,)?;- announcer.flush()+ announcer.flush()?;+ Ok(fate)};+ // Fates in execution order, which is also the JSON order below.+ let mut fates = Vec::new();for result in &plans.others {- run(result)?;+ fates.push(run(result)?);}for result in &plans.branch_only {- run(result)?;+ fates.push(run(result)?);}if let Some(ref result) = plans.current {- run(result)?;+ fates.push(run(result)?);}if json_mode {@@ -446,7 +455,8 @@ pub fn handle_remove_command(args: RemoveArgs, yes: bool) -> anyhow::Result<()>.iter().chain(&plans.branch_only).chain(plans.current.as_ref())- .map(RemoveResult::to_json)+ .zip(fates)+ .map(|(removal, fate)| removal.to_json(fate)).collect();println!("{}", serde_json::to_string_pretty(&json_items)?);}diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rsindex b18ea6363..a667992d0 100644--- a/src/commands/repository_ext.rs+++ b/src/commands/repository_ext.rs@@ -2,7 +2,7 @@ use std::path::{Path, PathBuf};use std::process;use std::time::{SystemTime, UNIX_EPOCH};-use super::worktree::{RemoveResult, SharedBranchCheckout};+use super::worktree::{RemovalPlan, SharedBranchCheckout};use anyhow::{Context, bail};use color_print::cformat;use worktrunk::git::{@@ -41,7 +41,7 @@ pub trait RepositoryCliExt {/// Prepare the removal of whichever worktree or branch [`RemoveTarget`]/// names.///- /// Returns a `RemoveResult` describing what will be removed. The actual+ /// Returns a `RemovalPlan` describing what will be removed. The actual/// removal is performed by the output handler.////// `current_path` overrides process-CWD discovery for determining which@@ -65,7 +65,7 @@ pub trait RepositoryCliExt {current_path: Option<PathBuf>,worktrees: Option<&[WorktreeInfo]>,snapshot: Option<&RefSnapshot>,- ) -> anyhow::Result<RemoveResult>;+ ) -> anyhow::Result<RemovalPlan>;/// Prepare the target worktree for push by auto-stashing non-overlapping changes when safe.///@@ -112,7 +112,7 @@ impl RepositoryCliExt for Repository {current_path: Option<PathBuf>,worktrees: Option<&[WorktreeInfo]>,snapshot: Option<&RefSnapshot>,- ) -> anyhow::Result<RemoveResult> {+ ) -> anyhow::Result<RemovalPlan> {let current_path = current_path.map_or_else(|| self.current_worktree().root(), Ok)?;let worktrees = match worktrees {Some(wts) => wts,@@ -274,7 +274,7 @@ impl RepositoryCliExt for Repository {.map(|sibling| SharedBranchCheckout::new(&sibling.path, &deletion_mode))});if let Some(shared) = shared {- return Ok(RemoveResult::BranchOnly {+ return Ok(RemovalPlan::BranchOnly {branch_name: branch,deletion_mode: BranchDeletionMode::Keep,pruned: true,@@ -292,7 +292,7 @@ impl RepositoryCliExt for Repository {target,deletion_mode,);- return Ok(RemoveResult::BranchOnly {+ return Ok(RemovalPlan::BranchOnly {branch_name: branch,deletion_mode,pruned: pruned_from.is_some(),@@ -375,7 +375,7 @@ impl RepositoryCliExt for Repository {// selected and frozen into the `ApprovedHookPlan` at the gate// (`remove.rs`'s `approve_remove`), anchored at this worktree's path,// so the executor needs no config — it runs only the frozen plan.- Ok(RemoveResult::RemovedWorktree {+ Ok(RemovalPlan::Worktree {main_path,worktree_path,changed_directory,diff --git a/src/commands/step/prune.rs b/src/commands/step/prune.rsindex a13d4348c..290f22f10 100644--- a/src/commands/step/prune.rs+++ b/src/commands/step/prune.rs@@ -38,8 +38,8 @@ use worktrunk::trace::Span;use super::super::hook_plan::{ApprovedHookPlan, HookPlan, HookPlanBuilder};use super::super::hooks::HookAnnouncer;use super::super::repository_ext::{RemoveTarget, RepositoryCliExt, live_sibling_checkout};-use super::super::worktree::RemoveResult;-use crate::output::{BackgroundFallbackMode, handle_remove_output};+use super::super::worktree::RemovalPlan;+use crate::output::{BackgroundFallbackMode, RemovalExecution, handle_remove_output};/// A candidate worktree or branch selected for removal.#[derive(Clone)]@@ -54,12 +54,16 @@ struct Candidate {path: Option<PathBuf>,/// Current worktree, other worktree, branch-only, or stale detached metadatakind: CandidateKind,- /// Whether the removal deletes `branch`, from- /// [`RemoveResult::deletes_branch`]. The kind is a plan, not an outcome: a- /// branch a sibling worktree still has checked out is retained, so a- /// worktree candidate can take the worktree and leave the branch standing.- /// The summary counts this rather than the kind, so it never reports a- /// branch the run deliberately kept.+ /// Whether the removal deletes `branch`. The kind is a plan, not an+ /// outcome: a branch a sibling worktree still has checked out is retained,+ /// so a worktree candidate can take the worktree and leave the branch+ /// standing. The summary counts this rather than the kind, so it never+ /// reports a branch the run deliberately kept.+ ///+ /// Starts as the scan's prediction (what the dry run prints); on the live+ /// path [`try_remove`] overwrites it with the executed+ /// [`BranchFate`](crate::commands::worktree::BranchFate), so a deletion+ /// the CAS refused mid-run is counted as retained, not as the plan hoped.deletes_branch: bool,}@@ -103,7 +107,7 @@ impl Candidate {/// The current-worktree candidate held back until every other removal ran/// (its removal cd's the shell to the primary), with its scan-time plan.-type DeferredCurrent = (Candidate, Option<RemoveResult>);+type DeferredCurrent = (Candidate, Option<RemovalPlan>);/// One unit of work for the removal workers, queued in scan-completion order.///@@ -118,8 +122,8 @@ enum RemovalJob {Remove {candidate: Candidate,/// Boxed to keep the variants near parity- /// (`clippy::large_enum_variant` — `RemoveResult` is large).- plan: Box<Option<RemoveResult>>,+ /// (`clippy::large_enum_variant` — `RemovalPlan` is large).+ plan: Box<Option<RemovalPlan>>,},/// Print an already-formatted skip line.PrintSkip(String),@@ -184,8 +188,9 @@ fn prune_summary(candidates: &[Candidate]) -> String {match &c.kind {CandidateKind::BranchOnly if c.deletes_branch => branch_only += 1,// Nothing but the stale worktree entry went. An orphan branch- // never reaches here — it has no worktree entry, so no sibling- // checkout exists to retain it.+ // that kept its branch never reaches here — with no worktree+ // entry it removed nothing, and `try_remove` excludes the no-op+ // from the removed list entirely.CandidateKind::BranchOnly => worktree_only += 1,// A stale detached worktree never has a branch.CandidateKind::StaleDetached => worktree_only += 1,@@ -283,37 +288,40 @@ struct RemovalContext<'a> {/// run alone; write for uniformity with its post-switch hooks.fn removal_needs_write(candidate: &Candidate,- plan: Option<&RemoveResult>,+ plan: Option<&RemovalPlan>,ctx: &RemovalContext<'_>,) -> bool {match candidate.kind {CandidateKind::Current | CandidateKind::StaleDetached => true,CandidateKind::Other | CandidateKind::BranchOnly => match plan {None => true,- Some(RemoveResult::RemovedWorktree { worktree_path, .. }) => {+ Some(RemovalPlan::Worktree { worktree_path, .. }) => {ctx.foreground|| ctx.hook_plan.has_hooks_for(worktree_path, &[HookType::PreRemove, HookType::PostRemove])}- Some(RemoveResult::BranchOnly { .. }) => false,+ Some(RemovalPlan::BranchOnly { .. }) => false,},}}-/// Try to remove a candidate immediately. Returns Ok(true) if removed,-/// Ok(false) if skipped (preparation error), Err on execution error.+/// Try to remove a candidate immediately. Returns `Ok(Some(branch_deleted))`+/// if removed — the executed outcome the summary counts — `Ok(None)` if+/// skipped (preparation error), `Err` on execution error.////// `plan` is the scan-time `prepare_worktree_removal` result from/// [`check_one`]. `Prunable` candidates arrive plan-less and prepare here,/// under the write lock, because preparing them prunes stale worktree/// metadata. Scan-time plans may be stale by execution; the pre-rename-/// `ensure_clean` and the branch-delete CAS re-validate what matters.+/// `ensure_clean` and the branch-delete CAS re-validate what matters — and the+/// returned [`BranchFate`](crate::commands::worktree::BranchFate) is how a CAS+/// refusal reaches the summary.fn try_remove(candidate: &Candidate,- plan: Option<RemoveResult>,+ plan: Option<RemovalPlan>,ctx: &RemovalContext<'_>,-) -> anyhow::Result<bool> {+) -> anyhow::Result<Option<bool>> {let _span = Span::new(format!("prune-remove:{}", candidate.label));// Read side for the parallel default, write side for the exclusive cases// (see `removal_needs_write`). The guards protect `()` — there is no@@ -335,7 +343,8 @@ fn try_remove(if matches!(candidate.kind, CandidateKind::StaleDetached) {ctx.repo.prune_worktrees()?;- return Ok(true);+ // A stale detached entry has no branch to delete.+ return Ok(Some(false));}let plan = match plan {@@ -352,7 +361,7 @@ fn try_remove(Err(_) => {// prepare_worktree_removal is the gate: if the worktree can't// be removed (dirty, locked, etc.), it's simply not selected.- return Ok(false);+ return Ok(None);}},};@@ -360,17 +369,23 @@ fn try_remove(// `SynchronousForNonCurrent`: a rename-failure fallback completes inline,// so the candidate counts as removed only once the worktree and branch// are actually gone — before the final summary prints.- handle_remove_output(- &plan,- ctx.foreground,- ctx.hook_plan,- true,- false,- &mut announcer,- BackgroundFallbackMode::SynchronousForNonCurrent,- )?;+ let execution = if ctx.foreground {+ RemovalExecution::Foreground+ } else {+ RemovalExecution::Background(BackgroundFallbackMode::SynchronousForNonCurrent)+ };+ let fate = handle_remove_output(&plan, execution, ctx.hook_plan, true, &mut announcer)?;announcer.flush()?;- Ok(true)+ let branch_deleted = fate.deleted();+ // A branch-only candidate that kept its branch removed nothing at all —+ // unless planning pruned a stale worktree entry, a removal worth counting.+ // Excluding the no-op keeps the summary and JSON honest when a concurrent+ // writer advanced an orphan branch between scan and delete (the per-item+ // retention warning has already told the user).+ if !branch_deleted && let RemovalPlan::BranchOnly { pruned: false, .. } = plan {+ return Ok(None);+ }+ Ok(Some(branch_deleted))}/// One candidate skipped because its project hooks aren't yet approved.@@ -402,7 +417,7 @@ struct CheckOutcome {/// silently, never reported as "younger than") — except for `Prunable`/// items, which are always removable but plan in `try_remove`: preparing/// them calls `prune_worktrees()`, a mutation that must stay serialized.- plan: Option<RemoveResult>,+ plan: Option<RemovalPlan>,/// Whether the item passed the removability gate (see `plan`).removable: bool,/// What the removal takes, carried onto [`Candidate::deletes_branch`].@@ -1113,7 +1128,7 @@ pub fn step_prune(// closes once every worker has drained the job queue and exited,// so draining it below also waits out all in-flight printing.let (job_tx, job_rx) = chan::unbounded::<RemovalJob>();- let (done_tx, done_rx) = chan::unbounded::<(Candidate, anyhow::Result<bool>)>();+ let (done_tx, done_rx) = chan::unbounded::<(Candidate, anyhow::Result<Option<bool>>)>();let abort_ref = &abort;let removal_ctx_ref = &removal_ctx;// Empty check_items → zero workers, correctly: no jobs can queue.@@ -1232,10 +1247,15 @@ pub fn step_prune(let mut removed: Vec<Candidate> = Vec::new();let mut first_err: Option<anyhow::Error> = None;- for (candidate, result) in &done_rx {+ for (mut candidate, result) in &done_rx {match result {- Ok(true) => removed.push(candidate),- Ok(false) => {}+ // Record the executed outcome, not the scan's prediction —+ // what the summary and `--format=json` report.+ Ok(Some(branch_deleted)) => {+ candidate.deletes_branch = branch_deleted;+ removed.push(candidate);+ }+ Ok(None) => {}Err(err) if first_err.is_none() => first_err = Some(err),// Concurrent failures (e.g. one Ctrl-C killing every// in-flight child) all carry the same story; report the@@ -1263,9 +1283,11 @@ pub fn step_prune(// current worktree stays last.removed.sort_by_key(|c| c.check_idx);// Remove deferred current worktree last (cd-to-primary happens here)- if let Some((current, plan)) = deferred_current- && try_remove(¤t, plan, &removal_ctx).with_context(|| current.removal_context())?+ if let Some((mut current, plan)) = deferred_current+ && let Some(branch_deleted) =+ try_remove(¤t, plan, &removal_ctx).with_context(|| current.removal_context())?{+ current.deletes_branch = branch_deleted;removed.push(current);}diff --git a/src/commands/worktree/finish.rs b/src/commands/worktree/finish.rsindex 065dd3fbd..d61c4bb0a 100644--- a/src/commands/worktree/finish.rs+++ b/src/commands/worktree/finish.rs@@ -27,7 +27,7 @@ use worktrunk::config::UserConfig;use worktrunk::git::{BranchDeletionMode, Repository};use worktrunk::styling::{eprintln, info_message};-use super::types::{RemoveResult, SharedBranchCheckout};+use super::types::{RemovalPlan, SharedBranchCheckout};use crate::commands::command_executor::CommandContext;use crate::commands::context::CommandEnv;use crate::commands::hook_plan::{ApprovedHookPlan, register_planned};@@ -38,7 +38,8 @@ use crate::commands::repository_ext::{};use crate::commands::template_vars::TemplateVars;use crate::output::{- BackgroundFallbackMode, handle_remove_output, post_hook_display_path, pre_hook_display_path,+ BackgroundFallbackMode, RemovalExecution, handle_remove_output, post_hook_display_path,+ pre_hook_display_path,};/// Inputs to [`finish_after_merge`]. Owned by the caller; this struct just@@ -166,7 +167,7 @@ pub fn finish_after_merge(// No config snapshot: `pre-remove` / `post-remove` were selected and// frozen into `plan` at the gate (anchored at `feature_path`), so the// executor needs no config — it runs only the frozen `plan`.- let remove_result = RemoveResult::RemovedWorktree {+ let remove_result = RemovalPlan::Worktree {main_path: destination_path.clone(),worktree_path: worktree_root,changed_directory: true,@@ -178,14 +179,15 @@ pub fn finish_after_merge(removed_commit: feature_commit.clone(),branch_checked_out_at,};+ // The fate is dropped: merge's own reporting (`removed` in the JSON+ // blob, the removal messages) doesn't itemize the branch, and the+ // handler has already narrated any retention.handle_remove_output(&remove_result,- false,+ RemovalExecution::Background(BackgroundFallbackMode::Detached),plan,false,- false,announcer,- BackgroundFallbackMode::Detached,)?;true};diff --git a/src/commands/worktree/mod.rs b/src/commands/worktree/mod.rsindex 9cae3c3ac..ea0e19430 100644--- a/src/commands/worktree/mod.rs+++ b/src/commands/worktree/mod.rs@@ -55,11 +55,12 @@//!//! # Implementation Details//!-//! Result types (`SwitchResult`, `RemoveResult`) are pure data structures that only contain-//! operation results. All presentation logic is handled by the `output` module:+//! `SwitchResult` (an operation result) and `RemovalPlan` (a validated plan)+//! are pure data structures. Execution and presentation live in the `output`+//! module://!//! - `output::handle_switch_output()`: Formats and outputs switch operation results-//! - `output::handle_remove_output()`: Formats and outputs remove operation results+//! - `output::handle_remove_output()`: Executes a `RemovalPlan` and narrates it//!//! The output handlers check `is_shell_integration_active()` to determine if hints should//! be suppressed (when shell integration is already configured).@@ -95,5 +96,5 @@ pub use resolve::{compute_worktree_path, is_worktree_at_expected_path, worktree_pub(crate) use switch::SwitchPipeline;pub use switch::handle_switch_command;pub use types::{- MergeOperations, RemoveResult, SharedBranchCheckout, SwitchBranchInfo, SwitchResult,+ BranchFate, MergeOperations, RemovalPlan, SharedBranchCheckout, SwitchBranchInfo, SwitchResult,};diff --git a/src/commands/worktree/types.rs b/src/commands/worktree/types.rsindex d8b2a1733..33bcc552d 100644--- a/src/commands/worktree/types.rs+++ b/src/commands/worktree/types.rs@@ -4,7 +4,9 @@use std::path::{Path, PathBuf};-use worktrunk::git::{BranchDeletionMode, IntegrationReason, RefType};+use worktrunk::git::{+ BranchDeletionMode, BranchDeletionOutcome, BranchDeletionResult, IntegrationReason, RefType,+};/// Flags indicating which merge operations occurred#[derive(Debug, Clone, Copy)]@@ -169,10 +171,73 @@ impl SharedBranchCheckout {}}-/// Result of a worktree remove operation-pub enum RemoveResult {- /// Removed worktree and changed directory (if needed)- RemovedWorktree {+/// What actually happened to a [`RemovalPlan`]'s branch by the time the+/// executor returned — the observed counterpart of the intent the plan+/// carries.+///+/// Consumers that report deletions (the prune summary, `--format=json`) read+/// this rather than the plan, so a deletion the CAS refused or an unmerged+/// branch SafeDelete declined is never reported as deleted. `Deferred` is the+/// one case with nothing to observe; [`deleted`](Self::deleted) reports the+/// plan's intent there.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum BranchFate {+ /// No deletion was attempted: the plan had no branch (detached worktree)+ /// or retained it (`deletion_mode` Keep — shared checkout, or+ /// `--no-delete-branch`).+ NotAttempted,+ /// The deletion ran and the branch is gone.+ Deleted,+ /// The deletion ran and the branch survives: SafeDelete declined an+ /// unmerged branch, the CAS refused a moved ref, or the delete command+ /// itself failed (already narrated at the site that observed it).+ Retained,+ /// The deletion was handed to a detached background process (the legacy+ /// `git worktree remove` fallback) whose outcome this process never sees.+ ///+ /// Only planned deletions defer — a `Keep` plan or a branchless worktree+ /// has no deletion command to hand off, and every fallback arm maps those+ /// to [`NotAttempted`](Self::NotAttempted) — so `Deferred` implies the+ /// plan's intent was deletion.+ Deferred,+}++impl BranchFate {+ /// Map a synchronous deletion attempt's result. `None` means no attempt+ /// was made.+ pub fn from_result(result: Option<&anyhow::Result<BranchDeletionResult>>) -> Self {+ match result {+ None => Self::NotAttempted,+ Some(Ok(r)) => match r.outcome {+ BranchDeletionOutcome::Integrated(_) | BranchDeletionOutcome::ForceDeleted => {+ Self::Deleted+ }+ BranchDeletionOutcome::NotDeleted | BranchDeletionOutcome::RetainedRaced => {+ Self::Retained+ }+ },+ Some(Err(_)) => Self::Retained,+ }+ }++ /// Whether the branch was deleted, best knowledge: the observed outcome+ /// where one exists, the plan's intent for `Deferred` (which is always+ /// deletion — see the variant doc).+ pub fn deleted(&self) -> bool {+ matches!(self, Self::Deleted | Self::Deferred)+ }+}++/// A validated, planned removal — what `prepare_worktree_removal` decided to+/// remove and how, before anything runs.+///+/// Produced by the planner, executed by `output::handle_remove_output`. The+/// deletion-relevant fields are intent, not fact: `deletion_mode` says what the+/// executor should attempt, and the actual deletion re-decides against fresh+/// refs (`delete_branch_if_safe`'s CAS).+pub enum RemovalPlan {+ /// Remove a worktree, changing directory away from it first if it's current.+ Worktree {/// Stable working directory for post-removal execution: hooks run here,/// background removal spawns from here, and `cd` directs the shell here./// Usually the primary worktree; falls back to cwd when removing the@@ -207,7 +272,7 @@ pub enum RemoveResult {BranchOnly {branch_name: String,deletion_mode: BranchDeletionMode,- /// True if the worktree was pruned before returning this result.+ /// True if a stale worktree entry was pruned during planning.pruned: bool,/// Integration target for display. May be the effective target (e.g.,/// `origin/main` when upstream is ahead) or the local default branch.@@ -225,16 +290,16 @@ pub enum RemoveResult {},}-impl RemoveResult {- /// Path of the removed worktree, if this result removed one.+impl RemovalPlan {+ /// Path of the worktree this plan removes, if it removes one.////// `None` for branch-only deletions — they have no worktree, so no/// `pre-remove` hook runs and there's no worktree-local `.config/wt.toml`/// to consult.pub fn removed_worktree_path(&self) -> Option<&Path> {match self {- RemoveResult::RemovedWorktree { worktree_path, .. } => Some(worktree_path),- RemoveResult::BranchOnly { .. } => None,+ RemovalPlan::Worktree { worktree_path, .. } => Some(worktree_path),+ RemovalPlan::BranchOnly { .. } => None,}}@@ -246,46 +311,51 @@ impl RemoveResult {#[cfg(unix)]pub fn branch_name(&self) -> Option<&str> {match self {- RemoveResult::RemovedWorktree { branch_name, .. } => branch_name.as_deref(),- RemoveResult::BranchOnly { branch_name, .. } => Some(branch_name),+ RemovalPlan::Worktree { branch_name, .. } => branch_name.as_deref(),+ RemovalPlan::BranchOnly { branch_name, .. } => Some(branch_name),}}/// Post-removal working directory — where the user lands, and the worktree/// whose `.config/wt.toml` `post-switch` reads. `None` for branch-only/// deletions (no worktree was removed, so nothing was switched away from).- /// See the `main_path` field docs on [`RemoveResult::RemovedWorktree`].+ /// See the `main_path` field docs on [`RemovalPlan::Worktree`].pub fn destination_path(&self) -> Option<&Path> {match self {- RemoveResult::RemovedWorktree { main_path, .. } => Some(main_path),- RemoveResult::BranchOnly { .. } => None,+ RemovalPlan::Worktree { main_path, .. } => Some(main_path),+ RemovalPlan::BranchOnly { .. } => None,}}- /// Whether this removal deletes a branch.+ /// Whether this plan intends to delete a branch.////// False for a detached worktree, which has none, and false whenever a/// sibling checkout forced `deletion_mode` to [`BranchDeletionMode::Keep`]- /// (see [`SharedBranchCheckout`]). What the plan intends, not what the- /// delete returned: a `SafeDelete` still re-decides against fresh refs, and- /// a background removal hasn't run yet — so this answers the same question- /// the removal message answers when it says "worktree" rather than- /// "worktree & branch".+ /// (see [`SharedBranchCheckout`]). Intent only: a `SafeDelete` still+ /// re-decides against fresh refs at execution, so anything reporting what+ /// happened reads [`BranchFate`]; this is what the scan-time predictions+ /// (prune's dry run) print, and the question the progress message answers+ /// when it says "worktree" rather than "worktree & branch".pub fn deletes_branch(&self) -> bool {match self {- RemoveResult::RemovedWorktree {+ RemovalPlan::Worktree {branch_name,deletion_mode,..} => branch_name.is_some() && !deletion_mode.should_keep(),- RemoveResult::BranchOnly { deletion_mode, .. } => !deletion_mode.should_keep(),+ RemovalPlan::BranchOnly { deletion_mode, .. } => !deletion_mode.should_keep(),}}/// Convert to a JSON value for structured output.- pub fn to_json(&self) -> serde_json::Value {+ ///+ /// `fate` is what execution reported back; `branch_deleted` is derived+ /// from it (via [`BranchFate::deleted`]) so the payload states what+ /// happened, not what the plan hoped.+ pub fn to_json(&self, fate: BranchFate) -> serde_json::Value {+ let branch_deleted = fate.deleted();match self {- RemoveResult::RemovedWorktree {+ RemovalPlan::Worktree {worktree_path,branch_name,branch_checked_out_at,@@ -294,10 +364,10 @@ impl RemoveResult {"kind": "worktree","branch": branch_name,"path": worktree_path,- "branch_deleted": self.deletes_branch(),+ "branch_deleted": branch_deleted,"branch_checked_out_at": branch_checked_out_at.as_ref().map(|c| &c.path),}),- RemoveResult::BranchOnly {+ RemovalPlan::BranchOnly {branch_name,pruned,branch_checked_out_at,@@ -306,7 +376,7 @@ impl RemoveResult {"kind": "branch_only","branch": branch_name,"pruned": pruned,- "branch_deleted": self.deletes_branch(),+ "branch_deleted": branch_deleted,"branch_checked_out_at": branch_checked_out_at.as_ref().map(|c| &c.path),}),}@@ -327,7 +397,7 @@ mod tests {#[cfg(unix)]#[test]fn remove_result_branch_name_reads_both_variants() {- let removed = RemoveResult::RemovedWorktree {+ let removed = RemovalPlan::Worktree {main_path: PathBuf::from("/main"),worktree_path: PathBuf::from("/wt"),changed_directory: false,@@ -341,7 +411,7 @@ mod tests {};assert_eq!(removed.branch_name(), Some("feature"));- let branch_only = RemoveResult::BranchOnly {+ let branch_only = RemovalPlan::BranchOnly {branch_name: "solo".to_string(),deletion_mode: BranchDeletionMode::default(),pruned: false,@@ -352,6 +422,61 @@ mod tests {assert_eq!(branch_only.branch_name(), Some("solo"));}+ /// The fate→deleted mapping: an observed deletion counts, a deferral+ /// reports the intent it carried (always deletion), and a raced or+ /// declined deletion (`Retained`) reports false even though the plan+ /// meant to delete — that divergence is the whole point of tracking fate+ /// separately.+ #[test]+ fn branch_fate_deleted_mapping() {+ let cases = [+ (BranchFate::Deleted, true),+ (BranchFate::Deferred, true),+ (BranchFate::Retained, false),+ (BranchFate::NotAttempted, false),+ ];+ for (fate, deleted) in cases {+ assert_eq!(fate.deleted(), deleted, "{fate:?}");+ }+ }++ /// Synchronous deletion results map onto fates: deletions count, refusals+ /// and errors read as the branch surviving, absence as never attempted.+ #[test]+ fn branch_fate_from_result_mapping() {+ use worktrunk::git::IntegrationReason;++ let fate = |outcome| {+ BranchFate::from_result(Some(&Ok(BranchDeletionResult {+ outcome,+ integration_target: "main".to_string(),+ })))+ };+ assert_eq!(+ fate(BranchDeletionOutcome::Integrated(+ IntegrationReason::SameCommit+ )),+ BranchFate::Deleted+ );+ assert_eq!(+ fate(BranchDeletionOutcome::ForceDeleted),+ BranchFate::Deleted+ );+ assert_eq!(+ fate(BranchDeletionOutcome::NotDeleted),+ BranchFate::Retained+ );+ assert_eq!(+ fate(BranchDeletionOutcome::RetainedRaced),+ BranchFate::Retained+ );+ assert_eq!(+ BranchFate::from_result(Some(&Err(anyhow::anyhow!("boom")))),+ BranchFate::Retained+ );+ assert_eq!(BranchFate::from_result(None), BranchFate::NotAttempted);+ }+#[test]fn test_switch_result_path_existing() {let path = PathBuf::from("/test/existing");@@ -391,7 +516,7 @@ mod tests {#[test]fn test_remove_result_removed_worktree() {- let result = RemoveResult::RemovedWorktree {+ let result = RemovalPlan::Worktree {main_path: PathBuf::from("/main"),worktree_path: PathBuf::from("/worktree"),changed_directory: true,@@ -404,7 +529,7 @@ mod tests {branch_checked_out_at: None,};match result {- RemoveResult::RemovedWorktree {+ RemovalPlan::Worktree {main_path,worktree_path,changed_directory,@@ -427,13 +552,13 @@ mod tests {assert_eq!(removed_commit.as_deref(), Some("abc1234567890"));assert!(branch_checked_out_at.is_none());}- _ => panic!("Expected RemovedWorktree variant"),+ _ => panic!("Expected Worktree variant"),}}#[test]fn test_remove_result_branch_only() {- let result = RemoveResult::BranchOnly {+ let result = RemovalPlan::BranchOnly {branch_name: "stale-branch".to_string(),deletion_mode: BranchDeletionMode::Keep,pruned: false,@@ -442,7 +567,7 @@ mod tests {branch_checked_out_at: None,};match result {- RemoveResult::BranchOnly {+ RemovalPlan::BranchOnly {branch_name,deletion_mode,pruned,@@ -464,7 +589,7 @@ mod tests {#[test]fn test_remove_result_branch_only_pruned() {- let result = RemoveResult::BranchOnly {+ let result = RemovalPlan::BranchOnly {branch_name: "pruned-branch".to_string(),deletion_mode: BranchDeletionMode::SafeDelete,pruned: true,@@ -473,7 +598,7 @@ mod tests {branch_checked_out_at: None,};match result {- RemoveResult::BranchOnly {+ RemovalPlan::BranchOnly {branch_name,deletion_mode,pruned,@@ -494,7 +619,7 @@ mod tests {#[test]fn test_remove_result_with_force_delete() {- let result = RemoveResult::RemovedWorktree {+ let result = RemovalPlan::Worktree {main_path: PathBuf::from("/main"),worktree_path: PathBuf::from("/worktree"),changed_directory: false,@@ -507,7 +632,7 @@ mod tests {branch_checked_out_at: None,};match result {- RemoveResult::RemovedWorktree {+ RemovalPlan::Worktree {branch_name,deletion_mode,force_worktree,@@ -517,7 +642,7 @@ mod tests {assert!(deletion_mode.is_force());assert!(force_worktree);}- _ => panic!("Expected RemovedWorktree variant"),+ _ => panic!("Expected Worktree variant"),}}}diff --git a/src/git/mod.rs b/src/git/mod.rsindex b1744a90b..0ef364cfe 100644--- a/src/git/mod.rs+++ b/src/git/mod.rs@@ -75,8 +75,8 @@ pub use parse::{parse_porcelain_z, parse_untracked_files};pub use recover::{current_or_recover, cwd_removed_hint};pub use remove::{BranchDeletionMode, BranchDeletionOutcome, BranchDeletionResult, RemovalOutput, RemoveOptions,- delete_branch_if_safe, remove_worktree_with_cleanup, stage_worktree_removal,- stop_fsmonitor_daemon,+ delete_branch_if_safe, execute_branch_deletion, remove_worktree_with_cleanup,+ stage_worktree_removal, stop_fsmonitor_daemon,};pub use repository::sha_cache;pub use repository::{diff --git a/src/git/remove.rs b/src/git/remove.rsindex c80fae8ef..9a7824bb7 100644--- a/src/git/remove.rs+++ b/src/git/remove.rs@@ -406,6 +406,29 @@ pub fn stage_worktree_removal(repo: &Repository, worktree_path: &Path) -> Option}}+/// Capture fresh refs and run a planned branch deletion.+///+/// The spelling of "the plan said delete; do it now" for every synchronous+/// site that doesn't already hold a fresh snapshot (the background fast path,+/// prune's synchronous fallback, branch-only removal, a picker row). The+/// invariant it carries — no deletion ever runs against the planning-time+/// snapshot, so the CAS in [`delete_branch_if_safe`] re-decides against the+/// live ref — also holds on the two paths that don't call it: the foreground+/// removal captures its own fresh snapshot just before+/// [`remove_worktree_with_cleanup`], and the detached fallback can't call+/// Rust, so it gets the guarantee from an `update-ref -d <ref> <sha>` shell+/// tail instead. A hook or concurrent process that advanced the branch since+/// planning surfaces as `RetainedRaced`, not a lost commit.+pub fn execute_branch_deletion(+ repo: &Repository,+ branch_name: &str,+ target: &str,+ force_delete: bool,+) -> anyhow::Result<BranchDeletionResult> {+ let snapshot = repo.capture_refs()?;+ delete_branch_if_safe(repo, &snapshot, branch_name, target, force_delete)+}+/// Delete a branch if its content is integrated into the target, or if/// `force_delete` is set.///diff --git a/src/output/handlers.rs b/src/output/handlers.rsindex fc451f21d..0a142c1cb 100644--- a/src/output/handlers.rs+++ b/src/output/handlers.rs@@ -18,7 +18,7 @@ use crate::commands::process::{};use crate::commands::worktree::hooks::PostRemoveContext;use crate::commands::worktree::{- RemoveResult, SharedBranchCheckout, SwitchBranchInfo, SwitchResult,+ BranchFate, RemovalPlan, SharedBranchCheckout, SwitchBranchInfo, SwitchResult,};use worktrunk::config::UserConfig;use worktrunk::git::ErrorExt;@@ -28,7 +28,7 @@ use worktrunk::git::Repository;use worktrunk::git::path_dir_name;use worktrunk::git::{BranchDeletionMode, BranchDeletionOutcome, BranchDeletionResult, RemoveOptions,- delete_branch_if_safe, remove_worktree_with_cleanup, stage_worktree_removal,+ execute_branch_deletion, remove_worktree_with_cleanup, stage_worktree_removal,stop_fsmonitor_daemon,};use worktrunk::path::format_path_for_display;@@ -109,6 +109,25 @@ pub enum BackgroundFallbackMode {SynchronousForNonCurrent,}+/// How [`handle_remove_output`] executes a [`RemovalPlan`]: one axis, one+/// value — inline with chrome, staged-and-detached with chrome, or inline+/// with none.+#[derive(Clone, Copy)]+pub enum RemovalExecution {+ /// Remove inline and report actual outcomes: progress message, spinner+ /// over the trash cleanup, success message from what really happened.+ Foreground,+ /// Announce, then stage the worktree into trash and hand the `rm -rf` to a+ /// detached process; the branch deletion still runs synchronously on the+ /// fast path. The mode says what happens when the rename-into-trash fails.+ Background(BackgroundFallbackMode),+ /// The TUI (picker) path: the same inline removal as `Foreground` with no+ /// terminal output, no spinner, and no `cd` directive — skim owns the+ /// terminal. Only [`RemovalPlan::Worktree`] arrives here; the picker+ /// deletes branch-only rows directly via `execute_branch_deletion`.+ Silent,+}+enum BackgroundRemovalPlan {Detached(String),CompletedSynchronously,@@ -118,15 +137,17 @@ enum BackgroundRemovalPlan {/// rename-then-prune, spawn detached rm.////// Shared sequence for both detached HEAD and branch background removal paths.-/// The caller is responsible for output messages before this call, and hooks after.+/// The caller is responsible for output messages before this call, and hooks+/// after. Returns the branch's fate — known synchronously on every path except+/// the detached fallback, whose CAS tail runs after this process exits.fn spawn_background_removal(repo: &Repository,main_path: &Path,removal: &BackgroundRemoval<'_>,log_label: &str,fallback_mode: BackgroundFallbackMode,-) -> anyhow::Result<()> {- let remove_plan = execute_instant_removal_or_fallback(repo, removal, fallback_mode)?;+) -> anyhow::Result<BranchFate> {+ let (remove_plan, fate) = execute_instant_removal_or_fallback(repo, removal, fallback_mode)?;if let BackgroundRemovalPlan::Detached(remove_command) = remove_plan {spawn_detached(@@ -138,7 +159,7 @@ fn spawn_background_removal(None,)?;}- Ok(())+ Ok(fate)}/// Execute instant worktree removal via rename-then-prune.@@ -156,7 +177,7 @@ fn execute_instant_removal_or_fallback(repo: &Repository,removal: &BackgroundRemoval<'_>,fallback_mode: BackgroundFallbackMode,-) -> anyhow::Result<BackgroundRemovalPlan> {+) -> anyhow::Result<(BackgroundRemovalPlan, BranchFate)> {let BackgroundRemoval {worktree_path,branch_name,@@ -184,22 +205,22 @@ fn execute_instant_removal_or_fallback(// prune git metadata, then background process just does `rm -rf`.if let Some(staged_path) = stage_worktree_removal(repo, worktree_path) {// Delete branch synchronously now that prune has removed the worktree metadata.- // Re-capture refs here rather than trusting the pre-hook planning- // decision: hooks or concurrent processes may have advanced the branch.- if let Some(branch) = branch_name+ // Fresh refs, not the pre-hook planning decision: hooks or concurrent+ // processes may have advanced the branch (`execute_branch_deletion`).+ let fate = if let Some(branch) = branch_name&& !deletion_mode.should_keep(){- let result = repo.capture_refs().and_then(|snapshot| {- delete_branch_if_safe(- repo,- &snapshot,- branch,- target_branch.unwrap_or("HEAD"),- deletion_mode.is_force(),- )- });+ let result = execute_branch_deletion(+ repo,+ branch,+ target_branch.unwrap_or("HEAD"),+ deletion_mode.is_force(),+ );warn_if_branch_retained(branch, &result, planner_expected_retention);- }+ BranchFate::from_result(Some(&result))+ } else {+ BranchFate::NotAttempted+ };if changed_directory {// Create an empty placeholder at the original path so the shell's working// directory ($env.PWD) remains valid until the wrapper has cd'd away.@@ -209,8 +230,13 @@ fn execute_instant_removal_or_fallback(// is that Nushell may still emit PWD errors — not a correctness issue.let _ = std::fs::create_dir(worktree_path);}- Ok(BackgroundRemovalPlan::Detached(- build_remove_command_staged(&staged_path, worktree_path, changed_directory),+ Ok((+ BackgroundRemovalPlan::Detached(build_remove_command_staged(+ &staged_path,+ worktree_path,+ changed_directory,+ )),+ fate,))} else {if matches!(@@ -219,7 +245,7 @@ fn execute_instant_removal_or_fallback() && !changed_directory{repo.remove_worktree(worktree_path, force_worktree)?;- if let Some(branch) = branch_name+ let fate = if let Some(branch) = branch_name&& !deletion_mode.should_keep(){delete_branch_in_synchronous_fallback(@@ -228,9 +254,11 @@ fn execute_instant_removal_or_fallback(target_branch,deletion_mode,planner_expected_retention,- );- }- return Ok(BackgroundRemovalPlan::CompletedSynchronously);+ )+ } else {+ BranchFate::NotAttempted+ };+ return Ok((BackgroundRemovalPlan::CompletedSynchronously, fate));}// Fallback: cross-filesystem, permissions, Windows file locking, etc.@@ -244,33 +272,64 @@ fn execute_instant_removal_or_fallback(// all accepted), and the CAS protects against tip movement between// the foreground check and the detached delete. Force-delete keeps// the unconditional `git branch -D` shell tail.- let command = match (branch_name, deletion_mode) {- (Some(branch), BranchDeletionMode::ForceDelete) => build_remove_command(- worktree_path,- Some(branch),- force_worktree,- changed_directory,- ),- (Some(branch), BranchDeletionMode::SafeDelete) => {- let cas_tail = build_cas_branch_delete_tail(repo, branch, target_branch);- build_remove_command_with_tail(+ let (command, fate) = match (branch_name, deletion_mode) {+ (Some(branch), BranchDeletionMode::ForceDelete) => (+ build_remove_command(worktree_path,+ Some(branch),force_worktree,changed_directory,- cas_tail.as_deref(),+ ),+ BranchFate::Deferred,+ ),+ (Some(branch), BranchDeletionMode::SafeDelete) => {+ let cas_tail = build_cas_branch_delete_tail(repo, branch, target_branch);+ // No tail means the foreground integration check declined (or+ // couldn't run): the detached process won't touch the branch,+ // so its survival is known here, not deferred — and when the+ // planner promised deletion, the progress message already said+ // "worktree & branch", so the survival gets the same+ // correction the fast path emits. (A check that errored+ // collapses into this: it couldn't confirm integration, which+ // is the message's effective claim.)+ let fate = match cas_tail {+ Some(_) => BranchFate::Deferred,+ None => {+ warn_if_branch_retained(+ branch,+ &Ok(BranchDeletionResult {+ outcome: BranchDeletionOutcome::NotDeleted,+ integration_target: target_branch.unwrap_or("HEAD").to_string(),+ }),+ planner_expected_retention,+ );+ BranchFate::Retained+ }+ };+ (+ build_remove_command_with_tail(+ worktree_path,+ force_worktree,+ changed_directory,+ cas_tail.as_deref(),+ ),+ fate,)}- _ => build_remove_command(worktree_path, None, force_worktree, changed_directory),+ _ => (+ build_remove_command(worktree_path, None, force_worktree, changed_directory),+ BranchFate::NotAttempted,+ ),};- Ok(BackgroundRemovalPlan::Detached(command))+ Ok((BackgroundRemovalPlan::Detached(command), fate))}}/// Delete the just-removed worktree's branch in the synchronous fallback path.////// Only `wt step prune` reaches this (via `SynchronousForNonCurrent`). Mirrors-/// the fast path above by re-capturing refs and calling `delete_branch_if_safe`,-/// so squash-merged / patch-id-matched branches that prune accepted as candidates+/// the fast path above via `execute_branch_deletion` (fresh refs + CAS), so+/// squash-merged / patch-id-matched branches that prune accepted as candidates/// are deleted here too — a plain `git branch -d` would refuse them on/// reachability from HEAD alone and leave the branch behind while the worktree/// was already removed. The caller filters out `None` branches and `Keep` modes.@@ -280,17 +339,15 @@ fn delete_branch_in_synchronous_fallback(target_branch: Option<&str>,deletion_mode: BranchDeletionMode,planner_expected_retention: bool,-) {- let result = repo.capture_refs().and_then(|snapshot| {- delete_branch_if_safe(- repo,- &snapshot,- branch,- target_branch.unwrap_or("HEAD"),- deletion_mode.is_force(),- )- });+) -> BranchFate {+ let result = execute_branch_deletion(+ repo,+ branch,+ target_branch.unwrap_or("HEAD"),+ deletion_mode.is_force(),+ );warn_if_branch_retained(branch, &result, planner_expected_retention);+ BranchFate::from_result(Some(&result))}/// Surface the residual branch when `delete_branch_if_safe` returned an@@ -298,8 +355,9 @@ fn delete_branch_in_synchronous_fallback(////// The worktree has already been removed by the time this runs, so silently/// dropping the branch-deletion outcome (the prior behavior) left the user-/// with no signal that the branch survived. Both the fast path and the-/// synchronous fallback route through here so the message is consistent.+/// with no signal that the branch survived. The fast path, the synchronous+/// fallback, and the detached fallback's known-retained arm (no CAS tail to+/// append) all route through here so the message is consistent.////// - `Ok(RetainedRaced)`: atomic CAS rejected the delete because the ref/// tip moved between integration check and delete (a hook, a concurrent@@ -997,7 +1055,15 @@ pub fn execute_user_command(command: &str, display_path: Option<&Path>) -> anyhoOk(())}-/// Handle output for a remove operation+/// Execute a [`RemovalPlan`] and narrate it per `execution`.+///+/// Returns the branch's [`BranchFate`] so callers report what happened rather+/// than what the plan intended — the prune summary and `--format=json` both+/// read it. Worktree-removal failures propagate as `Err`, and for a+/// `Worktree` plan a surviving branch is a fate, not an error — the removal+/// was the primary operation. For a `BranchOnly` plan the deletion *is* the+/// operation, so a hard command failure (not a declined or raced deletion)+/// still propagates as `Err`.////// Approval is handled at the gate (command entry point), not here. The/// `announcer`'s `show_branch` setting (set by the caller) controls whether@@ -1005,37 +1071,32 @@ pub fn execute_user_command(command: &str, display_path: Option<&Path>) -> anyho/// When `quiet` is true (prune context), suppresses informational messages/// like "No worktree found for branch X" that are noise in batch operations.///-/// `plan` is the frozen, approved hook set; an empty plan (`--no-hooks`,+/// `hook_plan` is the frozen, approved hook set; an empty plan (`--no-hooks`,/// declined, or no project config) runs no project hooks. `pre-remove` //// `post-remove` / `post-switch` execute only from it — the selection was/// frozen at the gate, never re-read.///-/// When `silent` is true (the TUI picker — this runs while skim owns the-/// terminal), a `RemovedWorktree` result is removed with no progress/success+/// [`RemovalExecution::Silent`] (the TUI picker — this runs while skim owns+/// the terminal) removes a `Worktree` plan inline with no progress/success/// messages, no trash-cleanup spinner, and no `cd` directive: just the git-/// removal plus the planned `pre-remove` / `post-remove` / `post-switch`-/// hooks. (The picker can't prompt mid-render, so its `plan` comes from a-/// read-only `Approvals` filter — see `do_removal`.) The removal runs inline-/// regardless of `foreground` (there's no detached `rm` to background to).-/// `silent` has no effect on `BranchOnly` results — the picker handles that-/// arm itself.+/// removal plus the planned hooks. (The picker can't prompt mid-render, so its+/// `hook_plan` comes from a read-only `Approvals` filter — see `do_removal`.)///-/// `background_fallback_mode` selects how a background removal whose-/// rename-into-trash fast path fails behaves: every caller but `wt step prune`-/// passes [`BackgroundFallbackMode::Detached`] (spawn the legacy `git worktree+/// The [`BackgroundFallbackMode`] inside [`RemovalExecution::Background`]+/// selects how a removal whose rename-into-trash fast path fails behaves:+/// every caller but `wt step prune` passes+/// [`BackgroundFallbackMode::Detached`] (spawn the legacy `git worktree/// remove`); prune passes [`BackgroundFallbackMode::SynchronousForNonCurrent`]/// so a candidate's removal is complete by the time prune reports it removed.pub fn handle_remove_output(- result: &RemoveResult,- foreground: bool,- plan: &ApprovedHookPlan,+ plan: &RemovalPlan,+ execution: RemovalExecution,+ hook_plan: &ApprovedHookPlan,quiet: bool,- silent: bool,announcer: &mut HookAnnouncer<'_>,- background_fallback_mode: BackgroundFallbackMode,-) -> anyhow::Result<()> {- match result {- RemoveResult::RemovedWorktree {+) -> anyhow::Result<BranchFate> {+ match plan {+ RemovalPlan::Worktree {main_path,worktree_path,changed_directory,@@ -1047,7 +1108,7 @@ pub fn handle_remove_output(removed_commit,branch_checked_out_at,} => handle_removed_worktree_output(- RemovedWorktreeOutputContext {+ WorktreeRemovalContext {main_path,worktree_path,changed_directory: *changed_directory,@@ -1058,14 +1119,12 @@ pub fn handle_remove_output(force_worktree: *force_worktree,removed_commit: removed_commit.as_deref(),branch_checked_out_at: branch_checked_out_at.as_ref(),- plan,- foreground,- silent,- background_fallback_mode,+ hook_plan,+ execution,},announcer,),- RemoveResult::BranchOnly {+ RemovalPlan::BranchOnly {branch_name,deletion_mode,pruned,@@ -1096,7 +1155,7 @@ fn handle_branch_only_output(target_branch: Option<&str>,branch_checked_out_at: Option<&SharedBranchCheckout>,quiet: bool,-) -> anyhow::Result<()> {+) -> anyhow::Result<BranchFate> {let branch_info = if pruned {cformat!("Worktree directory missing for <bold>{branch_name}</>; pruned")} else {@@ -1112,26 +1171,22 @@ fn handle_branch_only_output(print_branch_checked_out_elsewhere(branch_name, shared);}stderr().flush()?;- return Ok(());+ return Ok(BranchFate::NotAttempted);}let check_target = target_branch.unwrap_or("HEAD");// Force-delete bypasses CAS entirely — `git branch -D` is the user's// explicit override. For safe-delete with a pre-computed integration- // reason, re-run `delete_branch_if_safe`: a fresh snapshot lets the- // atomic CAS in there catch any tip movement since planning, rather than- // trusting the planner's stale view of the ref.+ // reason, re-run the deletion against fresh refs+ // (`execute_branch_deletion`): the atomic CAS catches any tip movement+ // since planning, rather than trusting the planner's stale view of the ref.let deletion = if let Some(integrated_reason) = integration_reason&& !deletion_mode.is_force(){let repo = worktrunk::git::Repository::current()?;- let result = repo- .capture_refs()- .and_then(|snapshot| {- delete_branch_if_safe(&repo, &snapshot, branch_name, check_target, false)- })- .map(|mut r| {+ let result =+ execute_branch_deletion(&repo, branch_name, check_target, false).map(|mut r| {// Preserve the planner's recorded reason so a CAS-accepted// delete still reports the original "integrated because X"// explanation. The fresh integration target stays as the@@ -1206,7 +1261,14 @@ fn handle_branch_only_output(}stderr().flush()?;- Ok(())+ Ok(match deletion.result.outcome {+ BranchDeletionOutcome::Integrated(_) | BranchDeletionOutcome::ForceDeleted => {+ BranchFate::Deleted+ }+ BranchDeletionOutcome::NotDeleted | BranchDeletionOutcome::RetainedRaced => {+ BranchFate::Retained+ }+ })}/// Register post-remove and post-switch hooks after worktree removal onto the@@ -1222,7 +1284,7 @@ fn handle_branch_only_output(/// Only runs if `ctx.verify` is true (hooks approved).fn spawn_hooks_after_remove(repo: &Repository,- ctx: &RemovedWorktreeOutputContext<'_>,+ ctx: &WorktreeRemovalContext<'_>,removed_branch: &str,announcer: &mut HookAnnouncer<'_>,) -> anyhow::Result<()> {@@ -1250,11 +1312,11 @@ fn spawn_hooks_after_remove(let remove_ctx = CommandContext::new(repo, &config, Some(removed_branch), ctx.main_path, false);// `post-remove` is *about* the removed worktree (gone by now); it was- // selected and frozen into `plan` at the gate, anchored at the removed+ // selected and frozen into `hook_plan` at the gate, anchored at the removed// worktree path. `remove_ctx` (rooted at `ctx.main_path`) only renders.register_planned(announcer,- ctx.plan,+ ctx.hook_plan,ctx.worktree_path,&remove_ctx,worktrunk::HookType::PostRemove,@@ -1270,7 +1332,7 @@ fn spawn_hooks_after_remove(CommandContext::new(repo, &config, dest_branch.as_deref(), ctx.main_path, false);register_planned(announcer,- ctx.plan,+ ctx.hook_plan,ctx.main_path,&switch_ctx,worktrunk::HookType::PostSwitch,@@ -1503,7 +1565,7 @@ impl RemovalDisplayInfo {// ============================================================================-struct RemovedWorktreeOutputContext<'a> {+struct WorktreeRemovalContext<'a> {main_path: &'a Path,worktree_path: &'a Path,changed_directory: bool,@@ -1521,18 +1583,28 @@ struct RemovedWorktreeOutputContext<'a> {/// The frozen, approved hook plan. `pre-remove` / `post-remove` //// `post-switch` execute only from this — no `.config/wt.toml` re-read,/// no `ProjectConfig` snapshot to thread.- plan: &'a ApprovedHookPlan,- foreground: bool,- /// TUI (picker) path: do the git removal and hook registration but emit no- /// progress/success messages, no trash-cleanup spinner, and no `cd`- /// directive — see [`handle_remove_output`].- silent: bool,- background_fallback_mode: BackgroundFallbackMode,+ hook_plan: &'a ApprovedHookPlan,+ execution: RemovalExecution,+}++impl WorktreeRemovalContext<'_> {+ /// The fallback mode for a background removal. Only the background paths+ /// consult this; they are reached only via [`RemovalExecution::Background`],+ /// so the other arms default to the standard detached fallback rather than+ /// carrying an unreachable panic in the removal path.+ fn background_fallback(&self) -> BackgroundFallbackMode {+ match self.execution {+ RemovalExecution::Background(mode) => mode,+ RemovalExecution::Foreground | RemovalExecution::Silent => {+ BackgroundFallbackMode::Detached+ }+ }+ }}fn execute_pre_remove_hooks_if_needed(repo: &Repository,- ctx: &RemovedWorktreeOutputContext<'_>,+ ctx: &WorktreeRemovalContext<'_>,) -> anyhow::Result<()> {let Ok(config) = UserConfig::load() else {return Ok(());@@ -1540,7 +1612,7 @@ fn execute_pre_remove_hooks_if_needed(// `pre-remove` runs in the worktree being removed (still on disk here).// `pre_remove_repo` roots the *render* context there for template vars;- // the command set is the frozen `plan` selected at the gate, so no+ // the command set is the frozen `hook_plan` selected at the gate, so no// `.config/wt.toml` is re-read here.let pre_remove_repo = Repository::at(ctx.worktree_path)?;let command_ctx = CommandContext::new(@@ -1568,7 +1640,7 @@ fn execute_pre_remove_hooks_if_needed(];execute_planned_hook(- ctx.plan,+ ctx.hook_plan,ctx.worktree_path,&command_ctx,worktrunk::HookType::PreRemove,@@ -1605,10 +1677,10 @@ fn prepare_remove_directory_change(fn handle_detached_removed_worktree_output(repo: &Repository,- ctx: &RemovedWorktreeOutputContext<'_>,+ ctx: &WorktreeRemovalContext<'_>,announcer: &mut HookAnnouncer<'_>,-) -> anyhow::Result<()> {- if ctx.foreground {+) -> anyhow::Result<BranchFate> {+ if matches!(ctx.execution, RemovalExecution::Foreground) {eprintln!("{}",progress_message(cformat!(@@ -1672,22 +1744,22 @@ fn handle_detached_removed_worktree_output(planner_expected_retention: true,},"detached",- ctx.background_fallback_mode,+ ctx.background_fallback(),)?;}// Post-remove hooks for detached HEAD use "HEAD" as the branch identifierspawn_hooks_after_remove(repo, ctx, "HEAD", announcer)?;stderr().flush()?;- Ok(())+ Ok(BranchFate::NotAttempted)}fn handle_named_removed_worktree_foreground(repo: &Repository,- ctx: &RemovedWorktreeOutputContext<'_>,+ ctx: &WorktreeRemovalContext<'_>,branch_name: &str,announcer: &mut HookAnnouncer<'_>,-) -> anyhow::Result<()> {+) -> anyhow::Result<BranchFate> {eprintln!("{}",progress_message(cformat!("Removing <bold>{branch_name}</> worktree..."))@@ -1717,6 +1789,10 @@ fn handle_named_removed_worktree_foreground(.map(cleanup_staged_with_progress).unwrap_or((0, 0));+ // The observed fate, read before the display path consumes (and, on Err,+ // propagates) the deletion result.+ let fate = BranchFate::from_result(output.branch_result.as_ref());+let display_info = RemovalDisplayInfo::from_branch_result(output.branch_result,branch_name,@@ -1734,15 +1810,15 @@ fn handle_named_removed_worktree_foreground(spawn_hooks_after_remove(repo, ctx, branch_name, announcer)?;stderr().flush()?;- Ok(())+ Ok(fate)}fn handle_named_removed_worktree_background(repo: &Repository,- ctx: &RemovedWorktreeOutputContext<'_>,+ ctx: &WorktreeRemovalContext<'_>,branch_name: &str,announcer: &mut HookAnnouncer<'_>,-) -> anyhow::Result<()> {+) -> anyhow::Result<BranchFate> {let display_info = RemovalDisplayInfo::from_precomputed(ctx.deletion_mode,ctx.integration_reason,@@ -1764,7 +1840,7 @@ fn handle_named_removed_worktree_background(let planner_expected_retention =ctx.deletion_mode.should_keep() || ctx.integration_reason.is_none();- spawn_background_removal(+ let fate = spawn_background_removal(repo,ctx.main_path,&BackgroundRemoval {@@ -1777,19 +1853,19 @@ fn handle_named_removed_worktree_background(planner_expected_retention,},branch_name,- ctx.background_fallback_mode,+ ctx.background_fallback(),)?;spawn_hooks_after_remove(repo, ctx, branch_name, announcer)?;stderr().flush()?;- Ok(())+ Ok(fate)}-/// Handle output for RemovedWorktree removal+/// Execute and narrate a [`RemovalPlan::Worktree`] plan.fn handle_removed_worktree_output(- ctx: RemovedWorktreeOutputContext<'_>,+ ctx: WorktreeRemovalContext<'_>,announcer: &mut HookAnnouncer<'_>,-) -> anyhow::Result<()> {+) -> anyhow::Result<BranchFate> {// Use main_path for discovery - the worktree being removed might be cwd,// and git operations after removal need a valid working directory.let repo = worktrunk::git::Repository::at(ctx.main_path)?;@@ -1806,7 +1882,7 @@ fn handle_removed_worktree_output(// owns the terminal, so no messages, no spinner, no `cd` directive (the// picker manages its own cwd). The git removal runs inline — same as the// foreground path, minus the chrome.- if ctx.silent {+ if matches!(ctx.execution, RemovalExecution::Silent) {return remove_removed_worktree_silently(&repo, &ctx, announcer);}@@ -1817,15 +1893,15 @@ fn handle_removed_worktree_output(return handle_detached_removed_worktree_output(&repo, &ctx, announcer);};- if ctx.foreground {+ if matches!(ctx.execution, RemovalExecution::Foreground) {handle_named_removed_worktree_foreground(&repo, &ctx, branch_name, announcer)} else {handle_named_removed_worktree_background(&repo, &ctx, branch_name, announcer)}}-/// Remove a `RemovedWorktree` worktree with no terminal output — the TUI-/// (`wt switch` picker) path of [`handle_remove_output`].+/// Remove a [`RemovalPlan::Worktree`] target with no terminal output — the+/// TUI (`wt switch` picker) path of [`handle_remove_output`].////// `pre-remove` has already run (when it was approved — `verify`), and the/// caller skipped the `cd` directive (the picker manages its own process cwd).@@ -1837,9 +1913,9 @@ fn handle_removed_worktree_output(/// entries" error against.fn remove_removed_worktree_silently(repo: &Repository,- ctx: &RemovedWorktreeOutputContext<'_>,+ ctx: &WorktreeRemovalContext<'_>,announcer: &mut HookAnnouncer<'_>,-) -> anyhow::Result<()> {+) -> anyhow::Result<BranchFate> {let snapshot = repo.capture_refs()?;let options = RemoveOptions {branch: ctx.branch_name.map(String::from),@@ -1854,9 +1930,15 @@ fn remove_removed_worktree_silently(let _ = std::fs::remove_dir_all(&staged);}+ // A best-effort deletion's failure is deliberately not narrated here+ // (no terminal to narrate to); the fate still reports the branch as+ // surviving.+ let fate = BranchFate::from_result(output.branch_result.as_ref());+// Post-remove (and post-switch when the picker cd'd away) hooks — registered// onto the caller's announcer, which `flush`es after this returns.- spawn_hooks_after_remove(repo, ctx, ctx.branch_name.unwrap_or("HEAD"), announcer)+ spawn_hooks_after_remove(repo, ctx, ctx.branch_name.unwrap_or("HEAD"), announcer)?;+ Ok(fate)}/// Run a shell command with streaming output, signal forwarding, and ANSI reset.diff --git a/src/output/mod.rs b/src/output/mod.rsindex 6423c5b69..dacff348b 100644--- a/src/output/mod.rs+++ b/src/output/mod.rs@@ -47,8 +47,9 @@ pub(crate) use global::{};// Re-export output handlerspub(crate) use handlers::{- BackgroundFallbackMode, DirectivePassthrough, execute_shell_command, execute_user_command,- handle_remove_output, handle_switch_output, retained_unmerged_branch_messages,+ BackgroundFallbackMode, DirectivePassthrough, RemovalExecution, execute_shell_command,+ execute_user_command, handle_remove_output, handle_switch_output,+ retained_unmerged_branch_messages,};// Re-export shell integration functionspub(crate) use shell_integration::{diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rsindex a043f62d7..b82583fa9 100644--- a/tests/integration_tests/remove.rs+++ b/tests/integration_tests/remove.rs@@ -1663,7 +1663,7 @@ fn test_remove_squash_merged_on_remote_then_advanced(#[from(repo_with_remote)] r}/// Like `test_remove_squash_merged_on_remote`, but with a **worktree** (not just-/// a branch). Tests that the `RemovedWorktree` path displays the effective target+/// a branch). Tests that the worktree-removal path displays the effective target/// (`origin/main`) rather than the local default branch when upstream is ahead.#[rstest]fn test_remove_worktree_squash_merged_on_remote(#[from(repo_with_remote)] mut repo: TestRepo) {@@ -3849,6 +3849,131 @@ fn test_remove_json_multi_with_current(mut repo: TestRepo) {assert_eq!(items[1]["kind"], "worktree");}+/// `branch_deleted` reports what execution did, not what the plan intended.+///+/// The planner sees `feature` at main's tip and intends to delete it. A+/// `pre-remove` hook then commits on the branch, so the SafeDelete's re-check+/// against fresh refs finds it unmerged and declines — the worktree goes, the+/// branch stays. Reporting the plan here would tell a script the branch was+/// deleted while it is still on disk.+#[rstest]+fn test_remove_json_branch_deleted_reflects_execution(mut repo: TestRepo) {+ use crate::common::wait_for_worktree_removed;++ repo.commit("initial");+ // Same commit as main — integrated, so the plan intends to delete it.+ let feature_wt = repo.add_worktree("feature");++ // Runs in the worktree being removed, after planning, and leaves the+ // worktree clean so the removal itself still succeeds. Resolved from the+ // invoking worktree's config (the repo root), so it needn't be committed.+ repo.write_project_config(+ r#"pre-remove = "printf raced > raced.txt && git add raced.txt && git commit -m raced""#,+ );++ let output = repo+ .wt_command()+ .args(["remove", "feature", "--format=json", "--yes"])+ .output()+ .unwrap();+ let stderr = String::from_utf8_lossy(&output.stderr)+ .ansi_strip()+ .into_owned();+ assert!(output.status.success(), "remove should succeed:\n{stderr}");++ let json: serde_json::Value =+ serde_json::from_str(&String::from_utf8_lossy(&output.stdout)).unwrap();+ let items = json.as_array().unwrap();+ assert_eq!(items.len(), 1);+ assert_eq!(items[0]["branch"], "feature");+ assert_eq!(+ items[0]["branch_deleted"], false,+ "branch_deleted must report the declined deletion, not the plan's intent:\n{stderr}",+ );++ wait_for_worktree_removed(&feature_wt);+ repo.run_git(&["rev-parse", "--verify", "refs/heads/feature"]);+ let tip = repo.git_output(&["show", "--format=", "--name-only", "refs/heads/feature"]);+ assert!(+ tip.lines().any(|line| line == "raced.txt"),+ "the hook's commit must be the branch tip, or the divergence never happened:\n{tip}",+ );++ assert!(+ stderr.contains("Removed worktree but kept branch feature (not integrated)"),+ "the surviving branch must be surfaced, not left silent:\n{stderr}",+ );+}++/// The detached legacy fallback also corrects a broken deletion promise.+///+/// When the rename-into-trash fast path fails, the removal falls back to a+/// detached `git worktree remove`, and the branch deletion becomes a CAS+/// shell tail — built in the foreground. A `pre-remove` hook that advances+/// the branch makes the integration re-check decline the tail, so the branch+/// definitively survives while the progress message already promised+/// "worktree & branch". That survival must be warned and reported, exactly as+/// on the fast path.+///+/// The fast path is forced to fail portably by planting a *file* where the+/// trash directory belongs: `stage_worktree_removal`'s `create_dir_all` fails+/// (ignored) and the rename into a non-directory fails on every OS.+#[rstest]+fn test_remove_fallback_warns_when_no_cas_tail(mut repo: TestRepo) {+ repo.commit("initial");+ let feature_wt = repo.add_worktree("feature");++ // Occupy the trash path with a file so the rename-into-trash fast path+ // cannot stage, forcing the detached-fallback arm.+ let wt_dir = repo.root_path().join(".git").join("wt");+ std::fs::create_dir_all(&wt_dir).unwrap();+ std::fs::write(wt_dir.join("trash"), b"not a directory").unwrap();++ // Same divergence as the fast-path test above: planner sees `feature`+ // integrated, the hook then commits on it, the re-check declines.+ repo.write_project_config(+ r#"pre-remove = "printf raced > raced.txt && git add raced.txt && git commit -m raced""#,+ );++ let output = repo+ .wt_command()+ .args(["remove", "feature", "--format=json", "--yes"])+ .output()+ .unwrap();+ let stderr = String::from_utf8_lossy(&output.stderr)+ .ansi_strip()+ .into_owned();+ assert!(output.status.success(), "remove should succeed:\n{stderr}");++ assert!(+ stderr.contains("Removed worktree but kept branch feature (not integrated)"),+ "the fallback must correct the deletion promise, not stay silent:\n{stderr}",+ );+ // Discriminates fallback from fast path (which prints the same warning):+ // staging would have replaced the planted file with a real trash+ // directory, so the file surviving proves the rename never staged.+ assert!(+ wt_dir.join("trash").is_file(),+ "the planted trash file should have kept the fast path from staging",+ );+ let json: serde_json::Value =+ serde_json::from_str(&String::from_utf8_lossy(&output.stdout)).unwrap();+ assert_eq!(+ json.as_array().unwrap()[0]["branch_deleted"],+ false,+ "a survival known in the foreground is not a deferral:\n{stderr}",+ );+ // The branch survives with the hook's commit as its tip; the worktree+ // directory itself is the detached process's job, so it isn't asserted.+ repo.run_git(&["rev-parse", "--verify", "refs/heads/feature"]);+ let tip = repo.git_output(&["show", "--format=", "--name-only", "refs/heads/feature"]);+ assert!(+ tip.lines().any(|line| line == "raced.txt"),+ "the hook's commit must be the branch tip, or the divergence never happened:\n{tip}",+ );+ let _ = feature_wt;+}+/// Regression: integration check ORs over local AND upstream. A branch merged/// into LOCAL `main` must still be detected as integrated when `main` and/// `origin/main` have diverged — symmetric todiff --git a/tests/integration_tests/step_prune.rs b/tests/integration_tests/step_prune.rsindex 6fcd6f605..85f7788d1 100644--- a/tests/integration_tests/step_prune.rs+++ b/tests/integration_tests/step_prune.rs@@ -1338,6 +1338,97 @@ fn test_prune_runs_pre_remove_hook(mut repo: TestRepo) {assert!(!wt_path.exists(), "the merged worktree should be removed");}+/// A declined orphan deletion removed nothing, so nothing is counted.+///+/// The scan selects both `carrier` (worktree, integrated) and `orphan`+/// (branch-only, integrated). `carrier`'s `pre-remove` hook then points+/// `orphan` at a commit main doesn't contain, so when the worker reaches+/// `orphan`, the SafeDelete re-check declines — and a candidate that removed+/// nothing must not appear in the summary as either "1 branch" (the plan's+/// intent) or "1 worktree" (the fate-counting of a stale entry it never had).+///+/// `RAYON_NUM_THREADS=1` makes the ordering causal, not raced: the serial+/// scan queues `carrier` (worktree entries precede orphans in `check_items`)+/// before `orphan`, and the single FIFO worker runs `carrier`'s removal — the+/// hook — before `orphan`'s deletion.+#[rstest]+fn test_prune_excludes_declined_orphan_deletion_from_summary(mut repo: TestRepo) {+ let carrier_wt = repo.add_worktree("carrier");+ repo.run_git(&["branch", "orphan"]);+ // Advance the default branch so both are ancestors — integrated at scan.+ repo.commit("Advance default branch");+ // Runs in `carrier`: commit a file, hand that commit to `orphan`, then+ // step `carrier` back to its integrated tip with a clean tree.+ repo.write_project_config(+ r#"pre-remove = "printf raced > raced.txt && git add raced.txt && git commit -m raced && git update-ref refs/heads/orphan HEAD && git reset --hard HEAD~1""#,+ );++ let mut cmd = repo.wt_command();+ cmd.args(["step", "prune", "--foreground", "--yes", "--min-age=0s"])+ .env("RAYON_NUM_THREADS", "1");+ let output = cmd.output().unwrap();+ let stderr = String::from_utf8_lossy(&output.stderr)+ .ansi_strip()+ .into_owned();+ assert!(output.status.success(), "prune should succeed:\n{stderr}");++ // The exact line, so a counted orphan fails whichever way it's counted:+ // as its plan's intent ("…, 1 branch") or as a phantom worktree+ // ("…, 1 worktree").+ assert!(+ stderr.contains("Pruned 1 worktree & branch\n"),+ "the summary must count only carrier; the no-op orphan contributes nothing:\n{stderr}",+ );+ assert!(!carrier_wt.exists(), "carrier should be removed");+ repo.run_git(&["rev-parse", "--verify", "refs/heads/orphan"]);+ let tip = repo.git_output(&["show", "--format=", "--name-only", "refs/heads/orphan"]);+ assert!(+ tip.lines().any(|line| line == "raced.txt"),+ "the hook's commit must be orphan's tip, or the divergence never happened:\n{tip}",+ );+}++/// The summary counts the executed outcome, not the scan-time plan.+///+/// The scan selects `merged` as integrated and plans to take its branch with+/// it. Its `pre-remove` hook then commits, so the SafeDelete re-check against+/// fresh refs declines and only the worktree goes. Counting the plan would+/// announce a branch the run left standing.+#[rstest]+fn test_prune_summary_counts_declined_deletion_as_worktree_only(mut repo: TestRepo) {+ let wt_path = repo.add_worktree("merged");+ // Advance the default branch so `merged` is an ancestor — prune's scan+ // treats it as integrated and plans to delete the branch too.+ repo.commit("Advance default branch");+ // Runs in the worktree being removed and leaves it clean, so the removal+ // still succeeds while the branch it was going to delete has moved on.+ repo.write_project_config(+ r#"pre-remove = "printf raced > raced.txt && git add raced.txt && git commit -m raced""#,+ );++ let output = repo+ .wt_command()+ .args(["step", "prune", "--foreground", "--yes", "--min-age=0s"])+ .output()+ .unwrap();+ let stderr = String::from_utf8_lossy(&output.stderr)+ .ansi_strip()+ .into_owned();+ assert!(output.status.success(), "prune should succeed:\n{stderr}");++ assert!(+ stderr.contains("Pruned 1 worktree") && !stderr.contains("worktree & branch"),+ "summary must count the worktree alone, not the branch prune kept:\n{stderr}",+ );+ assert!(!wt_path.exists(), "the merged worktree should be removed");+ repo.run_git(&["rev-parse", "--verify", "refs/heads/merged"]);+ let tip = repo.git_output(&["show", "--format=", "--name-only", "refs/heads/merged"]);+ assert!(+ tip.lines().any(|line| line == "raced.txt"),+ "the hook's commit must be the branch tip, or the divergence never happened:\n{tip}",+ );+}+/// Canary for `wt step prune` removals overlapping `.git/config` readers,/// and regression test for synchronous fallback completion.///