Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
refactor(step): split step_commands.rs into per-operation modules (#2601)
Maximilian Roosc23f678848c4
diff --git a/src/commands/merge.rs b/src/commands/merge.rsindex dae53c590..403e52e98 100644--- a/src/commands/merge.rs+++ b/src/commands/merge.rs@@ -231,14 +231,14 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {// --no-hooks vs declined-approval distinction.let squashed = if squash_enabled {matches!(- super::step_commands::handle_squash(+ super::step::handle_squash(Some(&target_branch),yes,commit_hooks,Some(stage_mode),&mut announcer,)?,- super::step_commands::SquashResult::Squashed { .. }+ super::step::SquashResult::Squashed { .. })} else {false@@ -248,8 +248,8 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {let rebased = if rebase {// Auto-rebase onto targetmatches!(- super::step_commands::handle_rebase(Some(&target_branch))?,- super::step_commands::RebaseResult::Rebased { .. }+ super::step::handle_rebase(Some(&target_branch))?,+ super::step::RebaseResult::Rebased { .. })} else {// --no-rebase: verify already rebased, fail if notdiff --git a/src/commands/mod.rs b/src/commands/mod.rsindex 08ffc5875..b92a1615c 100644--- a/src/commands/mod.rs+++ b/src/commands/mod.rs@@ -25,7 +25,7 @@ mod relocate;pub(crate) mod repository_ext;mod run_pipeline;pub(crate) mod statusline;-pub(crate) mod step_commands;+pub(crate) mod step;pub(crate) mod template_vars;pub(crate) mod worktree;@@ -56,7 +56,7 @@ pub(crate) use merge::{MergeFlagOverrides, MergeOptions, handle_merge};pub(crate) use picker::handle_picker;pub(crate) use repository_ext::RemoveTarget;pub(crate) use run_pipeline::run_pipeline;-pub(crate) use step_commands::{+pub(crate) use step::{PromoteResult, RebaseResult, SquashResult, handle_promote, handle_rebase, handle_squash,step_commit, step_copy_ignored, step_diff, step_dry_run_squash, step_prune, step_relocate,step_show_squash_prompt,diff --git a/src/commands/step/commit.rs b/src/commands/step/commit.rsnew file mode 100644index 000000000..380d52170--- /dev/null+++ b/src/commands/step/commit.rs@@ -0,0 +1,135 @@+//! `wt step commit` — commit working tree changes.++use std::fs;++use anyhow::Context;+use worktrunk::HookType;+use worktrunk::config::UserConfig;+use worktrunk::git::Repository;+use worktrunk::shell_exec::Cmd;+use worktrunk::styling::println;++use super::super::command_approval::approve_or_skip;+use super::super::commit::{CommitOptions, CommitOutcome, HookGate, StageMode};+use super::super::context::CommandEnv;+use super::super::hooks::HookAnnouncer;+use super::shared::print_dry_run;++/// Handle `wt step commit` command+///+/// `stage` is the CLI-provided stage mode. If None, uses the effective config default.+pub fn step_commit(+ branch: Option<String>,+ yes: bool,+ verify: bool,+ stage: Option<StageMode>,+ show_prompt: bool,+ dry_run: bool,+) -> anyhow::Result<Option<CommitOutcome>> {+ // --show-prompt and --dry-run skip hooks and the commit itself; --dry-run still+ // mirrors --stage against a temp index so the previewed prompt matches what a real+ // run would send the LLM. Neither path produces a CommitOutcome.+ if show_prompt || dry_run {+ preview_commit(stage, dry_run)?;+ return Ok(None);+ }++ // Load config once, run LLM setup prompt, then reuse config+ let mut config = UserConfig::load().context("Failed to load config")?;+ // One-time LLM setup prompt (errors logged internally; don't block commit)+ let _ = crate::output::prompt_commit_generation(&mut config);++ let env = match branch {+ Some(ref b) => CommandEnv::for_branch(config, b)?,+ None => CommandEnv::for_action(config)?,+ };+ let ctx = env.context(yes);++ // CLI flag overrides config value+ let stage_mode = stage.unwrap_or(env.resolved().commit.stage());++ // "Approve at the Gate": prompt for approval upfront (when hooks are enabled) so+ // hook execution downstream is fully gated.+ let approved = verify+ && approve_or_skip(+ &ctx,+ &[HookType::PreCommit, HookType::PostCommit],+ "Commands declined, committing without hooks",+ )?;+ let hooks = HookGate::from_approval(verify, approved);++ let mut options = CommitOptions::new(&ctx);+ options.hooks = hooks;+ options.stage_mode = stage_mode;+ options.show_no_squash_note = false;+ // Only warn about untracked if we're staging all+ options.warn_about_untracked = stage_mode == StageMode::All;++ let mut announcer = HookAnnouncer::new(ctx.repo, ctx.config, false);+ let outcome = options.commit(&mut announcer)?;+ announcer.flush()?;+ Ok(Some(outcome))+}++/// Handle `wt step commit` in `--show-prompt` or `--dry-run` mode.+///+/// Both modes skip hooks and the commit itself. `--show-prompt` outputs only the+/// rendered prompt against the existing index (cheap, pipeable). `--dry-run` mirrors+/// `--stage` against a temp index — so the previewed prompt matches what a real run+/// would send — then calls the LLM and prints the command and message in three labeled+/// sections. The user's real index is never modified.+fn preview_commit(stage: Option<StageMode>, dry_run: bool) -> anyhow::Result<()> {+ let env = CommandEnv::for_action(UserConfig::load().context("Failed to load config")?)?;+ let commit_config = env.resolved().commit_generation.clone();++ // For --dry-run, stage to a copy of the index so the preview reflects what a real+ // run would send. --show-prompt skips this — it's the cheap "what's already staged"+ // path. StageMode::None has nothing to stage, so we use the existing index as-is.+ let temp_index = if dry_run {+ let add_args: Option<&[&str]> = match stage.unwrap_or(env.resolved().commit.stage()) {+ StageMode::All => Some(&["add", "-A"]),+ StageMode::Tracked => Some(&["add", "-u"]),+ StageMode::None => None,+ };+ add_args+ .map(|args| stage_to_temp_index(&env.repo, args))+ .transpose()?+ } else {+ None+ };+ let index_override = temp_index.as_ref().map(|t| t.path());++ let prompt = crate::llm::build_commit_prompt(&commit_config, index_override)?;+ if !dry_run {+ println!("{}", prompt);+ return Ok(());+ }+ let message = crate::llm::generate_commit_message(&commit_config, index_override)?;+ print_dry_run(&prompt, &commit_config, &message)+}++/// Copy the current worktree's index to a temp file and run `git <add_args>` against it.+///+/// Returns the [`tempfile::NamedTempFile`] so the caller controls its lifetime — when+/// dropped, the temp file is removed without ever touching the user's real index.+fn stage_to_temp_index(+ repo: &Repository,+ add_args: &[&str],+) -> anyhow::Result<tempfile::NamedTempFile> {+ let wt = repo.current_worktree();+ let real_index = wt.git_dir()?.join("index");+ let temp = tempfile::NamedTempFile::new().context("Failed to create temporary index")?;+ fs::copy(&real_index, temp.path()).context("Failed to copy index file")?;++ let output = Cmd::new("git")+ .args(add_args.iter().copied())+ .current_dir(wt.root()?)+ .env("GIT_INDEX_FILE", temp.path())+ .run()+ .context("Failed to stage changes into temp index")?;+ if !output.status.success() {+ let stderr = String::from_utf8_lossy(&output.stderr);+ anyhow::bail!("git {} failed: {}", add_args.join(" "), stderr.trim());+ }+ Ok(temp)+}diff --git a/src/commands/step/copy_ignored.rs b/src/commands/step/copy_ignored.rsnew file mode 100644index 000000000..4e6e91abf--- /dev/null+++ b/src/commands/step/copy_ignored.rs@@ -0,0 +1,281 @@+//! `wt step copy-ignored` — copy gitignored files matching `.worktreeinclude`.++use std::fs;+use std::path::PathBuf;++use anyhow::Context;+use worktrunk::copy::{copy_dir_recursive, copy_leaf};+use worktrunk::git::Repository;+use worktrunk::path::format_path_for_display;+use worktrunk::progress::{Progress, format_bytes};+use worktrunk::styling::{+ eprintln, format_with_gutter, info_message, println, success_message, verbosity,+};++use super::shared::{list_and_filter_ignored_entries, resolve_copy_ignored_config};++/// Handle `wt step copy-ignored` command+///+/// Copies gitignored files from a source worktree to a destination worktree.+/// If a `.worktreeinclude` file exists, only files matching both `.worktreeinclude`+/// and gitignore patterns are copied. Without `.worktreeinclude`, all gitignored+/// files are copied. Uses COW (reflink) when available for efficient copying of+/// large directories like `target/`.+pub fn step_copy_ignored(+ from: Option<&str>,+ to: Option<&str>,+ dry_run: bool,+ force: bool,+ format: crate::cli::SwitchFormat,+) -> anyhow::Result<()> {+ // Self-lower only when we're running inside a background hook pipeline+ // (parent `wt` sets `WORKTRUNK_FOREGROUND=-1` on the detached runner).+ // Foreground callers — interactive `wt step copy-ignored` and synchronous+ // `pre-*` hook pipelines — are the UI the user is waiting on and must not+ // be I/O-throttled by `taskpolicy -b` on macOS.+ if worktrunk::priority::in_background_hook() {+ worktrunk::priority::lower_current_process();+ }+ let json_mode = format == crate::cli::SwitchFormat::Json;+ let repo = Repository::current()?;+ let copy_ignored_config = resolve_copy_ignored_config(&repo)?;++ // Resolve source and destination worktree paths+ let (source_path, source_context) = match from {+ Some(branch) => {+ let path = repo.worktree_for_branch(branch)?.ok_or_else(|| {+ worktrunk::git::GitError::WorktreeNotFound {+ branch: branch.to_string(),+ }+ })?;+ (path, branch.to_string())+ }+ None => {+ // Default source is the primary worktree (main worktree for normal repos,+ // default branch worktree for bare repos).+ let path = repo.primary_worktree()?.ok_or_else(|| {+ anyhow::anyhow!(+ "No primary worktree found (bare repo with no default branch worktree)"+ )+ })?;+ let context = path+ .file_name()+ .map(|n| n.to_string_lossy().into_owned())+ .unwrap_or_default();+ (path, context)+ }+ };++ let dest_path = match to {+ Some(branch) => repo.worktree_for_branch(branch)?.ok_or_else(|| {+ worktrunk::git::GitError::WorktreeNotFound {+ branch: branch.to_string(),+ }+ })?,+ None => repo.current_worktree().root()?,+ };++ if source_path == dest_path {+ if json_mode {+ let payload = serde_json::json!({+ "outcome": "same_worktree",+ "from": source_path,+ "to": dest_path,+ "entries": Vec::<serde_json::Value>::new(),+ "files": 0,+ "bytes": 0,+ });+ println!("{}", serde_json::to_string_pretty(&payload)?);+ } else {+ eprintln!(+ "{}",+ info_message("Source and destination are the same worktree")+ );+ }+ return Ok(());+ }++ let worktree_paths: Vec<PathBuf> = repo+ .list_worktrees()?+ .iter()+ .map(|wt| wt.path.clone())+ .collect();+ let entries_to_copy = list_and_filter_ignored_entries(+ &source_path,+ &source_context,+ &worktree_paths,+ ©_ignored_config.exclude,+ )?;++ if entries_to_copy.is_empty() {+ if json_mode {+ let payload = serde_json::json!({+ "outcome": if dry_run { "planned" } else { "copied" },+ "dry_run": dry_run,+ "from": source_path,+ "to": dest_path,+ "entries": Vec::<serde_json::Value>::new(),+ "files": 0,+ "bytes": 0,+ });+ println!("{}", serde_json::to_string_pretty(&payload)?);+ } else {+ eprintln!("{}", info_message("No matching files to copy"));+ }+ return Ok(());+ }++ let verbose = verbosity();++ if dry_run {+ if json_mode {+ let entries: Vec<_> = entries_to_copy+ .iter()+ .map(|(src_entry, is_dir)| {+ let relative = src_entry+ .strip_prefix(&source_path)+ .unwrap_or(src_entry.as_path());+ serde_json::json!({+ "path": relative,+ "kind": if *is_dir { "dir" } else { "file" },+ })+ })+ .collect();+ let payload = serde_json::json!({+ "outcome": "planned",+ "dry_run": true,+ "from": source_path,+ "to": dest_path,+ "entries": entries,+ });+ println!("{}", serde_json::to_string_pretty(&payload)?);+ return Ok(());+ }+ let items: Vec<String> = entries_to_copy+ .iter()+ .map(|(src_entry, is_dir)| {+ let relative = src_entry+ .strip_prefix(&source_path)+ .unwrap_or(src_entry.as_path());+ let entry_type = if *is_dir { "dir" } else { "file" };+ format!("{} ({})", format_path_for_display(relative), entry_type)+ })+ .collect();+ let entry_word = if items.len() == 1 { "entry" } else { "entries" };+ eprintln!(+ "{}",+ info_message(format!(+ "Would copy {} {}:\n{}",+ items.len(),+ entry_word,+ format_with_gutter(&items.join("\n"), None)+ ))+ );+ return Ok(());+ }++ // Show entries in verbose mode (text only — JSON mode emits the full list at the end).+ if verbose >= 1 && !json_mode {+ let items: Vec<String> = entries_to_copy+ .iter()+ .map(|(src_entry, is_dir)| {+ let relative = src_entry+ .strip_prefix(&source_path)+ .unwrap_or(src_entry.as_path());+ let entry_type = if *is_dir { "dir" } else { "file" };+ format!("{} ({})", format_path_for_display(relative), entry_type)+ })+ .collect();+ let entry_word = if items.len() == 1 { "entry" } else { "entries" };+ eprintln!(+ "{}",+ info_message(format!(+ "Copying {} {}:\n{}",+ items.len(),+ entry_word,+ format_with_gutter(&items.join("\n"), None)+ ))+ );+ }++ // `start` auto-detects the TTY; verbose/dry-run already print enough.+ let progress = if verbose >= 1 || json_mode {+ Progress::disabled()+ } else {+ Progress::start("Copying")+ };++ let mut copied_count = 0usize;+ let mut copied_bytes = 0u64;+ for (src_entry, is_dir) in &entries_to_copy {+ let relative = src_entry+ .strip_prefix(&source_path)+ .expect("git ls-files path under worktree");+ let dest_entry = dest_path.join(relative);++ if *is_dir {+ let (n, b) =+ copy_dir_recursive(src_entry, &dest_entry, Some(&dest_path), force, &progress)+ .with_context(|| {+ format!("copying directory {}", format_path_for_display(relative))+ })?;+ copied_count += n;+ copied_bytes += b;+ } else {+ if let Some(parent) = dest_entry.parent() {+ fs::create_dir_all(parent).with_context(|| {+ format!(+ "creating directory for {}",+ format_path_for_display(relative)+ )+ })?;+ }+ if let Some(bytes) = copy_leaf(src_entry, &dest_entry, Some(&dest_path), force)? {+ copied_count += 1;+ copied_bytes += bytes;+ progress.record(bytes);+ }+ }+ }+ progress.finish();++ if json_mode {+ // `entries` mirrors dry-run: the top-level units selected for copy+ // (files and dirs). `files` counts the actual leaves written+ // (recursive + skipping pre-existing files), `bytes` sums their size.+ let entries: Vec<_> = entries_to_copy+ .iter()+ .map(|(src_entry, is_dir)| {+ let relative = src_entry+ .strip_prefix(&source_path)+ .unwrap_or(src_entry.as_path());+ serde_json::json!({+ "path": relative,+ "kind": if *is_dir { "dir" } else { "file" },+ })+ })+ .collect();+ let payload = serde_json::json!({+ "outcome": "copied",+ "dry_run": false,+ "from": source_path,+ "to": dest_path,+ "entries": entries,+ "files": copied_count,+ "bytes": copied_bytes,+ });+ println!("{}", serde_json::to_string_pretty(&payload)?);+ } else {+ // Show summary+ let file_word = if copied_count == 1 { "file" } else { "files" };+ eprintln!(+ "{}",+ success_message(format!(+ "Copied {copied_count} {file_word} · {}",+ format_bytes(copied_bytes)+ ))+ );+ }++ Ok(())+}diff --git a/src/commands/step/diff.rs b/src/commands/step/diff.rsnew file mode 100644index 000000000..2057f8c76--- /dev/null+++ b/src/commands/step/diff.rs@@ -0,0 +1,61 @@+//! `wt step diff` — show all changes since branching from the target.++use anyhow::Context;+use worktrunk::git::Repository;+use worktrunk::shell_exec::Cmd;++/// Handle `wt step diff` command+///+/// Shows all changes since branching from the target: committed, staged, unstaged,+/// and untracked files in a single diff. Copies the real index to preserve git's stat+/// cache (avoiding re-reads of unchanged files), then registers untracked files with+/// `git add -N` so they appear in the diff.+pub fn step_diff(target: Option<&str>, extra_args: &[String]) -> anyhow::Result<()> {+ let repo = Repository::current()?;+ let wt = repo.current_worktree();++ // Get and validate target ref+ let integration_target = repo.require_target_ref(target)?;++ // Get merge base+ let merge_base = repo+ .merge_base("HEAD", &integration_target)?+ .context("No common ancestor with target branch")?;++ let current_branch = wt.branch()?.unwrap_or_else(|| "HEAD".to_string());++ // Copy the real index so git's stat cache is warm for tracked files, then+ // register untracked files with `git add -N .` so they appear in the diff.+ // This avoids re-reading and hashing every tracked file during `git diff`.+ let worktree_root = wt.root()?;++ let real_index = wt.git_dir()?.join("index");+ let temp_index = tempfile::NamedTempFile::new().context("Failed to create temporary index")?;+ let temp_index_path = temp_index+ .path()+ .to_str()+ .context("Temporary index path is not valid UTF-8")?;++ std::fs::copy(&real_index, temp_index.path()).context("Failed to copy index file")?;++ // Register untracked files as intent-to-add (tracked files already have entries)+ Cmd::new("git")+ .args(["add", "--intent-to-add", "."])+ .current_dir(&worktree_root)+ .context(¤t_branch)+ .env("GIT_INDEX_FILE", temp_index_path)+ .run()+ .context("Failed to register untracked files")?;++ // Stream diff to stdout — git handles pager and coloring+ let mut diff_args = vec!["diff".to_string(), merge_base];+ diff_args.extend_from_slice(extra_args);+ Cmd::new("git")+ .args(&diff_args)+ .current_dir(&worktree_root)+ .context(¤t_branch)+ .env("GIT_INDEX_FILE", temp_index_path)+ .stream()?;++ Ok(())+}diff --git a/src/commands/step/mod.rs b/src/commands/step/mod.rsnew file mode 100644index 000000000..0b6b4e926--- /dev/null+++ b/src/commands/step/mod.rs@@ -0,0 +1,35 @@+//! Step commands for the merge workflow and standalone worktree utilities.+//!+//! Merge steps:+//! - `commit::step_commit` - Commit working tree changes+//! - `squash::handle_squash` - Squash commits into one+//! - `squash::step_show_squash_prompt` - Show squash prompt without executing+//! - `rebase::handle_rebase` - Rebase onto target branch+//! - `diff::step_diff` - Show all changes since branching+//!+//! Standalone:+//! - `copy_ignored::step_copy_ignored` - Copy gitignored files matching .worktreeinclude+//! - `promote::handle_promote` - Swap a branch into the main worktree+//! - `prune::step_prune` - Remove worktrees merged into the default branch+//! - `relocate::step_relocate` - Move worktrees to expected paths++pub(crate) mod commit;+pub(crate) mod copy_ignored;+pub(crate) mod diff;+pub(crate) mod promote;+pub(crate) mod prune;+pub(crate) mod rebase;+pub(crate) mod relocate;+mod shared;+pub(crate) mod squash;++pub(crate) use commit::step_commit;+pub(crate) use copy_ignored::step_copy_ignored;+pub(crate) use diff::step_diff;+pub(crate) use promote::{PromoteResult, handle_promote};+pub(crate) use prune::step_prune;+pub(crate) use rebase::{RebaseResult, handle_rebase};+pub(crate) use relocate::step_relocate;+pub(crate) use squash::{+ SquashResult, handle_squash, step_dry_run_squash, step_show_squash_prompt,+};diff --git a/src/commands/step/promote.rs b/src/commands/step/promote.rsnew file mode 100644index 000000000..42271fb44--- /dev/null+++ b/src/commands/step/promote.rs@@ -0,0 +1,458 @@+//! `wt step promote` — swap a branch into the main worktree.++use std::fs;+use std::io::ErrorKind;+use std::path::{Path, PathBuf};++use anyhow::Context;+use color_print::cformat;+use path_slash::PathExt as _;+use worktrunk::copy::{copy_dir_recursive, copy_leaf};+use worktrunk::git::Repository;+use worktrunk::progress::Progress;+use worktrunk::styling::{eprintln, hint_message, info_message, success_message, warning_message};++use super::shared::list_and_filter_ignored_entries;++/// Move a file or directory, falling back to copy+delete on cross-device errors.+fn move_entry(src: &Path, dest: &Path, is_dir: bool) -> anyhow::Result<()> {+ // Ensure parent directory exists+ if let Some(parent) = dest.parent() {+ fs::create_dir_all(parent)+ .context(format!("creating parent directory for {}", dest.display()))?;+ }++ match fs::rename(src, dest) {+ Ok(()) => Ok(()),+ Err(e) if e.kind() == ErrorKind::CrossesDevices => copy_and_remove(src, dest, is_dir),+ Err(e) => Err(anyhow::Error::from(e).context(format!(+ "moving {} to {}",+ src.display(),+ dest.display()+ ))),+ }+}++/// Copy then delete — fallback when `rename` fails with EXDEV (cross-device).+fn copy_and_remove(src: &Path, dest: &Path, is_dir: bool) -> anyhow::Result<()> {+ if is_dir {+ copy_dir_recursive(src, dest, None, true, &Progress::disabled())?;+ fs::remove_dir_all(src).context(format!("removing source directory {}", src.display()))?;+ } else {+ copy_leaf(src, dest, None, true)?;++ fs::remove_file(src).context(format!("removing source file {}", src.display()))?;+ }+ Ok(())+}++const PROMOTE_STAGING_DIR: &str = "staging/promote";++/// Move gitignored files from both worktrees into a staging directory.+///+/// Called BEFORE the branch exchange because `git switch` silently overwrites+/// ignored files that collide with tracked files on the target branch.+///+/// Returns the staging directory path and the count of entries staged.+fn stage_ignored(+ repo: &Repository,+ path_a: &Path,+ entries_a: &[(PathBuf, bool)],+ path_b: &Path,+ entries_b: &[(PathBuf, bool)],+) -> anyhow::Result<(PathBuf, usize)> {+ let staging_dir = repo.wt_dir().join(PROMOTE_STAGING_DIR);+ fs::create_dir_all(&staging_dir).context("creating promote staging directory")?;++ let staging_a = staging_dir.join("a");+ let staging_b = staging_dir.join("b");+ let mut count = 0;++ // Move A's entries → staging/a+ for (src_entry, is_dir) in entries_a {+ let relative = src_entry+ .strip_prefix(path_a)+ .context("entry not under worktree A")?;+ let staging_entry = staging_a.join(relative);+ if fs::symlink_metadata(src_entry).is_ok() {+ move_entry(src_entry, &staging_entry, *is_dir)+ .context(format!("staging {}", relative.display()))?;+ count += 1;+ }+ }++ // Move B's entries → staging/b+ for (src_entry, is_dir) in entries_b {+ let relative = src_entry+ .strip_prefix(path_b)+ .context("entry not under worktree B")?;+ let staging_entry = staging_b.join(relative);+ if fs::symlink_metadata(src_entry).is_ok() {+ move_entry(src_entry, &staging_entry, *is_dir)+ .context(format!("staging {}", relative.display()))?;+ count += 1;+ }+ }++ // Clean up empty staging directory (can happen if all entries vanished+ // between listing and staging due to TOCTOU)+ if count == 0 && staging_dir.exists() {+ let _ = fs::remove_dir_all(&staging_dir);+ }++ Ok((staging_dir, count))+}++/// Distribute staged files to their new worktrees after a branch exchange.+///+/// B's original files (in staging/b) go to worktree A (which now has B's branch).+/// A's original files (in staging/a) go to worktree B (which now has A's branch).+fn distribute_staged(+ staging_dir: &Path,+ path_a: &Path,+ entries_a: &[(PathBuf, bool)],+ path_b: &Path,+ entries_b: &[(PathBuf, bool)],+) -> anyhow::Result<usize> {+ let staging_a = staging_dir.join("a");+ let staging_b = staging_dir.join("b");+ let mut count = 0;++ // Move B's staged entries → A (A now has B's branch)+ for (src_entry, is_dir) in entries_b {+ let relative = src_entry+ .strip_prefix(path_b)+ .context("entry not under worktree B")?;+ let staging_entry = staging_b.join(relative);+ let dest_entry = path_a.join(relative);+ if fs::symlink_metadata(&staging_entry).is_ok() {+ move_entry(&staging_entry, &dest_entry, *is_dir)+ .context(format!("distributing {}", relative.display()))?;+ count += 1;+ }+ }++ // Move A's staged entries → B (B now has A's branch)+ for (src_entry, is_dir) in entries_a {+ let relative = src_entry+ .strip_prefix(path_a)+ .context("entry not under worktree A")?;+ let staging_entry = staging_a.join(relative);+ let dest_entry = path_b.join(relative);+ if fs::symlink_metadata(&staging_entry).is_ok() {+ move_entry(&staging_entry, &dest_entry, *is_dir)+ .context(format!("distributing {}", relative.display()))?;+ count += 1;+ }+ }++ // Clean up staging directory (best-effort — files are already distributed)+ let _ = fs::remove_dir_all(staging_dir);++ Ok(count)+}++/// Result of a promote operation+pub enum PromoteResult {+ /// Branch was promoted successfully+ Promoted,+ /// Already in canonical state (requested branch is already in main)+ AlreadyInMain(String),+}++/// Exchange branches between two worktrees.+///+/// Steps: detach target → detach main → switch main → switch target.+/// Both worktrees must be clean (verified by caller). On failure, attempts+/// best-effort rollback — but failure here is near-impossible given the+/// preconditions (`ensure_clean` passed, branches exist, detach released locks).+fn exchange_branches(+ main_wt: &worktrunk::git::WorkingTree<'_>,+ main_branch: &str,+ target_wt: &worktrunk::git::WorkingTree<'_>,+ target_branch: &str,+) -> anyhow::Result<()> {+ let steps: &[(&worktrunk::git::WorkingTree<'_>, &[&str], &str)] = &[+ (target_wt, &["switch", "--detach"], "detach target"),+ (main_wt, &["switch", "--detach"], "detach main"),+ (main_wt, &["switch", target_branch], "switch main"),+ (target_wt, &["switch", main_branch], "switch target"),+ ];++ for (wt, args, label) in steps {+ if let Err(e) = wt.run_command(args) {+ // Best-effort rollback: try to re-attach both branches.+ let _ = main_wt.run_command(&["switch", main_branch]);+ let _ = target_wt.run_command(&["switch", target_branch]);+ return Err(e.context(format!("branch exchange failed at: {label}")));+ }+ }++ Ok(())+}++/// Handle `wt step promote` command+///+/// Promotes a branch to the main worktree, exchanging it with whatever branch is currently there.+///+/// ## Interruption recovery+///+/// The swap uses a staging directory at `.git/wt/staging/promote/` and proceeds+/// in three phases:+///+/// 1. **Stage**: move ignored files from both worktrees into staging (`a/`, `b/`)+/// 2. **Exchange**: detach + `git switch` to swap branches+/// 3. **Distribute**: move staged files to their new worktrees, then delete staging+///+/// A hard kill at any phase leaves files in staging, never deleted. The next run+/// detects the leftover directory and bails with a recovery path. A kill during+/// `git switch` may leave a worktree detached (fix: `git switch <branch>`).+pub fn handle_promote(branch: Option<&str>) -> anyhow::Result<PromoteResult> {+ use worktrunk::git::GitError;++ let repo = Repository::current()?;+ let worktrees = repo.list_worktrees()?;++ if worktrees.is_empty() {+ anyhow::bail!("No worktrees found");+ }++ // For normal repos, worktrees[0] is the main worktree+ // For bare repos, there's no main worktree - we don't support promote there+ if repo.is_bare()? {+ anyhow::bail!("wt step promote is not supported in bare repositories");+ }++ let main_wt = &worktrees[0];+ let main_path = &main_wt.path;+ let main_branch = main_wt+ .branch+ .clone()+ .ok_or_else(|| GitError::DetachedHead {+ action: Some("promote".into()),+ })?;++ // Resolve the branch to promote (default_branch computed lazily, only when needed)+ let target_branch = match branch {+ Some(b) => b.to_string(),+ None => {+ let current_wt = repo.current_worktree();+ if !current_wt.is_linked()? {+ // From main worktree with no args: restore default branch+ repo.default_branch()+ .ok_or_else(|| anyhow::anyhow!("Could not determine default branch"))?+ } else {+ // From other worktree with no args: promote current branch+ current_wt.branch()?.ok_or_else(|| GitError::DetachedHead {+ action: Some("promote".into()),+ })?+ }+ }+ };++ // Check if target is already in main worktree+ if target_branch == main_branch {+ return Ok(PromoteResult::AlreadyInMain(target_branch));+ }++ // Find the worktree with the target branch+ let target_wt = worktrees+ .iter()+ .skip(1) // Skip main worktree+ .find(|wt| wt.branch.as_deref() == Some(&target_branch))+ .ok_or_else(|| GitError::WorktreeNotFound {+ branch: target_branch.clone(),+ })?;++ let target_path = &target_wt.path;++ // Bail early if a leftover staging dir exists from a previous interrupted promote —+ // it may contain the user's only copy of files from the failed swap.+ // Check BEFORE ensure_clean so users see the recovery path first.+ let staging_path = repo.wt_dir().join(PROMOTE_STAGING_DIR);+ if staging_path.exists() {+ let display = staging_path.to_slash_lossy();+ return Err(anyhow::anyhow!(+ "Files may need manual recovery from: {display}\n\+ Remove it to retry: rm -rf \"{display}\""+ )+ .context("Found leftover staging directory from an interrupted promote"));+ }++ // Ensure both worktrees are clean+ let main_working_tree = repo.worktree_at(main_path);+ let target_working_tree = repo.worktree_at(target_path);++ main_working_tree.ensure_clean("promote", Some(&main_branch), false)?;+ target_working_tree.ensure_clean("promote", Some(&target_branch), false)?;++ // Check if we're restoring canonical state (promoting default branch back to main worktree)+ // Only lookup default_branch if needed for messaging (already resolved if no-arg from main)+ let default_branch = repo.default_branch();+ let is_restoring = default_branch.as_ref() == Some(&target_branch);++ if is_restoring {+ // Restoring default branch to main worktree - no warning needed+ eprintln!("{}", info_message("Restoring main worktree"));+ } else {+ // Creating mismatch - show warning and how to restore+ eprintln!(+ "{}",+ warning_message("Promoting creates mismatched worktree state (shown as ⚑ in wt list)",)+ );+ // Only show restore hint if we know the default branch+ if let Some(default) = &default_branch {+ eprintln!(+ "{}",+ hint_message(cformat!(+ "Run <underline>wt step promote {default}</> to restore canonical locations"+ ))+ );+ }+ }++ // Discover gitignored entries BEFORE branch exchange — .gitignore rules belong+ // to the current branch and will change after `git switch`.+ let worktree_paths: Vec<PathBuf> = worktrees.iter().map(|wt| wt.path.clone()).collect();+ let no_excludes: &[String] = &[];+ let main_entries =+ list_and_filter_ignored_entries(main_path, &main_branch, &worktree_paths, no_excludes)?;+ let target_entries =+ list_and_filter_ignored_entries(target_path, &target_branch, &worktree_paths, no_excludes)?;++ // Move gitignored files to staging BEFORE branch exchange.+ // `git switch` silently overwrites ignored files that collide with tracked+ // files on the target branch — staging them first prevents data loss.+ let staged = if !main_entries.is_empty() || !target_entries.is_empty() {+ let (dir, count) = stage_ignored(+ &repo,+ main_path,+ &main_entries,+ target_path,+ &target_entries,+ )+ .context(format!(+ "Failed to stage ignored files. Already-staged files may be recoverable from: {}",+ staging_path.to_slash_lossy()+ ))?;+ if count > 0 { Some((dir, count)) } else { None }+ } else {+ None+ };++ // Exchange branches (detach both, then switch to swapped branches).+ // Failure is near-impossible (both worktrees verified clean, branches exist).+ // If it somehow fails, stale staging detection recovers on next run.+ exchange_branches(+ &main_working_tree,+ &main_branch,+ &target_working_tree,+ &target_branch,+ )?;++ // Distribute staged files to their new worktrees (after branch exchange)+ let swapped = if let Some((ref staging_dir, _)) = staged {+ distribute_staged(+ staging_dir,+ main_path,+ &main_entries,+ target_path,+ &target_entries,+ )+ .context(format!(+ "Failed to distribute staged files. Staged files may be recoverable from: {}",+ staging_dir.display()+ ))?+ } else {+ 0+ };++ // Print success messages only after everything succeeded+ eprintln!(+ "{}",+ success_message(cformat!(+ "Promoted: main worktree now has <bold>{target_branch}</>; {} now has <bold>{main_branch}</>",+ worktrunk::path::format_path_for_display(target_path)+ ))+ );+ if swapped > 0 {+ let path_word = if swapped == 1 { "path" } else { "paths" };+ eprintln!(+ "{}",+ success_message(format!("Swapped {swapped} gitignored {path_word}"))+ );+ }++ Ok(PromoteResult::Promoted)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_move_entry_file() {+ let tmp = tempfile::tempdir().unwrap();+ let src = tmp.path().join("source.txt");+ let dest = tmp.path().join("subdir/dest.txt");++ fs::write(&src, "content").unwrap();+ move_entry(&src, &dest, false).unwrap();++ assert!(!src.exists());+ assert_eq!(fs::read_to_string(&dest).unwrap(), "content");+ }++ #[test]+ fn test_move_entry_directory() {+ let tmp = tempfile::tempdir().unwrap();+ let src = tmp.path().join("srcdir");+ let dest = tmp.path().join("nested/destdir");++ fs::create_dir_all(src.join("inner")).unwrap();+ fs::write(src.join("inner/file.txt"), "nested").unwrap();+ fs::write(src.join("root.txt"), "root").unwrap();++ move_entry(&src, &dest, true).unwrap();++ assert!(!src.exists());+ assert_eq!(+ fs::read_to_string(dest.join("inner/file.txt")).unwrap(),+ "nested"+ );+ assert_eq!(fs::read_to_string(dest.join("root.txt")).unwrap(), "root");+ }++ #[test]+ fn test_copy_and_remove_file() {+ let tmp = tempfile::tempdir().unwrap();+ let src = tmp.path().join("source.txt");+ let dest = tmp.path().join("dest.txt");++ fs::write(&src, "content").unwrap();+ copy_and_remove(&src, &dest, false).unwrap();++ assert!(!src.exists());+ assert_eq!(fs::read_to_string(&dest).unwrap(), "content");+ }++ #[test]+ fn test_copy_and_remove_directory() {+ let tmp = tempfile::tempdir().unwrap();+ let src = tmp.path().join("srcdir");+ let dest = tmp.path().join("destdir");++ fs::create_dir_all(src.join("sub")).unwrap();+ fs::write(src.join("sub/file.txt"), "nested").unwrap();+ fs::write(src.join("root.txt"), "root").unwrap();++ copy_and_remove(&src, &dest, true).unwrap();++ assert!(!src.exists());+ assert_eq!(+ fs::read_to_string(dest.join("sub/file.txt")).unwrap(),+ "nested"+ );+ assert_eq!(fs::read_to_string(dest.join("root.txt")).unwrap(), "root");+ }+}diff --git a/src/commands/step/prune.rs b/src/commands/step/prune.rsnew file mode 100644index 000000000..06b76aa80--- /dev/null+++ b/src/commands/step/prune.rs@@ -0,0 +1,581 @@+//! `wt step prune` — remove worktrees and branches integrated into the default branch.++use std::fs;+use std::path::PathBuf;+use std::time::Duration;++use anyhow::Context;+use color_print::cformat;+use crossbeam_channel as chan;+use rayon::prelude::*;+use worktrunk::HookType;+use worktrunk::config::UserConfig;+use worktrunk::git::{BranchDeletionMode, Repository, WorktreeInfo};+use worktrunk::styling::{eprintln, hint_message, info_message, println, success_message};++use super::super::command_approval::approve_or_skip;+use super::super::context::CommandEnv;+use super::super::hooks::HookAnnouncer;+use super::super::repository_ext::{RemoveTarget, RepositoryCliExt};+use crate::output::handle_remove_output;++/// Remove worktrees and branches integrated into the default branch.+///+/// Handles four cases: live worktrees with branches (removed + branch deleted),+/// detached HEAD worktrees (directory removed, no branch to delete), stale worktree+/// entries (pruned + branch deleted), and orphan branches without worktrees (deleted).+/// Skips the main/primary worktree, locked worktrees, and worktrees younger than+/// `min_age`. Removes the current worktree last to trigger cd to primary.+pub fn step_prune(+ dry_run: bool,+ yes: bool,+ min_age: &str,+ foreground: bool,+ format: crate::cli::SwitchFormat,+) -> anyhow::Result<()> {+ let min_age_duration =+ humantime::parse_duration(min_age).context("Invalid --min-age duration")?;++ let repo = Repository::current()?;+ let config = UserConfig::load()?;++ // Capture once at command entry. Reused for every per-branch+ // `integration_reason` probe later in this function.+ let snapshot = repo.capture_refs().context("capturing repository refs")?;++ // Pass the local default branch (e.g. "main") directly — `integration_reason`+ // ORs over local + upstream internally, so a branch merged into either side+ // counts as integrated.+ let integration_target = repo+ .default_branch()+ .context("cannot determine default branch")?;++ let worktrees = repo.list_worktrees().context("listing worktrees")?;+ let current_root = repo+ .current_worktree()+ .root()+ .context("resolving current worktree root")?+ .to_path_buf();+ let current_root = dunce::canonicalize(¤t_root).unwrap_or(current_root);+ let now_secs = worktrunk::utils::epoch_now();++ let default_branch = repo.default_branch();++ // Gather candidates: integrated worktrees + integrated branch-only refs+ struct Candidate {+ /// Original index in check_items (for deterministic output ordering)+ check_idx: usize,+ /// Branch name (None for detached HEAD worktrees)+ branch: Option<String>,+ /// Display label: branch name or abbreviated commit SHA+ label: String,+ /// Worktree path (for Path-based removal of detached worktrees)+ path: Option<PathBuf>,+ /// Current worktree, other worktree, or branch-only (no worktree)+ kind: CandidateKind,+ }+ enum CandidateKind {+ Current,+ Other,+ BranchOnly,+ }++ impl CandidateKind {+ fn as_str(&self) -> &'static str {+ match self {+ CandidateKind::Current => "current",+ CandidateKind::Other => "worktree",+ CandidateKind::BranchOnly => "branch_only",+ }+ }+ }++ /// Build a human-readable count like "3 worktrees & branches".+ ///+ /// Worktree + branch is the default pair (matching progress messages'+ /// "worktree & branch" pattern). Unpaired items listed separately.+ fn prune_summary(candidates: &[Candidate]) -> String {+ let mut worktree_with_branch = 0usize;+ let mut detached_worktree = 0usize;+ let mut branch_only = 0usize;+ for c in candidates {+ match (&c.kind, &c.branch) {+ (CandidateKind::BranchOnly, _) => branch_only += 1,+ (CandidateKind::Current | CandidateKind::Other, Some(_)) => {+ worktree_with_branch += 1;+ }+ (CandidateKind::Current | CandidateKind::Other, None) => {+ detached_worktree += 1;+ }+ }+ }+ let mut parts = Vec::new();+ if worktree_with_branch > 0 {+ let noun = if worktree_with_branch == 1 {+ "worktree & branch"+ } else {+ "worktrees & branches"+ };+ parts.push(format!("{worktree_with_branch} {noun}"));+ }+ if detached_worktree > 0 {+ let noun = if detached_worktree == 1 {+ "worktree"+ } else {+ "worktrees"+ };+ parts.push(format!("{detached_worktree} {noun}"));+ }+ if branch_only > 0 {+ let noun = if branch_only == 1 {+ "branch"+ } else {+ "branches"+ };+ parts.push(format!("{branch_only} {noun}"));+ }+ parts.join(", ")+ }++ // For non-dry-run, approve hooks upfront so we can remove inline.+ let run_hooks = if dry_run {+ false // unused in dry-run path+ } else {+ let env = CommandEnv::for_action_branchless()?;+ let ctx = env.context(yes);+ approve_or_skip(+ &ctx,+ &[+ HookType::PreRemove,+ HookType::PostRemove,+ HookType::PostSwitch,+ ],+ "Commands declined, continuing removal",+ )?+ };++ let mut removed: Vec<Candidate> = Vec::new();+ let mut deferred_current: Option<Candidate> = None;+ let mut skipped_young: Vec<String> = Vec::new();+ // Track branches seen via worktree entries so we don't double-count+ // in the orphan branch scan below.+ let mut seen_branches: std::collections::HashSet<String> = std::collections::HashSet::new();++ /// Try to remove a candidate immediately. Returns Ok(true) if removed,+ /// Ok(false) if skipped (preparation error), Err on execution error.+ fn try_remove(+ candidate: &Candidate,+ repo: &Repository,+ config: &UserConfig,+ foreground: bool,+ run_hooks: bool,+ worktrees: &[WorktreeInfo],+ snapshot: &worktrunk::git::RefSnapshot,+ ) -> anyhow::Result<bool> {+ let target = match candidate.kind {+ CandidateKind::Current => RemoveTarget::Current,+ CandidateKind::BranchOnly => RemoveTarget::Branch(+ candidate+ .branch+ .as_ref()+ .context("BranchOnly candidate missing branch")?,+ ),+ CandidateKind::Other => match &candidate.branch {+ Some(branch) => RemoveTarget::Branch(branch),+ None => RemoveTarget::Path(+ candidate+ .path+ .as_ref()+ .context("detached candidate missing path")?,+ ),+ },+ };+ let plan = match repo.prepare_worktree_removal(+ target,+ BranchDeletionMode::SafeDelete,+ false,+ config,+ None,+ Some(worktrees),+ Some(snapshot),+ ) {+ Ok(plan) => plan,+ 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);+ }+ };+ let mut announcer = HookAnnouncer::new(repo, config, true);+ handle_remove_output(&plan, foreground, run_hooks, true, &mut announcer)?;+ announcer.flush()?;+ Ok(true)+ }++ enum CheckSource {+ /// Worktree with directory gone (prunable)+ Prunable { branch: String },+ /// Linked worktree+ Linked { wt_idx: usize },+ /// Local branch without a worktree entry+ Orphan,+ }++ struct CheckItem {+ integration_ref: String,+ source: CheckSource,+ }++ let mut check_items: Vec<CheckItem> = Vec::new();++ for (idx, wt) in worktrees.iter().enumerate() {+ if let Some(branch) = &wt.branch {+ seen_branches.insert(branch.clone());+ }++ if wt.locked.is_some() {+ continue;+ }++ if let Some(branch) = &wt.branch+ && default_branch.as_deref() == Some(branch.as_str())+ {+ continue;+ }++ if wt.is_prunable() {+ if let Some(branch) = &wt.branch {+ check_items.push(CheckItem {+ integration_ref: branch.clone(),+ source: CheckSource::Prunable {+ branch: branch.clone(),+ },+ });+ }+ continue;+ }++ // Skip main worktree (non-linked); in bare repos all are linked,+ // so the default-branch check above is the primary guard.+ let wt_tree = repo.worktree_at(&wt.path);+ if !wt_tree+ .is_linked()+ .context("checking whether worktree is linked")?+ {+ continue;+ }++ let integration_ref = match &wt.branch {+ Some(b) if !wt.detached => b.clone(),+ _ => wt.head.clone(),+ };++ check_items.push(CheckItem {+ integration_ref,+ source: CheckSource::Linked { wt_idx: idx },+ });+ }++ for branch in repo.all_branches().context("listing branches")? {+ if seen_branches.contains(&branch) {+ continue;+ }+ if default_branch.as_deref() == Some(branch.as_str()) {+ continue;+ }+ check_items.push(CheckItem {+ integration_ref: branch,+ source: CheckSource::Orphan,+ });+ }++ // Parallel integration checks with inline removals.+ //+ // Spawn integration checks on a background thread via rayon par_iter,+ // sending each result through a channel as it completes. The main thread+ // processes results as they arrive: age-filtering, printing "Skipped"+ // messages, and removing candidates immediately. This overlaps integration+ // checking with removal — output appears as soon as the first check+ // completes instead of waiting for all checks to finish.+ let (tx, rx) = chan::unbounded();+ let integration_refs: Vec<String> = check_items+ .iter()+ .map(|item| item.integration_ref.clone())+ .collect();++ // Intentionally detached: if the main thread returns early (error in+ // the recv loop), remaining rayon tasks silently fail to send on the+ // closed channel and the thread cleans up on its own. Empty+ // integration_refs produces an empty par_iter that completes immediately.+ let repo_clone = repo.clone();+ let target = integration_target.clone();+ // Share by Arc — main thread keeps `snapshot_arc` for `try_remove`; the+ // rayon worker takes a refcount-bump clone. No deep snapshot copy.+ let snapshot_arc = std::sync::Arc::new(snapshot);+ let snapshot_for_thread = std::sync::Arc::clone(&snapshot_arc);+ std::thread::spawn(move || {+ integration_refs+ .into_par_iter()+ .enumerate()+ .for_each(|(idx, ref_name)| {+ let result =+ repo_clone.integration_reason(&snapshot_for_thread, &ref_name, &target);+ let _ = tx.send((idx, result));+ });+ });++ // Collect integration context alongside candidates for dry-run display.+ struct DryRunInfo {+ reason_desc: String,+ effective_target: String,+ suffix: &'static str,+ }+ let mut dry_run_info: Vec<(Candidate, DryRunInfo)> = Vec::new();++ // Process results as they arrive from the channel.+ for (idx, result) in rx {+ let (effective_target, reason) = result.context("checking branch integration")?;+ let Some(reason) = reason else {+ continue;+ };++ let item = &check_items[idx];++ // Linked worktrees need special handling: age check via filesystem+ // metadata, current-worktree deferral, and path-based candidates.+ if let CheckSource::Linked { wt_idx } = &item.source {+ let wt = &worktrees[*wt_idx];+ let label = wt.branch.clone().unwrap_or_else(|| {+ let short = repo.short_sha(&wt.head).unwrap_or_else(|_| wt.head.clone());+ format!("(detached {short})")+ });++ // Skip recently-created worktrees that look "merged" because+ // they were just created from the default branch+ if min_age_duration > Duration::ZERO {+ let wt_tree = repo.worktree_at(&wt.path);+ let git_dir = wt_tree.git_dir().context("resolving worktree git dir")?;+ let metadata = fs::metadata(&git_dir).context("Failed to read worktree git dir")?;+ let created = metadata.created().or_else(|_| {+ fs::metadata(git_dir.join("commondir")).and_then(|m| m.modified())+ });+ if let Ok(created) = created+ && let Ok(created_epoch) = created.duration_since(std::time::UNIX_EPOCH)+ {+ let age = Duration::from_secs(now_secs.saturating_sub(created_epoch.as_secs()));+ if age < min_age_duration {+ if !dry_run {+ eprintln!(+ "{}",+ info_message(format!("Skipped {label} (younger than {min_age})"))+ );+ }+ skipped_young.push(label);+ continue;+ }+ }+ }++ let wt_path = dunce::canonicalize(&wt.path).unwrap_or(wt.path.clone());+ let is_current = wt_path == current_root;+ let candidate = Candidate {+ check_idx: idx,+ branch: if wt.detached { None } else { wt.branch.clone() },+ label,+ path: Some(wt.path.clone()),+ kind: if is_current {+ CandidateKind::Current+ } else {+ CandidateKind::Other+ },+ };+ if dry_run {+ let info = DryRunInfo {+ reason_desc: reason.description().to_string(),+ effective_target,+ suffix: "",+ };+ dry_run_info.push((candidate, info));+ } else if is_current {+ deferred_current = Some(candidate);+ } else if try_remove(+ &candidate,+ &repo,+ &config,+ foreground,+ run_hooks,+ worktrees,+ &snapshot_arc,+ )+ .with_context(|| format!("removing worktree for {}", candidate.label))?+ {+ removed.push(candidate);+ }+ continue;+ }++ // Branch-only candidates: prunable (stale worktree) and orphan branches+ let (branch, suffix) = match &item.source {+ CheckSource::Prunable { branch } => (branch, " (stale)"),+ CheckSource::Orphan => (&item.integration_ref, " (branch only)"),+ CheckSource::Linked { .. } => unreachable!(),+ };++ // Age check for orphan branches via reflog creation timestamp+ if matches!(&item.source, CheckSource::Orphan) && min_age_duration > Duration::ZERO {+ let ref_name = format!("refs/heads/{branch}");+ if let Ok(stdout) = repo.run_command(&["reflog", "show", "--format=%ct", &ref_name])+ && let Some(created_epoch) = stdout+ .trim()+ .lines()+ .last()+ .and_then(|s| s.parse::<u64>().ok())+ {+ let age = Duration::from_secs(now_secs.saturating_sub(created_epoch));+ if age < min_age_duration {+ if !dry_run {+ eprintln!(+ "{}",+ info_message(format!("Skipped {branch} (younger than {min_age})"))+ );+ }+ skipped_young.push(branch.clone());+ continue;+ }+ }+ }++ let candidate = Candidate {+ check_idx: idx,+ label: branch.clone(),+ branch: Some(branch.clone()),+ path: None,+ kind: CandidateKind::BranchOnly,+ };+ if dry_run {+ let info = DryRunInfo {+ reason_desc: reason.description().to_string(),+ effective_target,+ suffix,+ };+ dry_run_info.push((candidate, info));+ } else if try_remove(+ &candidate,+ &repo,+ &config,+ foreground,+ run_hooks,+ worktrees,+ &snapshot_arc,+ )+ .with_context(|| format!("removing worktree for {}", candidate.label))?+ {+ removed.push(candidate);+ }+ }++ if dry_run {+ // Sort by original check order for deterministic output regardless of+ // channel completion order.+ dry_run_info.sort_by_key(|(c, _)| c.check_idx);++ if format == crate::cli::SwitchFormat::Json {+ let items: Vec<serde_json::Value> = dry_run_info+ .iter()+ .map(|(c, info)| {+ serde_json::json!({+ "branch": c.branch,+ "path": c.path,+ "kind": c.kind.as_str(),+ "reason": info.reason_desc,+ "target": info.effective_target,+ })+ })+ .collect();+ println!("{}", serde_json::to_string_pretty(&items)?);+ return Ok(());+ }++ let mut dry_candidates = Vec::new();+ for (candidate, info) in dry_run_info {+ eprintln!(+ "{}",+ info_message(cformat!(+ "<bold>{}</>{} — {} {}",+ candidate.label,+ info.suffix,+ info.reason_desc,+ info.effective_target+ ))+ );+ dry_candidates.push(candidate);+ }++ // Report skipped worktrees (after candidates, before summary).+ // Sort for deterministic output regardless of channel completion order.+ skipped_young.sort();+ if !skipped_young.is_empty() {+ let names = skipped_young.join(", ");+ eprintln!(+ "{}",+ info_message(format!("Skipped {names} (younger than {min_age})"))+ );+ }++ if dry_candidates.is_empty() {+ if skipped_young.is_empty() {+ eprintln!("{}", info_message("No merged worktrees to remove"));+ }+ return Ok(());+ }+ eprintln!(+ "{}",+ hint_message(format!(+ "{} would be removed (dry run)",+ prune_summary(&dry_candidates)+ ))+ );+ return Ok(());+ }++ // Remove deferred current worktree last (cd-to-primary happens here)+ if let Some(current) = deferred_current+ && try_remove(+ ¤t,+ &repo,+ &config,+ foreground,+ run_hooks,+ worktrees,+ &snapshot_arc,+ )+ .with_context(|| format!("removing worktree for {}", current.label))?+ {+ removed.push(current);+ }++ if format == crate::cli::SwitchFormat::Json {+ let items: Vec<serde_json::Value> = removed+ .iter()+ .map(|c| {+ serde_json::json!({+ "branch": c.branch,+ "path": c.path,+ "kind": c.kind.as_str(),+ })+ })+ .collect();+ println!("{}", serde_json::to_string_pretty(&items)?);+ } else if removed.is_empty() {+ if skipped_young.is_empty() {+ eprintln!("{}", info_message("No merged worktrees to remove"));+ }+ } else {+ eprintln!(+ "{}",+ success_message(format!("Pruned {}", prune_summary(&removed)))+ );+ }++ Ok(())+}diff --git a/src/commands/step/rebase.rs b/src/commands/step/rebase.rsnew file mode 100644index 000000000..86cca53f3--- /dev/null+++ b/src/commands/step/rebase.rs@@ -0,0 +1,96 @@+//! `wt step rebase` — rebase onto target branch (also used by `wt merge`).++use anyhow::Context;+use color_print::cformat;+use worktrunk::git::Repository;+use worktrunk::styling::{eprintln, progress_message, success_message};++use super::super::repository_ext::RepositoryCliExt;++/// Result of a rebase operation+pub enum RebaseResult {+ /// Rebase occurred. `fast_forward` distinguishes the two flavors.+ Rebased { target: String, fast_forward: bool },+ /// Already up-to-date with target branch+ UpToDate(String),+}++/// Handle shared rebase workflow (used by `wt step rebase` and `wt merge`)+pub fn handle_rebase(target: Option<&str>) -> anyhow::Result<RebaseResult> {+ let repo = Repository::current()?;++ // Get and validate target ref (any commit-ish for rebase)+ let integration_target = repo.require_target_ref(target)?;++ // Check if already up-to-date (linear extension of target, no merge commits)+ if repo.is_rebased_onto(&integration_target)? {+ return Ok(RebaseResult::UpToDate(integration_target));+ }++ // Check if this is a fast-forward or true rebase+ let merge_base = repo+ .merge_base("HEAD", &integration_target)?+ .context("Cannot rebase: no common ancestor with target branch")?;+ let head_sha = repo.run_command(&["rev-parse", "HEAD"])?.trim().to_string();+ let is_fast_forward = merge_base == head_sha;++ // Only show progress for true rebases (fast-forwards are instant)+ if !is_fast_forward {+ eprintln!(+ "{}",+ progress_message(cformat!("Rebasing onto <bold>{integration_target}</>..."))+ );+ }++ let rebase_result = repo.run_command(&["rebase", &integration_target]);++ // If rebase failed, check if it's due to conflicts+ if let Err(e) = rebase_result {+ // Check if it's a rebase conflict+ let is_rebasing = repo+ .worktree_state()?+ .is_some_and(|s| s.starts_with("REBASING"));+ // Pull git's stderr from the typed leaf when present so we get the+ // raw conflict-marker bytes regardless of how many `.context(...)`+ // layers wrap the error.+ let detail = worktrunk::git::display_message(&e);+ if is_rebasing {+ return Err(worktrunk::git::GitError::RebaseConflict {+ target_branch: integration_target,+ git_output: detail,+ }+ .into());+ }+ // Not a rebase conflict, return original error+ return Err(worktrunk::git::GitError::Other {+ message: cformat!(+ "Failed to rebase onto <bold>{}</>: {}",+ integration_target,+ detail+ ),+ }+ .into());+ }++ // Verify rebase completed successfully (safety check for edge cases)+ if repo.worktree_state()?.is_some() {+ return Err(worktrunk::git::GitError::RebaseConflict {+ target_branch: integration_target,+ git_output: String::new(),+ }+ .into());+ }++ // Success+ let msg = if is_fast_forward {+ cformat!("Fast-forwarded to <bold>{integration_target}</>")+ } else {+ cformat!("Rebased onto <bold>{integration_target}</>")+ };+ eprintln!("{}", success_message(msg));++ Ok(RebaseResult::Rebased {+ target: integration_target,+ fast_forward: is_fast_forward,+ })+}diff --git a/src/commands/step/relocate.rs b/src/commands/step/relocate.rsnew file mode 100644index 000000000..1b4798c15--- /dev/null+++ b/src/commands/step/relocate.rs@@ -0,0 +1,160 @@+//! `wt step relocate` — move worktrees to expected paths based on the `worktree-path` template.+//!+//! See `src/commands/relocate.rs` for the implementation details and algorithm.++use std::path::PathBuf;++use worktrunk::config::UserConfig;+use worktrunk::git::Repository;+use worktrunk::styling::println;++/// Move worktrees to their expected paths based on the `worktree-path` template.+///+/// See `src/commands/relocate.rs` for the implementation details and algorithm.+///+/// # Flags+///+/// | Flag | Purpose |+/// |------|---------|+/// | `--dry-run` | Show what would be moved without moving |+/// | `--commit` | Auto-commit dirty worktrees with LLM-generated messages before relocating |+/// | `--clobber` | Move non-worktree paths out of the way (`<path>.bak-<timestamp>`) |+/// | `[branches...]` | Specific branches to relocate (default: all mismatched) |+pub fn step_relocate(+ branches: Vec<String>,+ dry_run: bool,+ commit: bool,+ clobber: bool,+ format: crate::cli::SwitchFormat,+) -> anyhow::Result<()> {+ use super::super::relocate::{+ GatherResult, RelocationExecutor, ValidationResult, gather_candidates, show_all_skipped,+ show_dry_run_preview, show_no_relocations_needed, show_summary, validate_candidates,+ };++ let json_mode = format == crate::cli::SwitchFormat::Json;++ let repo = Repository::current()?;+ let config = UserConfig::load()?;+ let default_branch = repo.default_branch().unwrap_or_default();++ // Validate default branch early - needed for main worktree relocation+ if default_branch.is_empty() {+ anyhow::bail!(+ "Cannot determine default branch; set with: wt config state default-branch set main"+ );+ }+ let repo_path = repo.repo_path()?.to_path_buf();++ // Phase 1: Gather candidates (worktrees not at expected paths)+ let GatherResult {+ candidates,+ template_error_branches,+ } = gather_candidates(&repo, &config, &branches)?;++ let template_skips: Vec<super::super::relocate::SkippedEntry> = template_error_branches+ .iter()+ .map(|b| super::super::relocate::SkippedEntry {+ branch: b.clone(),+ reason: "template_error",+ })+ .collect();++ if candidates.is_empty() {+ if json_mode {+ print_relocate_json(&[], &template_skips, dry_run)?;+ } else {+ show_no_relocations_needed(template_error_branches.len());+ }+ return Ok(());+ }++ // Dry run: show preview and exit+ if dry_run {+ if json_mode {+ let planned: Vec<_> = candidates+ .iter()+ .map(|c| RelocatedEntryView {+ branch: c.branch().to_string(),+ from: c.wt.path.clone(),+ to: c.expected_path.clone(),+ })+ .collect();+ print_relocate_json(&planned, &template_skips, true)?;+ } else {+ show_dry_run_preview(&candidates);+ }+ return Ok(());+ }++ // Phase 2: Validate candidates (check locked/dirty, optionally auto-commit)+ let ValidationResult {+ validated,+ skipped: validation_skipped,+ } = validate_candidates(&repo, &config, candidates, commit, &repo_path)?;++ if validated.is_empty() {+ if json_mode {+ let mut all_skipped = template_skips;+ all_skipped.extend(validation_skipped);+ print_relocate_json(&[], &all_skipped, false)?;+ } else {+ show_all_skipped(validation_skipped.len());+ }+ return Ok(());+ }++ // Phase 3 & 4: Create executor (classifies targets) and execute relocations+ let mut executor = RelocationExecutor::new(&repo, validated, clobber)?;+ let cwd = std::env::current_dir().ok();+ executor.execute(&default_branch, cwd.as_deref())?;++ if json_mode {+ let relocated_views: Vec<RelocatedEntryView> = executor+ .relocated_entries+ .iter()+ .map(|e| RelocatedEntryView {+ branch: e.branch.clone(),+ from: e.from.clone(),+ to: e.to.clone(),+ })+ .collect();+ let mut all_skipped = template_skips;+ all_skipped.extend(validation_skipped);+ all_skipped.extend(executor.skipped_entries);+ print_relocate_json(&relocated_views, &all_skipped, false)?;+ } else {+ let total_skipped = validation_skipped.len() + executor.skipped_count();+ show_summary(executor.relocated_count(), total_skipped);+ }++ Ok(())+}++/// Internal projection of a relocation event for JSON output.+struct RelocatedEntryView {+ branch: String,+ from: PathBuf,+ to: PathBuf,+}++fn print_relocate_json(+ entries: &[RelocatedEntryView],+ skipped: &[super::super::relocate::SkippedEntry],+ dry_run: bool,+) -> anyhow::Result<()> {+ let payload = serde_json::json!({+ "dry_run": dry_run,+ "entries": entries.iter().map(|e| serde_json::json!({+ "branch": e.branch,+ "from": e.from,+ "to": e.to,+ })).collect::<Vec<_>>(),+ "skipped": skipped.iter().map(|s| serde_json::json!({+ "branch": s.branch,+ "reason": s.reason,+ })).collect::<Vec<_>>(),+ });+ println!("{}", serde_json::to_string_pretty(&payload)?);+ Ok(())+}diff --git a/src/commands/step/shared.rs b/src/commands/step/shared.rsnew file mode 100644index 000000000..821a9bde5--- /dev/null+++ b/src/commands/step/shared.rs@@ -0,0 +1,230 @@+//! Helpers shared between multiple step subcommands.+//!+//! - `print_dry_run` — used by `commit` and `squash` for `--dry-run` output.+//! - Copy-ignored discovery (`list_and_filter_ignored_entries` and friends) —+//! used by `copy_ignored` and `promote`.++use std::path::{Path, PathBuf};++use anyhow::Context;+use ignore::gitignore::GitignoreBuilder;+use worktrunk::config::CopyIgnoredConfig;+use worktrunk::git::Repository;+use worktrunk::shell_exec::Cmd;+use worktrunk::styling::{format_bash_with_gutter, format_heading, format_with_gutter};++use super::super::commit::CommitGenerator;++/// Print the three dry-run sections: rendered prompt, LLM command, generated message.+///+/// The COMMAND and MESSAGE sections use the same gutter treatment as the regular commit+/// flow — `format_bash_with_gutter` for the shell invocation, and the bold-first-line+/// commit message format wrapped in `format_with_gutter`. The PROMPT is left ungutter'd+/// to keep `--dry-run`'s output visually aligned with `--show-prompt`.+///+/// Output is routed through the pager when stdout is a TTY (see writing-user-outputs →+/// "When to page output"). The helper falls back to direct stdout when piped.+pub(super) fn print_dry_run(+ prompt: &str,+ commit_config: &worktrunk::config::CommitGenerationConfig,+ message: &str,+) -> anyhow::Result<()> {+ let command_block = match commit_config+ .command+ .as_deref()+ .filter(|s| !s.trim().is_empty())+ {+ Some(cmd) => format_bash_with_gutter(&crate::llm::render_llm_invocation(cmd)?),+ None => format_with_gutter("(LLM not configured — using built-in fallback)", None),+ };+ let formatted = CommitGenerator::new(commit_config).format_message_for_display(message);+ let out = format!(+ "{prompt_heading}\n{prompt}\n\n{command_heading}\n{command_block}\n\n{message_heading}\n{message_block}\n",+ prompt_heading = format_heading("PROMPT", None),+ command_heading = format_heading("COMMAND", None),+ message_heading = format_heading("MESSAGE", None),+ message_block = format_with_gutter(&formatted, None),+ );++ crate::help_pager::show_help_in_pager(&out, true);+ Ok(())+}++/// Built-in excludes for `wt step copy-ignored`: VCS metadata + tool-state directories.+///+/// VCS directories contain internal state tied to a specific working directory.+/// Git's own `.git` is implicitly excluded (git ls-files never reports it), but+/// other VCS tools colocated with git need explicit exclusion. Tool-state+/// directories (`.conductor/`, `.worktrees/`, etc.) are project-local state that+/// shouldn't be shared between worktrees.+pub(super) const BUILTIN_COPY_IGNORED_EXCLUDES: &[&str] = &[+ ".bzr/",+ ".conductor/",+ ".entire/",+ ".hg/",+ ".jj/",+ ".pijul/",+ ".sl/",+ ".svn/",+ ".worktrees/",+];++fn default_copy_ignored_excludes() -> Vec<String> {+ BUILTIN_COPY_IGNORED_EXCLUDES+ .iter()+ .map(|s| (*s).to_string())+ .collect()+}++/// Resolve the full copy-ignored config by merging built-in defaults, project+/// config (`.config/wt.toml`), and user config (global + per-project overrides).+pub(super) fn resolve_copy_ignored_config(repo: &Repository) -> anyhow::Result<CopyIgnoredConfig> {+ let mut config = CopyIgnoredConfig {+ exclude: default_copy_ignored_excludes(),+ };+ let user_config = repo.user_config();+ let project_config = repo+ .project_config()+ .context("Failed to load project config")?;+ if let Some(project_config) = project_config+ && let Some(project_copy_ignored) = project_config.copy_ignored()+ {+ config = config.merged_with(project_copy_ignored);+ }+ let project_id = repo.project_identifier().ok();+ config = config.merged_with(&user_config.copy_ignored(project_id.as_deref()));+ Ok(config)+}++/// List gitignored entries in a worktree, filtered by `.worktreeinclude` and excluding+/// configured patterns, VCS metadata directories, and entries that contain nested worktrees.+///+/// Combines five steps:+/// 1. `list_ignored_entries()` — git ls-files for ignored entries+/// 2. `.worktreeinclude` filtering — only matching entries if the file exists+/// 3. `[step.copy-ignored].exclude` filtering — skip entries matching configured patterns+/// 4. Built-in exclude filtering — always skip VCS metadata and tool-state directories+/// 5. Nested worktree filtering — exclude entries containing other worktrees+pub(super) fn list_and_filter_ignored_entries(+ worktree_path: &Path,+ context: &str,+ worktree_paths: &[PathBuf],+ exclude_patterns: &[String],+) -> anyhow::Result<Vec<(PathBuf, bool)>> {+ let ignored_entries = list_ignored_entries(worktree_path, context)?;++ // Filter to entries that match .worktreeinclude (or all if no file exists)+ let include_path = worktree_path.join(".worktreeinclude");+ let filtered: Vec<_> = if include_path.exists() {+ let include_matcher = {+ let mut builder = GitignoreBuilder::new(worktree_path);+ if let Some(err) = builder.add(&include_path) {+ // The `ignore` crate formats the path with OS-native separators;+ // normalize to forward slashes for consistent display.+ return Err(worktrunk::git::GitError::WorktreeIncludeParseError {+ error: err.to_string().replace('\\', "/"),+ }+ .into());+ }+ builder.build().context("Failed to build include matcher")?+ };+ ignored_entries+ .into_iter()+ .filter(|(path, is_dir)| include_matcher.matched(path, *is_dir).is_ignore())+ .collect()+ } else {+ ignored_entries+ };++ // Build exclude matcher for configured patterns (if any)+ let exclude_matcher = if exclude_patterns.is_empty() {+ None+ } else {+ let mut builder = GitignoreBuilder::new(worktree_path);+ for pattern in exclude_patterns {+ builder.add_line(None, pattern).map_err(|error| {+ anyhow::anyhow!(+ "Invalid [step.copy-ignored].exclude pattern {:?}: {}",+ pattern,+ error+ )+ })?;+ }+ Some(+ builder+ .build()+ .context("Failed to build copy-ignored exclude matcher")?,+ )+ };++ // Filter out excluded patterns, VCS metadata directories, and nested worktrees+ Ok(filtered+ .into_iter()+ .filter(|(path, is_dir)| {+ // Skip entries matching configured exclude patterns+ if let Some(ref matcher) = exclude_matcher {+ let relative = path.strip_prefix(worktree_path).unwrap_or(path.as_path());+ if matcher.matched(relative, *is_dir).is_ignore() {+ return false;+ }+ }+ // Skip built-in excluded directories (.jj, .hg, .worktrees, etc.)+ if *is_dir+ && path+ .file_name()+ .and_then(|n| n.to_str())+ .is_some_and(|name| {+ BUILTIN_COPY_IGNORED_EXCLUDES+ .iter()+ .any(|pat| pat.trim_end_matches('/') == name)+ })+ {+ return false;+ }+ // Skip entries that contain other worktrees+ !worktree_paths+ .iter()+ .any(|wt_path| wt_path != worktree_path && wt_path.starts_with(path))+ })+ .collect())+}++/// List ignored entries using git ls-files+///+/// Uses `git ls-files --ignored --exclude-standard -o --directory` which:+/// - Handles all gitignore sources (global, .gitignore, .git/info/exclude, nested)+/// - Stops at directory boundaries (--directory) to avoid listing thousands of files+fn list_ignored_entries(+ worktree_path: &Path,+ context: &str,+) -> anyhow::Result<Vec<(std::path::PathBuf, bool)>> {+ let output = Cmd::new("git")+ .args([+ "ls-files",+ "--ignored",+ "--exclude-standard",+ "-o",+ "--directory",+ ])+ .current_dir(worktree_path)+ .context(context)+ .run()+ .context("Failed to run git ls-files")?;++ if !output.status.success() {+ let stderr = String::from_utf8_lossy(&output.stderr);+ anyhow::bail!("git ls-files failed: {}", stderr.trim());+ }++ // Parse output: directories end with /+ let entries = String::from_utf8_lossy(&output.stdout)+ .lines()+ .map(|line| {+ let is_dir = line.ends_with('/');+ let path = worktree_path.join(line.trim_end_matches('/'));+ (path, is_dir)+ })+ .collect();++ Ok(entries)+}diff --git a/src/commands/step/squash.rs b/src/commands/step/squash.rsnew file mode 100644index 000000000..ff40bb374--- /dev/null+++ b/src/commands/step/squash.rs@@ -0,0 +1,365 @@+//! `wt step squash` — squash commits into one (also used by `wt merge --squash`).++use anyhow::Context;+use color_print::cformat;+use worktrunk::HookType;+use worktrunk::config::UserConfig;+use worktrunk::git::Repository;+use worktrunk::styling::{+ eprintln, format_with_gutter, hint_message, info_message, println, progress_message,+ success_message,+};++use super::super::command_approval::approve_or_skip;+use super::super::command_executor::FailureStrategy;+use super::super::commit::{CommitGenerator, CommitOutcome, HookGate, StageMode};+use super::super::context::CommandEnv;+use super::super::hooks::{self, HookAnnouncer, execute_hook};+use super::super::repository_ext::RepositoryCliExt;+use super::super::template_vars::TemplateVars;+use super::shared::print_dry_run;++/// Result of a squash operation+#[derive(Debug, Clone)]+pub enum SquashResult {+ /// Squash or commit occurred. Carries the resulting commit's SHA, message,+ /// and resolved stage mode so callers can render structured output.+ Squashed {+ sha: String,+ message: String,+ stage_mode: StageMode,+ },+ /// Nothing to squash: no commits ahead of target branch+ NoCommitsAhead(String),+ /// Nothing to squash: already a single commit+ AlreadySingleCommit,+ /// Squash attempted but resulted in no net changes (commits canceled out)+ NoNetChanges,+}++/// Handle shared squash workflow (used by `wt step squash` and `wt merge`)+///+/// # Arguments+/// * `hooks` - Whether to run pre-commit hooks. `Run` triggers an internal approval+/// prompt; `NoHooksFlag` skips with a "(--no-hooks)" message; `Silent` skips silently+/// (used when the caller already declined approval upstream and announced it).+/// * `stage` - CLI-provided stage mode. If None, uses the effective config default.+/// * `announcer` - Post-commit hooks register on the caller's announcer; the+/// caller decides when to flush. Multi-phase callers (`wt merge --squash`+/// combining post-commit + post-remove + post-switch + post-merge) share+/// one announce line; standalone callers (`wt step squash`) construct an+/// announcer of their own and flush right after.+pub fn handle_squash(+ target: Option<&str>,+ yes: bool,+ hooks: HookGate,+ stage: Option<StageMode>,+ announcer: &mut HookAnnouncer<'_>,+) -> anyhow::Result<SquashResult> {+ // Load config once, run LLM setup prompt, then reuse config+ let mut config = UserConfig::load().context("Failed to load config")?;+ // One-time LLM setup prompt (errors logged internally; don't block commit)+ let _ = crate::output::prompt_commit_generation(&mut config);++ let env = CommandEnv::for_action(config)?;+ let repo = &env.repo;+ // Squash requires being on a branch (can't squash in detached HEAD)+ let current_branch = env.require_branch("squash")?.to_string();+ let ctx = env.context(yes);+ let resolved = env.resolved();+ let generator = CommitGenerator::new(&resolved.commit_generation);++ // CLI flag overrides config value+ let stage_mode = stage.unwrap_or(resolved.commit.stage());++ // Check if any pre-commit hooks exist (needed for skip message and approval)+ let project_config = repo.load_project_config()?;+ let user_hooks = ctx.config.hooks(ctx.project_id().as_deref());+ let (user_cfg, proj_cfg) =+ hooks::lookup_hook_configs(&user_hooks, project_config.as_ref(), HookType::PreCommit);+ let any_hooks_exist = user_cfg.is_some() || proj_cfg.is_some();++ // Resolve the hook gate: Run triggers an approval prompt and downgrades to Silent+ // on decline (approve_or_skip prints its own message). NoHooksFlag prints the skip+ // message itself; Silent stays quiet so the upstream caller's decline message isn't+ // followed by a spurious "(--no-hooks)" line.+ let hooks = match hooks {+ HookGate::Run => {+ if approve_or_skip(+ &ctx,+ &[HookType::PreCommit, HookType::PostCommit],+ "Commands declined, squashing without hooks",+ )? {+ HookGate::Run+ } else {+ HookGate::Silent+ }+ }+ HookGate::NoHooksFlag => {+ if any_hooks_exist {+ eprintln!("{}", info_message("Skipping pre-commit hooks (--no-hooks)"));+ }+ HookGate::NoHooksFlag+ }+ HookGate::Silent => HookGate::Silent,+ };++ // Get and validate target ref (any commit-ish for merge-base calculation)+ let integration_target = repo.require_target_ref(target)?;+ let template_vars = TemplateVars::new().with_target(&integration_target);++ // Auto-stage changes before running pre-commit hooks so both beta and merge paths behave identically+ match stage_mode {+ StageMode::All => {+ repo.warn_if_auto_staging_untracked()?;+ repo.run_command(&["add", "-A"])+ .context("Failed to stage changes")?;+ }+ StageMode::Tracked => {+ repo.run_command(&["add", "-u"])+ .context("Failed to stage tracked changes")?;+ }+ StageMode::None => {+ // Stage nothing - use what's already staged+ }+ }++ // Run pre-commit hooks (user first, then project).+ if hooks.run() {+ execute_hook(+ &ctx,+ HookType::PreCommit,+ &template_vars.as_extra_vars(),+ FailureStrategy::FailFast,+ crate::output::pre_hook_display_path(ctx.worktree_path),+ )?;+ }++ // Get merge base with target branch (required for squash)+ let merge_base = repo+ .merge_base("HEAD", &integration_target)?+ .context("Cannot squash: no common ancestor with target branch")?;++ // Count commits since merge base+ let commit_count = repo.count_commits(&merge_base, "HEAD")?;++ // Check if there are staged changes in addition to commits+ let wt = repo.current_worktree();+ let has_staged = wt.has_staged_changes()?;++ // Handle different scenarios+ if commit_count == 0 && !has_staged {+ // No commits and no staged changes - nothing to squash+ return Ok(SquashResult::NoCommitsAhead(integration_target));+ }++ if commit_count == 0 && has_staged {+ // Just staged changes, no commits - commit them directly (no squashing needed)+ let CommitOutcome {+ sha,+ message,+ stage_mode,+ } = generator.commit_staged_changes(&wt, true, true, stage_mode)?;+ return Ok(SquashResult::Squashed {+ sha,+ message,+ stage_mode,+ });+ }++ if commit_count == 1 && !has_staged {+ // Single commit, no staged changes - already squashed+ return Ok(SquashResult::AlreadySingleCommit);+ }++ // Either multiple commits OR single commit with staged changes - squash them+ // Get diff stats early for display in progress message+ let range = format!("{}..HEAD", merge_base);++ let commit_text = if commit_count == 1 {+ "commit"+ } else {+ "commits"+ };++ // Get total stats (commits + any working tree changes)+ let total_stats = if has_staged {+ repo.diff_stats_summary(&["diff", "--shortstat", &merge_base, "--cached"])+ } else {+ repo.diff_stats_summary(&["diff", "--shortstat", &range])+ };++ let with_changes = if has_staged {+ match stage_mode {+ StageMode::Tracked => " & tracked changes",+ _ => " & working tree changes",+ }+ } else {+ ""+ };++ // Build parenthesized content: stats only (stage mode is in message text)+ let parts = total_stats;++ let squash_progress = if parts.is_empty() {+ format!("Squashing {commit_count} {commit_text}{with_changes} into a single commit...")+ } else {+ // Gray parenthetical with separate cformat for closing paren (avoids optimizer)+ let parts_str = parts.join(", ");+ let paren_close = cformat!("<bright-black>)</>");+ cformat!(+ "Squashing {commit_count} {commit_text}{with_changes} into a single commit <bright-black>({parts_str}</>{paren_close}..."+ )+ };+ eprintln!("{}", progress_message(squash_progress));++ // Create safety backup before potentially destructive reset if there are working tree changes+ if has_staged {+ let backup_message = format!("{} → {} (squash)", current_branch, integration_target);+ let sha = wt.create_safety_backup(&backup_message)?;+ eprintln!("{}", hint_message(format!("Backup created @ {sha}")));+ }++ // Get commit subjects for the squash message+ let subjects = repo.commit_subjects(&range)?;++ // Generate squash commit message+ eprintln!(+ "{}",+ progress_message("Generating squash commit message...")+ );++ generator.emit_hint_if_needed();++ // Get current branch and repo name for template variables+ let repo_root = wt.root()?;+ let repo_name = repo_root+ .file_name()+ .and_then(|n| n.to_str())+ .unwrap_or("repo");++ let commit_message = crate::llm::generate_squash_message(+ &integration_target,+ &merge_base,+ &subjects,+ ¤t_branch,+ repo_name,+ &resolved.commit_generation,+ )?;++ // Display the generated commit message+ let formatted_message = generator.format_message_for_display(&commit_message);+ eprintln!("{}", format_with_gutter(&formatted_message, None));++ // Reset to merge base (soft reset stages all changes, including any already-staged uncommitted changes)+ //+ // TOCTOU note: Between this reset and the commit below, an external process could+ // modify the staging area. This is extremely unlikely (requires precise timing) and+ // the consequence is minor (unexpected content in squash commit). The commit message+ // generated above accurately reflects the original commits being squashed, so any+ // discrepancy would be visible in the diff. Considered acceptable risk.+ repo.run_command(&["reset", "--soft", &merge_base])+ .context("Failed to reset to merge base")?;++ // Check if there are actually any changes to commit+ if !wt.has_staged_changes()? {+ eprintln!(+ "{}",+ info_message(format!(+ "No changes after squashing {commit_count} {commit_text}"+ ))+ );+ return Ok(SquashResult::NoNetChanges);+ }++ // Commit with the generated message+ repo.run_command(&["commit", "-m", &commit_message])+ .context("Failed to create squash commit")?;++ // Full SHA for the JSON payload, abbreviated form for the success line.+ let commit_sha = repo.run_command(&["rev-parse", "HEAD"])?.trim().to_string();+ let commit_hash = repo.short_sha(&commit_sha)?;++ // Show success immediately after completing the squash+ eprintln!(+ "{}",+ success_message(cformat!("Squashed @ <dim>{commit_hash}</>"))+ );++ // Register post-commit hooks onto the caller's announcer (respects --no-hooks).+ if hooks.run() {+ let extra_vars = template_vars.as_extra_vars();+ announcer.register(&ctx, HookType::PostCommit, &extra_vars, None)?;+ }++ Ok(SquashResult::Squashed {+ sha: commit_sha,+ message: commit_message,+ stage_mode,+ })+}++/// Handle `wt step squash --show-prompt`+///+/// Builds and outputs the squash prompt without running the LLM or squashing.+pub fn step_show_squash_prompt(target: Option<&str>) -> anyhow::Result<()> {+ preview_squash(target, false)+}++/// Handle `wt step squash --dry-run`+///+/// Renders the squash prompt, prints the LLM command, generates the message, and prints+/// it without resetting, running hooks, or committing.+pub fn step_dry_run_squash(target: Option<&str>) -> anyhow::Result<()> {+ preview_squash(target, true)+}++/// Shared implementation for `--show-prompt` and `--dry-run` on squash. `--show-prompt`+/// (`dry_run = false`) outputs only the rendered prompt; `--dry-run` additionally calls+/// the LLM and prints the command and the generated message.+fn preview_squash(target: Option<&str>, dry_run: bool) -> anyhow::Result<()> {+ let repo = Repository::current()?;+ let config = UserConfig::load().context("Failed to load config")?;+ let project_id = repo.project_identifier().ok();+ let commit_config = config.commit_generation(project_id.as_deref());++ let integration_target = repo.require_target_ref(target)?;++ let wt = repo.current_worktree();+ let current_branch = wt.branch()?.unwrap_or_else(|| "HEAD".to_string());++ let merge_base = repo+ .merge_base("HEAD", &integration_target)?+ .context("Cannot generate squash message: no common ancestor with target branch")?;++ let range = format!("{}..HEAD", merge_base);+ let subjects = repo.commit_subjects(&range)?;++ let repo_root = wt.root()?;+ let repo_name = repo_root+ .file_name()+ .and_then(|n| n.to_str())+ .unwrap_or("repo");++ let prompt = crate::llm::build_squash_prompt(+ &integration_target,+ &merge_base,+ &subjects,+ ¤t_branch,+ repo_name,+ &commit_config,+ )?;+ if !dry_run {+ println!("{}", prompt);+ return Ok(());+ }+ let message = crate::llm::generate_squash_message(+ &integration_target,+ &merge_base,+ &subjects,+ ¤t_branch,+ repo_name,+ &commit_config,+ )?;+ print_dry_run(&prompt, &commit_config, &message)+}diff --git a/src/commands/step_commands.rs b/src/commands/step_commands.rsdeleted file mode 100644index 243895bb9..000000000--- a/src/commands/step_commands.rs+++ /dev/null@@ -1,2292 +0,0 @@-//! Step commands for the merge workflow and standalone worktree utilities.-//!-//! Merge steps:-//! - `step_commit` - Commit working tree changes-//! - `handle_squash` - Squash commits into one-//! - `step_show_squash_prompt` - Show squash prompt without executing-//! - `handle_rebase` - Rebase onto target branch-//! - `step_diff` - Show all changes since branching-//!-//! Standalone:-//! - `step_copy_ignored` - Copy gitignored files matching .worktreeinclude-//! - `handle_promote` - Swap a branch into the main worktree-//! - `step_prune` - Remove worktrees merged into the default branch--use std::fs;-use std::io::ErrorKind;-use std::path::{Path, PathBuf};-use std::time::Duration;--use anyhow::Context;-use color_print::cformat;-use crossbeam_channel as chan;-use ignore::gitignore::GitignoreBuilder;-use path_slash::PathExt as _;-use rayon::prelude::*;-use worktrunk::HookType;-use worktrunk::config::{CopyIgnoredConfig, UserConfig};-use worktrunk::copy::{copy_dir_recursive, copy_leaf};-use worktrunk::git::{Repository, WorktreeInfo};-use worktrunk::path::format_path_for_display;-use worktrunk::progress::{Progress, format_bytes};-use worktrunk::shell_exec::Cmd;-use worktrunk::styling::{- eprintln, format_bash_with_gutter, format_heading, format_with_gutter, hint_message,- info_message, println, progress_message, success_message, verbosity, warning_message,-};--use super::command_approval::approve_or_skip;-use super::command_executor::FailureStrategy;-use super::commit::{CommitGenerator, CommitOptions, CommitOutcome, HookGate, StageMode};-use super::context::CommandEnv;-use super::hooks::{HookAnnouncer, execute_hook};-use super::repository_ext::{RemoveTarget, RepositoryCliExt};-use super::template_vars::TemplateVars;-use crate::output::handle_remove_output;-use worktrunk::git::BranchDeletionMode;--/// Handle `wt step commit` command-///-/// `stage` is the CLI-provided stage mode. If None, uses the effective config default.-pub fn step_commit(- branch: Option<String>,- yes: bool,- verify: bool,- stage: Option<StageMode>,- show_prompt: bool,- dry_run: bool,-) -> anyhow::Result<Option<CommitOutcome>> {- // --show-prompt and --dry-run skip hooks and the commit itself; --dry-run still- // mirrors --stage against a temp index so the previewed prompt matches what a real- // run would send the LLM. Neither path produces a CommitOutcome.- if show_prompt || dry_run {- preview_commit(stage, dry_run)?;- return Ok(None);- }-- // Load config once, run LLM setup prompt, then reuse config- let mut config = UserConfig::load().context("Failed to load config")?;- // One-time LLM setup prompt (errors logged internally; don't block commit)- let _ = crate::output::prompt_commit_generation(&mut config);-- let env = match branch {- Some(ref b) => CommandEnv::for_branch(config, b)?,- None => CommandEnv::for_action(config)?,- };- let ctx = env.context(yes);-- // CLI flag overrides config value- let stage_mode = stage.unwrap_or(env.resolved().commit.stage());-- // "Approve at the Gate": prompt for approval upfront (when hooks are enabled) so- // hook execution downstream is fully gated.- let approved = verify- && approve_or_skip(- &ctx,- &[HookType::PreCommit, HookType::PostCommit],- "Commands declined, committing without hooks",- )?;- let hooks = HookGate::from_approval(verify, approved);-- let mut options = CommitOptions::new(&ctx);- options.hooks = hooks;- options.stage_mode = stage_mode;- options.show_no_squash_note = false;- // Only warn about untracked if we're staging all- options.warn_about_untracked = stage_mode == StageMode::All;-- let mut announcer = HookAnnouncer::new(ctx.repo, ctx.config, false);- let outcome = options.commit(&mut announcer)?;- announcer.flush()?;- Ok(Some(outcome))-}--/// Handle `wt step commit` in `--show-prompt` or `--dry-run` mode.-///-/// Both modes skip hooks and the commit itself. `--show-prompt` outputs only the-/// rendered prompt against the existing index (cheap, pipeable). `--dry-run` mirrors-/// `--stage` against a temp index — so the previewed prompt matches what a real run-/// would send — then calls the LLM and prints the command and message in three labeled-/// sections. The user's real index is never modified.-fn preview_commit(stage: Option<StageMode>, dry_run: bool) -> anyhow::Result<()> {- let env = CommandEnv::for_action(UserConfig::load().context("Failed to load config")?)?;- let commit_config = env.resolved().commit_generation.clone();-- // For --dry-run, stage to a copy of the index so the preview reflects what a real- // run would send. --show-prompt skips this — it's the cheap "what's already staged"- // path. StageMode::None has nothing to stage, so we use the existing index as-is.- let temp_index = if dry_run {- let add_args: Option<&[&str]> = match stage.unwrap_or(env.resolved().commit.stage()) {- StageMode::All => Some(&["add", "-A"]),- StageMode::Tracked => Some(&["add", "-u"]),- StageMode::None => None,- };- add_args- .map(|args| stage_to_temp_index(&env.repo, args))- .transpose()?- } else {- None- };- let index_override = temp_index.as_ref().map(|t| t.path());-- let prompt = crate::llm::build_commit_prompt(&commit_config, index_override)?;- if !dry_run {- println!("{}", prompt);- return Ok(());- }- let message = crate::llm::generate_commit_message(&commit_config, index_override)?;- print_dry_run(&prompt, &commit_config, &message)-}--/// Copy the current worktree's index to a temp file and run `git <add_args>` against it.-///-/// Returns the [`tempfile::NamedTempFile`] so the caller controls its lifetime — when-/// dropped, the temp file is removed without ever touching the user's real index.-fn stage_to_temp_index(- repo: &Repository,- add_args: &[&str],-) -> anyhow::Result<tempfile::NamedTempFile> {- let wt = repo.current_worktree();- let real_index = wt.git_dir()?.join("index");- let temp = tempfile::NamedTempFile::new().context("Failed to create temporary index")?;- fs::copy(&real_index, temp.path()).context("Failed to copy index file")?;-- let output = Cmd::new("git")- .args(add_args.iter().copied())- .current_dir(wt.root()?)- .env("GIT_INDEX_FILE", temp.path())- .run()- .context("Failed to stage changes into temp index")?;- if !output.status.success() {- let stderr = String::from_utf8_lossy(&output.stderr);- anyhow::bail!("git {} failed: {}", add_args.join(" "), stderr.trim());- }- Ok(temp)-}--/// Print the three dry-run sections: rendered prompt, LLM command, generated message.-///-/// The COMMAND and MESSAGE sections use the same gutter treatment as the regular commit-/// flow — `format_bash_with_gutter` for the shell invocation, and the bold-first-line-/// commit message format wrapped in `format_with_gutter`. The PROMPT is left ungutter'd-/// to keep `--dry-run`'s output visually aligned with `--show-prompt`.-///-/// Output is routed through the pager when stdout is a TTY (see writing-user-outputs →-/// "When to page output"). The helper falls back to direct stdout when piped.-fn print_dry_run(- prompt: &str,- commit_config: &worktrunk::config::CommitGenerationConfig,- message: &str,-) -> anyhow::Result<()> {- let command_block = match commit_config- .command- .as_deref()- .filter(|s| !s.trim().is_empty())- {- Some(cmd) => format_bash_with_gutter(&crate::llm::render_llm_invocation(cmd)?),- None => format_with_gutter("(LLM not configured — using built-in fallback)", None),- };- let formatted = CommitGenerator::new(commit_config).format_message_for_display(message);- let out = format!(- "{prompt_heading}\n{prompt}\n\n{command_heading}\n{command_block}\n\n{message_heading}\n{message_block}\n",- prompt_heading = format_heading("PROMPT", None),- command_heading = format_heading("COMMAND", None),- message_heading = format_heading("MESSAGE", None),- message_block = format_with_gutter(&formatted, None),- );-- crate::help_pager::show_help_in_pager(&out, true);- Ok(())-}--/// Result of a squash operation-#[derive(Debug, Clone)]-pub enum SquashResult {- /// Squash or commit occurred. Carries the resulting commit's SHA, message,- /// and resolved stage mode so callers can render structured output.- Squashed {- sha: String,- message: String,- stage_mode: StageMode,- },- /// Nothing to squash: no commits ahead of target branch- NoCommitsAhead(String),- /// Nothing to squash: already a single commit- AlreadySingleCommit,- /// Squash attempted but resulted in no net changes (commits canceled out)- NoNetChanges,-}--/// Handle shared squash workflow (used by `wt step squash` and `wt merge`)-///-/// # Arguments-/// * `hooks` - Whether to run pre-commit hooks. `Run` triggers an internal approval-/// prompt; `NoHooksFlag` skips with a "(--no-hooks)" message; `Silent` skips silently-/// (used when the caller already declined approval upstream and announced it).-/// * `stage` - CLI-provided stage mode. If None, uses the effective config default.-/// * `announcer` - Post-commit hooks register on the caller's announcer; the-/// caller decides when to flush. Multi-phase callers (`wt merge --squash`-/// combining post-commit + post-remove + post-switch + post-merge) share-/// one announce line; standalone callers (`wt step squash`) construct an-/// announcer of their own and flush right after.-pub fn handle_squash(- target: Option<&str>,- yes: bool,- hooks: HookGate,- stage: Option<StageMode>,- announcer: &mut HookAnnouncer<'_>,-) -> anyhow::Result<SquashResult> {- // Load config once, run LLM setup prompt, then reuse config- let mut config = UserConfig::load().context("Failed to load config")?;- // One-time LLM setup prompt (errors logged internally; don't block commit)- let _ = crate::output::prompt_commit_generation(&mut config);-- let env = CommandEnv::for_action(config)?;- let repo = &env.repo;- // Squash requires being on a branch (can't squash in detached HEAD)- let current_branch = env.require_branch("squash")?.to_string();- let ctx = env.context(yes);- let resolved = env.resolved();- let generator = CommitGenerator::new(&resolved.commit_generation);-- // CLI flag overrides config value- let stage_mode = stage.unwrap_or(resolved.commit.stage());-- // Check if any pre-commit hooks exist (needed for skip message and approval)- let project_config = repo.load_project_config()?;- let user_hooks = ctx.config.hooks(ctx.project_id().as_deref());- let (user_cfg, proj_cfg) = super::hooks::lookup_hook_configs(- &user_hooks,- project_config.as_ref(),- HookType::PreCommit,- );- let any_hooks_exist = user_cfg.is_some() || proj_cfg.is_some();-- // Resolve the hook gate: Run triggers an approval prompt and downgrades to Silent- // on decline (approve_or_skip prints its own message). NoHooksFlag prints the skip- // message itself; Silent stays quiet so the upstream caller's decline message isn't- // followed by a spurious "(--no-hooks)" line.- let hooks = match hooks {- HookGate::Run => {- if approve_or_skip(- &ctx,- &[HookType::PreCommit, HookType::PostCommit],- "Commands declined, squashing without hooks",- )? {- HookGate::Run- } else {- HookGate::Silent- }- }- HookGate::NoHooksFlag => {- if any_hooks_exist {- eprintln!("{}", info_message("Skipping pre-commit hooks (--no-hooks)"));- }- HookGate::NoHooksFlag- }- HookGate::Silent => HookGate::Silent,- };-- // Get and validate target ref (any commit-ish for merge-base calculation)- let integration_target = repo.require_target_ref(target)?;- let template_vars = TemplateVars::new().with_target(&integration_target);-- // Auto-stage changes before running pre-commit hooks so both beta and merge paths behave identically- match stage_mode {- StageMode::All => {- repo.warn_if_auto_staging_untracked()?;- repo.run_command(&["add", "-A"])- .context("Failed to stage changes")?;- }- StageMode::Tracked => {- repo.run_command(&["add", "-u"])- .context("Failed to stage tracked changes")?;- }- StageMode::None => {- // Stage nothing - use what's already staged- }- }-- // Run pre-commit hooks (user first, then project).- if hooks.run() {- execute_hook(- &ctx,- HookType::PreCommit,- &template_vars.as_extra_vars(),- FailureStrategy::FailFast,- crate::output::pre_hook_display_path(ctx.worktree_path),- )?;- }-- // Get merge base with target branch (required for squash)- let merge_base = repo- .merge_base("HEAD", &integration_target)?- .context("Cannot squash: no common ancestor with target branch")?;-- // Count commits since merge base- let commit_count = repo.count_commits(&merge_base, "HEAD")?;-- // Check if there are staged changes in addition to commits- let wt = repo.current_worktree();- let has_staged = wt.has_staged_changes()?;-- // Handle different scenarios- if commit_count == 0 && !has_staged {- // No commits and no staged changes - nothing to squash- return Ok(SquashResult::NoCommitsAhead(integration_target));- }-- if commit_count == 0 && has_staged {- // Just staged changes, no commits - commit them directly (no squashing needed)- let CommitOutcome {- sha,- message,- stage_mode,- } = generator.commit_staged_changes(&wt, true, true, stage_mode)?;- return Ok(SquashResult::Squashed {- sha,- message,- stage_mode,- });- }-- if commit_count == 1 && !has_staged {- // Single commit, no staged changes - already squashed- return Ok(SquashResult::AlreadySingleCommit);- }-- // Either multiple commits OR single commit with staged changes - squash them- // Get diff stats early for display in progress message- let range = format!("{}..HEAD", merge_base);-- let commit_text = if commit_count == 1 {- "commit"- } else {- "commits"- };-- // Get total stats (commits + any working tree changes)- let total_stats = if has_staged {- repo.diff_stats_summary(&["diff", "--shortstat", &merge_base, "--cached"])- } else {- repo.diff_stats_summary(&["diff", "--shortstat", &range])- };-- let with_changes = if has_staged {- match stage_mode {- StageMode::Tracked => " & tracked changes",- _ => " & working tree changes",- }- } else {- ""- };-- // Build parenthesized content: stats only (stage mode is in message text)- let parts = total_stats;-- let squash_progress = if parts.is_empty() {- format!("Squashing {commit_count} {commit_text}{with_changes} into a single commit...")- } else {- // Gray parenthetical with separate cformat for closing paren (avoids optimizer)- let parts_str = parts.join(", ");- let paren_close = cformat!("<bright-black>)</>");- cformat!(- "Squashing {commit_count} {commit_text}{with_changes} into a single commit <bright-black>({parts_str}</>{paren_close}..."- )- };- eprintln!("{}", progress_message(squash_progress));-- // Create safety backup before potentially destructive reset if there are working tree changes- if has_staged {- let backup_message = format!("{} → {} (squash)", current_branch, integration_target);- let sha = wt.create_safety_backup(&backup_message)?;- eprintln!("{}", hint_message(format!("Backup created @ {sha}")));- }-- // Get commit subjects for the squash message- let subjects = repo.commit_subjects(&range)?;-- // Generate squash commit message- eprintln!(- "{}",- progress_message("Generating squash commit message...")- );-- generator.emit_hint_if_needed();-- // Get current branch and repo name for template variables- let repo_root = wt.root()?;- let repo_name = repo_root- .file_name()- .and_then(|n| n.to_str())- .unwrap_or("repo");-- let commit_message = crate::llm::generate_squash_message(- &integration_target,- &merge_base,- &subjects,- ¤t_branch,- repo_name,- &resolved.commit_generation,- )?;-- // Display the generated commit message- let formatted_message = generator.format_message_for_display(&commit_message);- eprintln!("{}", format_with_gutter(&formatted_message, None));-- // Reset to merge base (soft reset stages all changes, including any already-staged uncommitted changes)- //- // TOCTOU note: Between this reset and the commit below, an external process could- // modify the staging area. This is extremely unlikely (requires precise timing) and- // the consequence is minor (unexpected content in squash commit). The commit message- // generated above accurately reflects the original commits being squashed, so any- // discrepancy would be visible in the diff. Considered acceptable risk.- repo.run_command(&["reset", "--soft", &merge_base])- .context("Failed to reset to merge base")?;-- // Check if there are actually any changes to commit- if !wt.has_staged_changes()? {- eprintln!(- "{}",- info_message(format!(- "No changes after squashing {commit_count} {commit_text}"- ))- );- return Ok(SquashResult::NoNetChanges);- }-- // Commit with the generated message- repo.run_command(&["commit", "-m", &commit_message])- .context("Failed to create squash commit")?;-- // Full SHA for the JSON payload, abbreviated form for the success line.- let commit_sha = repo.run_command(&["rev-parse", "HEAD"])?.trim().to_string();- let commit_hash = repo.short_sha(&commit_sha)?;-- // Show success immediately after completing the squash- eprintln!(- "{}",- success_message(cformat!("Squashed @ <dim>{commit_hash}</>"))- );-- // Register post-commit hooks onto the caller's announcer (respects --no-hooks).- if hooks.run() {- let extra_vars = template_vars.as_extra_vars();- announcer.register(&ctx, HookType::PostCommit, &extra_vars, None)?;- }-- Ok(SquashResult::Squashed {- sha: commit_sha,- message: commit_message,- stage_mode,- })-}--/// Handle `wt step squash --show-prompt`-///-/// Builds and outputs the squash prompt without running the LLM or squashing.-pub fn step_show_squash_prompt(target: Option<&str>) -> anyhow::Result<()> {- preview_squash(target, false)-}--/// Handle `wt step squash --dry-run`-///-/// Renders the squash prompt, prints the LLM command, generates the message, and prints-/// it without resetting, running hooks, or committing.-pub fn step_dry_run_squash(target: Option<&str>) -> anyhow::Result<()> {- preview_squash(target, true)-}--/// Shared implementation for `--show-prompt` and `--dry-run` on squash. `--show-prompt`-/// (`dry_run = false`) outputs only the rendered prompt; `--dry-run` additionally calls-/// the LLM and prints the command and the generated message.-fn preview_squash(target: Option<&str>, dry_run: bool) -> anyhow::Result<()> {- let repo = Repository::current()?;- let config = UserConfig::load().context("Failed to load config")?;- let project_id = repo.project_identifier().ok();- let commit_config = config.commit_generation(project_id.as_deref());-- let integration_target = repo.require_target_ref(target)?;-- let wt = repo.current_worktree();- let current_branch = wt.branch()?.unwrap_or_else(|| "HEAD".to_string());-- let merge_base = repo- .merge_base("HEAD", &integration_target)?- .context("Cannot generate squash message: no common ancestor with target branch")?;-- let range = format!("{}..HEAD", merge_base);- let subjects = repo.commit_subjects(&range)?;-- let repo_root = wt.root()?;- let repo_name = repo_root- .file_name()- .and_then(|n| n.to_str())- .unwrap_or("repo");-- let prompt = crate::llm::build_squash_prompt(- &integration_target,- &merge_base,- &subjects,- ¤t_branch,- repo_name,- &commit_config,- )?;- if !dry_run {- println!("{}", prompt);- return Ok(());- }- let message = crate::llm::generate_squash_message(- &integration_target,- &merge_base,- &subjects,- ¤t_branch,- repo_name,- &commit_config,- )?;- print_dry_run(&prompt, &commit_config, &message)-}--/// Result of a rebase operation-pub enum RebaseResult {- /// Rebase occurred. `fast_forward` distinguishes the two flavors.- Rebased { target: String, fast_forward: bool },- /// Already up-to-date with target branch- UpToDate(String),-}--/// Handle shared rebase workflow (used by `wt step rebase` and `wt merge`)-pub fn handle_rebase(target: Option<&str>) -> anyhow::Result<RebaseResult> {- let repo = Repository::current()?;-- // Get and validate target ref (any commit-ish for rebase)- let integration_target = repo.require_target_ref(target)?;-- // Check if already up-to-date (linear extension of target, no merge commits)- if repo.is_rebased_onto(&integration_target)? {- return Ok(RebaseResult::UpToDate(integration_target));- }-- // Check if this is a fast-forward or true rebase- let merge_base = repo- .merge_base("HEAD", &integration_target)?- .context("Cannot rebase: no common ancestor with target branch")?;- let head_sha = repo.run_command(&["rev-parse", "HEAD"])?.trim().to_string();- let is_fast_forward = merge_base == head_sha;-- // Only show progress for true rebases (fast-forwards are instant)- if !is_fast_forward {- eprintln!(- "{}",- progress_message(cformat!("Rebasing onto <bold>{integration_target}</>..."))- );- }-- let rebase_result = repo.run_command(&["rebase", &integration_target]);-- // If rebase failed, check if it's due to conflicts- if let Err(e) = rebase_result {- // Check if it's a rebase conflict- let is_rebasing = repo- .worktree_state()?- .is_some_and(|s| s.starts_with("REBASING"));- // Pull git's stderr from the typed leaf when present so we get the- // raw conflict-marker bytes regardless of how many `.context(...)`- // layers wrap the error.- let detail = worktrunk::git::display_message(&e);- if is_rebasing {- return Err(worktrunk::git::GitError::RebaseConflict {- target_branch: integration_target,- git_output: detail,- }- .into());- }- // Not a rebase conflict, return original error- return Err(worktrunk::git::GitError::Other {- message: cformat!(- "Failed to rebase onto <bold>{}</>: {}",- integration_target,- detail- ),- }- .into());- }-- // Verify rebase completed successfully (safety check for edge cases)- if repo.worktree_state()?.is_some() {- return Err(worktrunk::git::GitError::RebaseConflict {- target_branch: integration_target,- git_output: String::new(),- }- .into());- }-- // Success- let msg = if is_fast_forward {- cformat!("Fast-forwarded to <bold>{integration_target}</>")- } else {- cformat!("Rebased onto <bold>{integration_target}</>")- };- eprintln!("{}", success_message(msg));-- Ok(RebaseResult::Rebased {- target: integration_target,- fast_forward: is_fast_forward,- })-}--/// Handle `wt step diff` command-///-/// Shows all changes since branching from the target: committed, staged, unstaged,-/// and untracked files in a single diff. Copies the real index to preserve git's stat-/// cache (avoiding re-reads of unchanged files), then registers untracked files with-/// `git add -N` so they appear in the diff.-pub fn step_diff(target: Option<&str>, extra_args: &[String]) -> anyhow::Result<()> {- let repo = Repository::current()?;- let wt = repo.current_worktree();-- // Get and validate target ref- let integration_target = repo.require_target_ref(target)?;-- // Get merge base- let merge_base = repo- .merge_base("HEAD", &integration_target)?- .context("No common ancestor with target branch")?;-- let current_branch = wt.branch()?.unwrap_or_else(|| "HEAD".to_string());-- // Copy the real index so git's stat cache is warm for tracked files, then- // register untracked files with `git add -N .` so they appear in the diff.- // This avoids re-reading and hashing every tracked file during `git diff`.- let worktree_root = wt.root()?;-- let real_index = wt.git_dir()?.join("index");- let temp_index = tempfile::NamedTempFile::new().context("Failed to create temporary index")?;- let temp_index_path = temp_index- .path()- .to_str()- .context("Temporary index path is not valid UTF-8")?;-- std::fs::copy(&real_index, temp_index.path()).context("Failed to copy index file")?;-- // Register untracked files as intent-to-add (tracked files already have entries)- Cmd::new("git")- .args(["add", "--intent-to-add", "."])- .current_dir(&worktree_root)- .context(¤t_branch)- .env("GIT_INDEX_FILE", temp_index_path)- .run()- .context("Failed to register untracked files")?;-- // Stream diff to stdout — git handles pager and coloring- let mut diff_args = vec!["diff".to_string(), merge_base];- diff_args.extend_from_slice(extra_args);- Cmd::new("git")- .args(&diff_args)- .current_dir(&worktree_root)- .context(¤t_branch)- .env("GIT_INDEX_FILE", temp_index_path)- .stream()?;-- Ok(())-}--/// Built-in excludes for `wt step copy-ignored`: VCS metadata + tool-state directories.-///-/// VCS directories contain internal state tied to a specific working directory.-/// Git's own `.git` is implicitly excluded (git ls-files never reports it), but-/// other VCS tools colocated with git need explicit exclusion. Tool-state-/// directories (`.conductor/`, `.worktrees/`, etc.) are project-local state that-/// shouldn't be shared between worktrees.-const BUILTIN_COPY_IGNORED_EXCLUDES: &[&str] = &[- ".bzr/",- ".conductor/",- ".entire/",- ".hg/",- ".jj/",- ".pijul/",- ".sl/",- ".svn/",- ".worktrees/",-];--fn default_copy_ignored_excludes() -> Vec<String> {- BUILTIN_COPY_IGNORED_EXCLUDES- .iter()- .map(|s| (*s).to_string())- .collect()-}--/// Resolve the full copy-ignored config by merging built-in defaults, project-/// config (`.config/wt.toml`), and user config (global + per-project overrides).-fn resolve_copy_ignored_config(repo: &Repository) -> anyhow::Result<CopyIgnoredConfig> {- let mut config = CopyIgnoredConfig {- exclude: default_copy_ignored_excludes(),- };- let user_config = repo.user_config();- let project_config = repo- .project_config()- .context("Failed to load project config")?;- if let Some(project_config) = project_config- && let Some(project_copy_ignored) = project_config.copy_ignored()- {- config = config.merged_with(project_copy_ignored);- }- let project_id = repo.project_identifier().ok();- config = config.merged_with(&user_config.copy_ignored(project_id.as_deref()));- Ok(config)-}--/// List gitignored entries in a worktree, filtered by `.worktreeinclude` and excluding-/// configured patterns, VCS metadata directories, and entries that contain nested worktrees.-///-/// Combines five steps:-/// 1. `list_ignored_entries()` — git ls-files for ignored entries-/// 2. `.worktreeinclude` filtering — only matching entries if the file exists-/// 3. `[step.copy-ignored].exclude` filtering — skip entries matching configured patterns-/// 4. Built-in exclude filtering — always skip VCS metadata and tool-state directories-/// 5. Nested worktree filtering — exclude entries containing other worktrees-fn list_and_filter_ignored_entries(- worktree_path: &Path,- context: &str,- worktree_paths: &[PathBuf],- exclude_patterns: &[String],-) -> anyhow::Result<Vec<(PathBuf, bool)>> {- let ignored_entries = list_ignored_entries(worktree_path, context)?;-- // Filter to entries that match .worktreeinclude (or all if no file exists)- let include_path = worktree_path.join(".worktreeinclude");- let filtered: Vec<_> = if include_path.exists() {- let include_matcher = {- let mut builder = GitignoreBuilder::new(worktree_path);- if let Some(err) = builder.add(&include_path) {- // The `ignore` crate formats the path with OS-native separators;- // normalize to forward slashes for consistent display.- return Err(worktrunk::git::GitError::WorktreeIncludeParseError {- error: err.to_string().replace('\\', "/"),- }- .into());- }- builder.build().context("Failed to build include matcher")?- };- ignored_entries- .into_iter()- .filter(|(path, is_dir)| include_matcher.matched(path, *is_dir).is_ignore())- .collect()- } else {- ignored_entries- };-- // Build exclude matcher for configured patterns (if any)- let exclude_matcher = if exclude_patterns.is_empty() {- None- } else {- let mut builder = GitignoreBuilder::new(worktree_path);- for pattern in exclude_patterns {- builder.add_line(None, pattern).map_err(|error| {- anyhow::anyhow!(- "Invalid [step.copy-ignored].exclude pattern {:?}: {}",- pattern,- error- )- })?;- }- Some(- builder- .build()- .context("Failed to build copy-ignored exclude matcher")?,- )- };-- // Filter out excluded patterns, VCS metadata directories, and nested worktrees- Ok(filtered- .into_iter()- .filter(|(path, is_dir)| {- // Skip entries matching configured exclude patterns- if let Some(ref matcher) = exclude_matcher {- let relative = path.strip_prefix(worktree_path).unwrap_or(path.as_path());- if matcher.matched(relative, *is_dir).is_ignore() {- return false;- }- }- // Skip built-in excluded directories (.jj, .hg, .worktrees, etc.)- if *is_dir- && path- .file_name()- .and_then(|n| n.to_str())- .is_some_and(|name| {- BUILTIN_COPY_IGNORED_EXCLUDES- .iter()- .any(|pat| pat.trim_end_matches('/') == name)- })- {- return false;- }- // Skip entries that contain other worktrees- !worktree_paths- .iter()- .any(|wt_path| wt_path != worktree_path && wt_path.starts_with(path))- })- .collect())-}--/// Handle `wt step copy-ignored` command-///-/// Copies gitignored files from a source worktree to a destination worktree.-/// If a `.worktreeinclude` file exists, only files matching both `.worktreeinclude`-/// and gitignore patterns are copied. Without `.worktreeinclude`, all gitignored-/// files are copied. Uses COW (reflink) when available for efficient copying of-/// large directories like `target/`.-pub fn step_copy_ignored(- from: Option<&str>,- to: Option<&str>,- dry_run: bool,- force: bool,- format: crate::cli::SwitchFormat,-) -> anyhow::Result<()> {- // Self-lower only when we're running inside a background hook pipeline- // (parent `wt` sets `WORKTRUNK_FOREGROUND=-1` on the detached runner).- // Foreground callers — interactive `wt step copy-ignored` and synchronous- // `pre-*` hook pipelines — are the UI the user is waiting on and must not- // be I/O-throttled by `taskpolicy -b` on macOS.- if worktrunk::priority::in_background_hook() {- worktrunk::priority::lower_current_process();- }- let json_mode = format == crate::cli::SwitchFormat::Json;- let repo = Repository::current()?;- let copy_ignored_config = resolve_copy_ignored_config(&repo)?;-- // Resolve source and destination worktree paths- let (source_path, source_context) = match from {- Some(branch) => {- let path = repo.worktree_for_branch(branch)?.ok_or_else(|| {- worktrunk::git::GitError::WorktreeNotFound {- branch: branch.to_string(),- }- })?;- (path, branch.to_string())- }- None => {- // Default source is the primary worktree (main worktree for normal repos,- // default branch worktree for bare repos).- let path = repo.primary_worktree()?.ok_or_else(|| {- anyhow::anyhow!(- "No primary worktree found (bare repo with no default branch worktree)"- )- })?;- let context = path- .file_name()- .map(|n| n.to_string_lossy().into_owned())- .unwrap_or_default();- (path, context)- }- };-- let dest_path = match to {- Some(branch) => repo.worktree_for_branch(branch)?.ok_or_else(|| {- worktrunk::git::GitError::WorktreeNotFound {- branch: branch.to_string(),- }- })?,- None => repo.current_worktree().root()?,- };-- if source_path == dest_path {- if json_mode {- let payload = serde_json::json!({- "outcome": "same_worktree",- "from": source_path,- "to": dest_path,- "entries": Vec::<serde_json::Value>::new(),- "files": 0,- "bytes": 0,- });- println!("{}", serde_json::to_string_pretty(&payload)?);- } else {- eprintln!(- "{}",- info_message("Source and destination are the same worktree")- );- }- return Ok(());- }-- let worktree_paths: Vec<PathBuf> = repo- .list_worktrees()?- .iter()- .map(|wt| wt.path.clone())- .collect();- let entries_to_copy = list_and_filter_ignored_entries(- &source_path,- &source_context,- &worktree_paths,- ©_ignored_config.exclude,- )?;-- if entries_to_copy.is_empty() {- if json_mode {- let payload = serde_json::json!({- "outcome": if dry_run { "planned" } else { "copied" },- "dry_run": dry_run,- "from": source_path,- "to": dest_path,- "entries": Vec::<serde_json::Value>::new(),- "files": 0,- "bytes": 0,- });- println!("{}", serde_json::to_string_pretty(&payload)?);- } else {- eprintln!("{}", info_message("No matching files to copy"));- }- return Ok(());- }-- let verbose = verbosity();-- if dry_run {- if json_mode {- let entries: Vec<_> = entries_to_copy- .iter()- .map(|(src_entry, is_dir)| {- let relative = src_entry- .strip_prefix(&source_path)- .unwrap_or(src_entry.as_path());- serde_json::json!({- "path": relative,- "kind": if *is_dir { "dir" } else { "file" },- })- })- .collect();- let payload = serde_json::json!({- "outcome": "planned",- "dry_run": true,- "from": source_path,- "to": dest_path,- "entries": entries,- });- println!("{}", serde_json::to_string_pretty(&payload)?);- return Ok(());- }- let items: Vec<String> = entries_to_copy- .iter()- .map(|(src_entry, is_dir)| {- let relative = src_entry- .strip_prefix(&source_path)- .unwrap_or(src_entry.as_path());- let entry_type = if *is_dir { "dir" } else { "file" };- format!("{} ({})", format_path_for_display(relative), entry_type)- })- .collect();- let entry_word = if items.len() == 1 { "entry" } else { "entries" };- eprintln!(- "{}",- info_message(format!(- "Would copy {} {}:\n{}",- items.len(),- entry_word,- format_with_gutter(&items.join("\n"), None)- ))- );- return Ok(());- }-- // Show entries in verbose mode (text only — JSON mode emits the full list at the end).- if verbose >= 1 && !json_mode {- let items: Vec<String> = entries_to_copy- .iter()- .map(|(src_entry, is_dir)| {- let relative = src_entry- .strip_prefix(&source_path)- .unwrap_or(src_entry.as_path());- let entry_type = if *is_dir { "dir" } else { "file" };- format!("{} ({})", format_path_for_display(relative), entry_type)- })- .collect();- let entry_word = if items.len() == 1 { "entry" } else { "entries" };- eprintln!(- "{}",- info_message(format!(- "Copying {} {}:\n{}",- items.len(),- entry_word,- format_with_gutter(&items.join("\n"), None)- ))- );- }-- // `start` auto-detects the TTY; verbose/dry-run already print enough.- let progress = if verbose >= 1 || json_mode {- Progress::disabled()- } else {- Progress::start("Copying")- };-- let mut copied_count = 0usize;- let mut copied_bytes = 0u64;- for (src_entry, is_dir) in &entries_to_copy {- let relative = src_entry- .strip_prefix(&source_path)- .expect("git ls-files path under worktree");- let dest_entry = dest_path.join(relative);-- if *is_dir {- let (n, b) =- copy_dir_recursive(src_entry, &dest_entry, Some(&dest_path), force, &progress)- .with_context(|| {- format!("copying directory {}", format_path_for_display(relative))- })?;- copied_count += n;- copied_bytes += b;- } else {- if let Some(parent) = dest_entry.parent() {- fs::create_dir_all(parent).with_context(|| {- format!(- "creating directory for {}",- format_path_for_display(relative)- )- })?;- }- if let Some(bytes) = copy_leaf(src_entry, &dest_entry, Some(&dest_path), force)? {- copied_count += 1;- copied_bytes += bytes;- progress.record(bytes);- }- }- }- progress.finish();-- if json_mode {- // `entries` mirrors dry-run: the top-level units selected for copy- // (files and dirs). `files` counts the actual leaves written- // (recursive + skipping pre-existing files), `bytes` sums their size.- let entries: Vec<_> = entries_to_copy- .iter()- .map(|(src_entry, is_dir)| {- let relative = src_entry- .strip_prefix(&source_path)- .unwrap_or(src_entry.as_path());- serde_json::json!({- "path": relative,- "kind": if *is_dir { "dir" } else { "file" },- })- })- .collect();- let payload = serde_json::json!({- "outcome": "copied",- "dry_run": false,- "from": source_path,- "to": dest_path,- "entries": entries,- "files": copied_count,- "bytes": copied_bytes,- });- println!("{}", serde_json::to_string_pretty(&payload)?);- } else {- // Show summary- let file_word = if copied_count == 1 { "file" } else { "files" };- eprintln!(- "{}",- success_message(format!(- "Copied {copied_count} {file_word} · {}",- format_bytes(copied_bytes)- ))- );- }-- Ok(())-}--/// List ignored entries using git ls-files-///-/// Uses `git ls-files --ignored --exclude-standard -o --directory` which:-/// - Handles all gitignore sources (global, .gitignore, .git/info/exclude, nested)-/// - Stops at directory boundaries (--directory) to avoid listing thousands of files-fn list_ignored_entries(- worktree_path: &Path,- context: &str,-) -> anyhow::Result<Vec<(std::path::PathBuf, bool)>> {- let output = Cmd::new("git")- .args([- "ls-files",- "--ignored",- "--exclude-standard",- "-o",- "--directory",- ])- .current_dir(worktree_path)- .context(context)- .run()- .context("Failed to run git ls-files")?;-- if !output.status.success() {- let stderr = String::from_utf8_lossy(&output.stderr);- anyhow::bail!("git ls-files failed: {}", stderr.trim());- }-- // Parse output: directories end with /- let entries = String::from_utf8_lossy(&output.stdout)- .lines()- .map(|line| {- let is_dir = line.ends_with('/');- let path = worktree_path.join(line.trim_end_matches('/'));- (path, is_dir)- })- .collect();-- Ok(entries)-}--/// Move a file or directory, falling back to copy+delete on cross-device errors.-fn move_entry(src: &Path, dest: &Path, is_dir: bool) -> anyhow::Result<()> {- // Ensure parent directory exists- if let Some(parent) = dest.parent() {- fs::create_dir_all(parent)- .context(format!("creating parent directory for {}", dest.display()))?;- }-- match fs::rename(src, dest) {- Ok(()) => Ok(()),- Err(e) if e.kind() == ErrorKind::CrossesDevices => copy_and_remove(src, dest, is_dir),- Err(e) => Err(anyhow::Error::from(e).context(format!(- "moving {} to {}",- src.display(),- dest.display()- ))),- }-}--/// Copy then delete — fallback when `rename` fails with EXDEV (cross-device).-fn copy_and_remove(src: &Path, dest: &Path, is_dir: bool) -> anyhow::Result<()> {- if is_dir {- copy_dir_recursive(src, dest, None, true, &Progress::disabled())?;- fs::remove_dir_all(src).context(format!("removing source directory {}", src.display()))?;- } else {- copy_leaf(src, dest, None, true)?;-- fs::remove_file(src).context(format!("removing source file {}", src.display()))?;- }- Ok(())-}--const PROMOTE_STAGING_DIR: &str = "staging/promote";--/// Move gitignored files from both worktrees into a staging directory.-///-/// Called BEFORE the branch exchange because `git switch` silently overwrites-/// ignored files that collide with tracked files on the target branch.-///-/// Returns the staging directory path and the count of entries staged.-fn stage_ignored(- repo: &Repository,- path_a: &Path,- entries_a: &[(PathBuf, bool)],- path_b: &Path,- entries_b: &[(PathBuf, bool)],-) -> anyhow::Result<(PathBuf, usize)> {- let staging_dir = repo.wt_dir().join(PROMOTE_STAGING_DIR);- fs::create_dir_all(&staging_dir).context("creating promote staging directory")?;-- let staging_a = staging_dir.join("a");- let staging_b = staging_dir.join("b");- let mut count = 0;-- // Move A's entries → staging/a- for (src_entry, is_dir) in entries_a {- let relative = src_entry- .strip_prefix(path_a)- .context("entry not under worktree A")?;- let staging_entry = staging_a.join(relative);- if fs::symlink_metadata(src_entry).is_ok() {- move_entry(src_entry, &staging_entry, *is_dir)- .context(format!("staging {}", relative.display()))?;- count += 1;- }- }-- // Move B's entries → staging/b- for (src_entry, is_dir) in entries_b {- let relative = src_entry- .strip_prefix(path_b)- .context("entry not under worktree B")?;- let staging_entry = staging_b.join(relative);- if fs::symlink_metadata(src_entry).is_ok() {- move_entry(src_entry, &staging_entry, *is_dir)- .context(format!("staging {}", relative.display()))?;- count += 1;- }- }-- // Clean up empty staging directory (can happen if all entries vanished- // between listing and staging due to TOCTOU)- if count == 0 && staging_dir.exists() {- let _ = fs::remove_dir_all(&staging_dir);- }-- Ok((staging_dir, count))-}--/// Distribute staged files to their new worktrees after a branch exchange.-///-/// B's original files (in staging/b) go to worktree A (which now has B's branch).-/// A's original files (in staging/a) go to worktree B (which now has A's branch).-fn distribute_staged(- staging_dir: &Path,- path_a: &Path,- entries_a: &[(PathBuf, bool)],- path_b: &Path,- entries_b: &[(PathBuf, bool)],-) -> anyhow::Result<usize> {- let staging_a = staging_dir.join("a");- let staging_b = staging_dir.join("b");- let mut count = 0;-- // Move B's staged entries → A (A now has B's branch)- for (src_entry, is_dir) in entries_b {- let relative = src_entry- .strip_prefix(path_b)- .context("entry not under worktree B")?;- let staging_entry = staging_b.join(relative);- let dest_entry = path_a.join(relative);- if fs::symlink_metadata(&staging_entry).is_ok() {- move_entry(&staging_entry, &dest_entry, *is_dir)- .context(format!("distributing {}", relative.display()))?;- count += 1;- }- }-- // Move A's staged entries → B (B now has A's branch)- for (src_entry, is_dir) in entries_a {- let relative = src_entry- .strip_prefix(path_a)- .context("entry not under worktree A")?;- let staging_entry = staging_a.join(relative);- let dest_entry = path_b.join(relative);- if fs::symlink_metadata(&staging_entry).is_ok() {- move_entry(&staging_entry, &dest_entry, *is_dir)- .context(format!("distributing {}", relative.display()))?;- count += 1;- }- }-- // Clean up staging directory (best-effort — files are already distributed)- let _ = fs::remove_dir_all(staging_dir);-- Ok(count)-}--/// Result of a promote operation-pub enum PromoteResult {- /// Branch was promoted successfully- Promoted,- /// Already in canonical state (requested branch is already in main)- AlreadyInMain(String),-}--/// Exchange branches between two worktrees.-///-/// Steps: detach target → detach main → switch main → switch target.-/// Both worktrees must be clean (verified by caller). On failure, attempts-/// best-effort rollback — but failure here is near-impossible given the-/// preconditions (`ensure_clean` passed, branches exist, detach released locks).-fn exchange_branches(- main_wt: &worktrunk::git::WorkingTree<'_>,- main_branch: &str,- target_wt: &worktrunk::git::WorkingTree<'_>,- target_branch: &str,-) -> anyhow::Result<()> {- let steps: &[(&worktrunk::git::WorkingTree<'_>, &[&str], &str)] = &[- (target_wt, &["switch", "--detach"], "detach target"),- (main_wt, &["switch", "--detach"], "detach main"),- (main_wt, &["switch", target_branch], "switch main"),- (target_wt, &["switch", main_branch], "switch target"),- ];-- for (wt, args, label) in steps {- if let Err(e) = wt.run_command(args) {- // Best-effort rollback: try to re-attach both branches.- let _ = main_wt.run_command(&["switch", main_branch]);- let _ = target_wt.run_command(&["switch", target_branch]);- return Err(e.context(format!("branch exchange failed at: {label}")));- }- }-- Ok(())-}--/// Handle `wt step promote` command-///-/// Promotes a branch to the main worktree, exchanging it with whatever branch is currently there.-///-/// ## Interruption recovery-///-/// The swap uses a staging directory at `.git/wt/staging/promote/` and proceeds-/// in three phases:-///-/// 1. **Stage**: move ignored files from both worktrees into staging (`a/`, `b/`)-/// 2. **Exchange**: detach + `git switch` to swap branches-/// 3. **Distribute**: move staged files to their new worktrees, then delete staging-///-/// A hard kill at any phase leaves files in staging, never deleted. The next run-/// detects the leftover directory and bails with a recovery path. A kill during-/// `git switch` may leave a worktree detached (fix: `git switch <branch>`).-pub fn handle_promote(branch: Option<&str>) -> anyhow::Result<PromoteResult> {- use worktrunk::git::GitError;-- let repo = Repository::current()?;- let worktrees = repo.list_worktrees()?;-- if worktrees.is_empty() {- anyhow::bail!("No worktrees found");- }-- // For normal repos, worktrees[0] is the main worktree- // For bare repos, there's no main worktree - we don't support promote there- if repo.is_bare()? {- anyhow::bail!("wt step promote is not supported in bare repositories");- }-- let main_wt = &worktrees[0];- let main_path = &main_wt.path;- let main_branch = main_wt- .branch- .clone()- .ok_or_else(|| GitError::DetachedHead {- action: Some("promote".into()),- })?;-- // Resolve the branch to promote (default_branch computed lazily, only when needed)- let target_branch = match branch {- Some(b) => b.to_string(),- None => {- let current_wt = repo.current_worktree();- if !current_wt.is_linked()? {- // From main worktree with no args: restore default branch- repo.default_branch()- .ok_or_else(|| anyhow::anyhow!("Could not determine default branch"))?- } else {- // From other worktree with no args: promote current branch- current_wt.branch()?.ok_or_else(|| GitError::DetachedHead {- action: Some("promote".into()),- })?- }- }- };-- // Check if target is already in main worktree- if target_branch == main_branch {- return Ok(PromoteResult::AlreadyInMain(target_branch));- }-- // Find the worktree with the target branch- let target_wt = worktrees- .iter()- .skip(1) // Skip main worktree- .find(|wt| wt.branch.as_deref() == Some(&target_branch))- .ok_or_else(|| GitError::WorktreeNotFound {- branch: target_branch.clone(),- })?;-- let target_path = &target_wt.path;-- // Bail early if a leftover staging dir exists from a previous interrupted promote —- // it may contain the user's only copy of files from the failed swap.- // Check BEFORE ensure_clean so users see the recovery path first.- let staging_path = repo.wt_dir().join(PROMOTE_STAGING_DIR);- if staging_path.exists() {- let display = staging_path.to_slash_lossy();- return Err(anyhow::anyhow!(- "Files may need manual recovery from: {display}\n\- Remove it to retry: rm -rf \"{display}\""- )- .context("Found leftover staging directory from an interrupted promote"));- }-- // Ensure both worktrees are clean- let main_working_tree = repo.worktree_at(main_path);- let target_working_tree = repo.worktree_at(target_path);-- main_working_tree.ensure_clean("promote", Some(&main_branch), false)?;- target_working_tree.ensure_clean("promote", Some(&target_branch), false)?;-- // Check if we're restoring canonical state (promoting default branch back to main worktree)- // Only lookup default_branch if needed for messaging (already resolved if no-arg from main)- let default_branch = repo.default_branch();- let is_restoring = default_branch.as_ref() == Some(&target_branch);-- if is_restoring {- // Restoring default branch to main worktree - no warning needed- eprintln!("{}", info_message("Restoring main worktree"));- } else {- // Creating mismatch - show warning and how to restore- eprintln!(- "{}",- warning_message("Promoting creates mismatched worktree state (shown as ⚑ in wt list)",)- );- // Only show restore hint if we know the default branch- if let Some(default) = &default_branch {- eprintln!(- "{}",- hint_message(cformat!(- "Run <underline>wt step promote {default}</> to restore canonical locations"- ))- );- }- }-- // Discover gitignored entries BEFORE branch exchange — .gitignore rules belong- // to the current branch and will change after `git switch`.- let worktree_paths: Vec<PathBuf> = worktrees.iter().map(|wt| wt.path.clone()).collect();- let no_excludes: &[String] = &[];- let main_entries =- list_and_filter_ignored_entries(main_path, &main_branch, &worktree_paths, no_excludes)?;- let target_entries =- list_and_filter_ignored_entries(target_path, &target_branch, &worktree_paths, no_excludes)?;-- // Move gitignored files to staging BEFORE branch exchange.- // `git switch` silently overwrites ignored files that collide with tracked- // files on the target branch — staging them first prevents data loss.- let staged = if !main_entries.is_empty() || !target_entries.is_empty() {- let (dir, count) = stage_ignored(- &repo,- main_path,- &main_entries,- target_path,- &target_entries,- )- .context(format!(- "Failed to stage ignored files. Already-staged files may be recoverable from: {}",- staging_path.to_slash_lossy()- ))?;- if count > 0 { Some((dir, count)) } else { None }- } else {- None- };-- // Exchange branches (detach both, then switch to swapped branches).- // Failure is near-impossible (both worktrees verified clean, branches exist).- // If it somehow fails, stale staging detection recovers on next run.- exchange_branches(- &main_working_tree,- &main_branch,- &target_working_tree,- &target_branch,- )?;-- // Distribute staged files to their new worktrees (after branch exchange)- let swapped = if let Some((ref staging_dir, _)) = staged {- distribute_staged(- staging_dir,- main_path,- &main_entries,- target_path,- &target_entries,- )- .context(format!(- "Failed to distribute staged files. Staged files may be recoverable from: {}",- staging_dir.display()- ))?- } else {- 0- };-- // Print success messages only after everything succeeded- eprintln!(- "{}",- success_message(cformat!(- "Promoted: main worktree now has <bold>{target_branch}</>; {} now has <bold>{main_branch}</>",- worktrunk::path::format_path_for_display(target_path)- ))- );- if swapped > 0 {- let path_word = if swapped == 1 { "path" } else { "paths" };- eprintln!(- "{}",- success_message(format!("Swapped {swapped} gitignored {path_word}"))- );- }-- Ok(PromoteResult::Promoted)-}--/// Remove worktrees and branches integrated into the default branch.-///-/// Handles four cases: live worktrees with branches (removed + branch deleted),-/// detached HEAD worktrees (directory removed, no branch to delete), stale worktree-/// entries (pruned + branch deleted), and orphan branches without worktrees (deleted).-/// Skips the main/primary worktree, locked worktrees, and worktrees younger than-/// `min_age`. Removes the current worktree last to trigger cd to primary.-pub fn step_prune(- dry_run: bool,- yes: bool,- min_age: &str,- foreground: bool,- format: crate::cli::SwitchFormat,-) -> anyhow::Result<()> {- let min_age_duration =- humantime::parse_duration(min_age).context("Invalid --min-age duration")?;-- let repo = Repository::current()?;- let config = UserConfig::load()?;-- // Capture once at command entry. Reused for every per-branch- // `integration_reason` probe later in this function.- let snapshot = repo.capture_refs().context("capturing repository refs")?;-- // Pass the local default branch (e.g. "main") directly — `integration_reason`- // ORs over local + upstream internally, so a branch merged into either side- // counts as integrated.- let integration_target = repo- .default_branch()- .context("cannot determine default branch")?;-- let worktrees = repo.list_worktrees().context("listing worktrees")?;- let current_root = repo- .current_worktree()- .root()- .context("resolving current worktree root")?- .to_path_buf();- let current_root = dunce::canonicalize(¤t_root).unwrap_or(current_root);- let now_secs = worktrunk::utils::epoch_now();-- let default_branch = repo.default_branch();-- // Gather candidates: integrated worktrees + integrated branch-only refs- struct Candidate {- /// Original index in check_items (for deterministic output ordering)- check_idx: usize,- /// Branch name (None for detached HEAD worktrees)- branch: Option<String>,- /// Display label: branch name or abbreviated commit SHA- label: String,- /// Worktree path (for Path-based removal of detached worktrees)- path: Option<PathBuf>,- /// Current worktree, other worktree, or branch-only (no worktree)- kind: CandidateKind,- }- enum CandidateKind {- Current,- Other,- BranchOnly,- }-- impl CandidateKind {- fn as_str(&self) -> &'static str {- match self {- CandidateKind::Current => "current",- CandidateKind::Other => "worktree",- CandidateKind::BranchOnly => "branch_only",- }- }- }-- /// Build a human-readable count like "3 worktrees & branches".- ///- /// Worktree + branch is the default pair (matching progress messages'- /// "worktree & branch" pattern). Unpaired items listed separately.- fn prune_summary(candidates: &[Candidate]) -> String {- let mut worktree_with_branch = 0usize;- let mut detached_worktree = 0usize;- let mut branch_only = 0usize;- for c in candidates {- match (&c.kind, &c.branch) {- (CandidateKind::BranchOnly, _) => branch_only += 1,- (CandidateKind::Current | CandidateKind::Other, Some(_)) => {- worktree_with_branch += 1;- }- (CandidateKind::Current | CandidateKind::Other, None) => {- detached_worktree += 1;- }- }- }- let mut parts = Vec::new();- if worktree_with_branch > 0 {- let noun = if worktree_with_branch == 1 {- "worktree & branch"- } else {- "worktrees & branches"- };- parts.push(format!("{worktree_with_branch} {noun}"));- }- if detached_worktree > 0 {- let noun = if detached_worktree == 1 {- "worktree"- } else {- "worktrees"- };- parts.push(format!("{detached_worktree} {noun}"));- }- if branch_only > 0 {- let noun = if branch_only == 1 {- "branch"- } else {- "branches"- };- parts.push(format!("{branch_only} {noun}"));- }- parts.join(", ")- }-- // For non-dry-run, approve hooks upfront so we can remove inline.- let run_hooks = if dry_run {- false // unused in dry-run path- } else {- let env = CommandEnv::for_action_branchless()?;- let ctx = env.context(yes);- approve_or_skip(- &ctx,- &[- HookType::PreRemove,- HookType::PostRemove,- HookType::PostSwitch,- ],- "Commands declined, continuing removal",- )?- };-- let mut removed: Vec<Candidate> = Vec::new();- let mut deferred_current: Option<Candidate> = None;- let mut skipped_young: Vec<String> = Vec::new();- // Track branches seen via worktree entries so we don't double-count- // in the orphan branch scan below.- let mut seen_branches: std::collections::HashSet<String> = std::collections::HashSet::new();-- /// Try to remove a candidate immediately. Returns Ok(true) if removed,- /// Ok(false) if skipped (preparation error), Err on execution error.- fn try_remove(- candidate: &Candidate,- repo: &Repository,- config: &UserConfig,- foreground: bool,- run_hooks: bool,- worktrees: &[WorktreeInfo],- snapshot: &worktrunk::git::RefSnapshot,- ) -> anyhow::Result<bool> {- let target = match candidate.kind {- CandidateKind::Current => RemoveTarget::Current,- CandidateKind::BranchOnly => RemoveTarget::Branch(- candidate- .branch- .as_ref()- .context("BranchOnly candidate missing branch")?,- ),- CandidateKind::Other => match &candidate.branch {- Some(branch) => RemoveTarget::Branch(branch),- None => RemoveTarget::Path(- candidate- .path- .as_ref()- .context("detached candidate missing path")?,- ),- },- };- let plan = match repo.prepare_worktree_removal(- target,- BranchDeletionMode::SafeDelete,- false,- config,- None,- Some(worktrees),- Some(snapshot),- ) {- Ok(plan) => plan,- 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);- }- };- let mut announcer = HookAnnouncer::new(repo, config, true);- handle_remove_output(&plan, foreground, run_hooks, true, &mut announcer)?;- announcer.flush()?;- Ok(true)- }-- enum CheckSource {- /// Worktree with directory gone (prunable)- Prunable { branch: String },- /// Linked worktree- Linked { wt_idx: usize },- /// Local branch without a worktree entry- Orphan,- }-- struct CheckItem {- integration_ref: String,- source: CheckSource,- }-- let mut check_items: Vec<CheckItem> = Vec::new();-- for (idx, wt) in worktrees.iter().enumerate() {- if let Some(branch) = &wt.branch {- seen_branches.insert(branch.clone());- }-- if wt.locked.is_some() {- continue;- }-- if let Some(branch) = &wt.branch- && default_branch.as_deref() == Some(branch.as_str())- {- continue;- }-- if wt.is_prunable() {- if let Some(branch) = &wt.branch {- check_items.push(CheckItem {- integration_ref: branch.clone(),- source: CheckSource::Prunable {- branch: branch.clone(),- },- });- }- continue;- }-- // Skip main worktree (non-linked); in bare repos all are linked,- // so the default-branch check above is the primary guard.- let wt_tree = repo.worktree_at(&wt.path);- if !wt_tree- .is_linked()- .context("checking whether worktree is linked")?- {- continue;- }-- let integration_ref = match &wt.branch {- Some(b) if !wt.detached => b.clone(),- _ => wt.head.clone(),- };-- check_items.push(CheckItem {- integration_ref,- source: CheckSource::Linked { wt_idx: idx },- });- }-- for branch in repo.all_branches().context("listing branches")? {- if seen_branches.contains(&branch) {- continue;- }- if default_branch.as_deref() == Some(branch.as_str()) {- continue;- }- check_items.push(CheckItem {- integration_ref: branch,- source: CheckSource::Orphan,- });- }-- // Parallel integration checks with inline removals.- //- // Spawn integration checks on a background thread via rayon par_iter,- // sending each result through a channel as it completes. The main thread- // processes results as they arrive: age-filtering, printing "Skipped"- // messages, and removing candidates immediately. This overlaps integration- // checking with removal — output appears as soon as the first check- // completes instead of waiting for all checks to finish.- let (tx, rx) = chan::unbounded();- let integration_refs: Vec<String> = check_items- .iter()- .map(|item| item.integration_ref.clone())- .collect();-- // Intentionally detached: if the main thread returns early (error in- // the recv loop), remaining rayon tasks silently fail to send on the- // closed channel and the thread cleans up on its own. Empty- // integration_refs produces an empty par_iter that completes immediately.- let repo_clone = repo.clone();- let target = integration_target.clone();- // Share by Arc — main thread keeps `snapshot_arc` for `try_remove`; the- // rayon worker takes a refcount-bump clone. No deep snapshot copy.- let snapshot_arc = std::sync::Arc::new(snapshot);- let snapshot_for_thread = std::sync::Arc::clone(&snapshot_arc);- std::thread::spawn(move || {- integration_refs- .into_par_iter()- .enumerate()- .for_each(|(idx, ref_name)| {- let result =- repo_clone.integration_reason(&snapshot_for_thread, &ref_name, &target);- let _ = tx.send((idx, result));- });- });-- // Collect integration context alongside candidates for dry-run display.- struct DryRunInfo {- reason_desc: String,- effective_target: String,- suffix: &'static str,- }- let mut dry_run_info: Vec<(Candidate, DryRunInfo)> = Vec::new();-- // Process results as they arrive from the channel.- for (idx, result) in rx {- let (effective_target, reason) = result.context("checking branch integration")?;- let Some(reason) = reason else {- continue;- };-- let item = &check_items[idx];-- // Linked worktrees need special handling: age check via filesystem- // metadata, current-worktree deferral, and path-based candidates.- if let CheckSource::Linked { wt_idx } = &item.source {- let wt = &worktrees[*wt_idx];- let label = wt.branch.clone().unwrap_or_else(|| {- let short = repo.short_sha(&wt.head).unwrap_or_else(|_| wt.head.clone());- format!("(detached {short})")- });-- // Skip recently-created worktrees that look "merged" because- // they were just created from the default branch- if min_age_duration > Duration::ZERO {- let wt_tree = repo.worktree_at(&wt.path);- let git_dir = wt_tree.git_dir().context("resolving worktree git dir")?;- let metadata = fs::metadata(&git_dir).context("Failed to read worktree git dir")?;- let created = metadata.created().or_else(|_| {- fs::metadata(git_dir.join("commondir")).and_then(|m| m.modified())- });- if let Ok(created) = created- && let Ok(created_epoch) = created.duration_since(std::time::UNIX_EPOCH)- {- let age = Duration::from_secs(now_secs.saturating_sub(created_epoch.as_secs()));- if age < min_age_duration {- if !dry_run {- eprintln!(- "{}",- info_message(format!("Skipped {label} (younger than {min_age})"))- );- }- skipped_young.push(label);- continue;- }- }- }-- let wt_path = dunce::canonicalize(&wt.path).unwrap_or(wt.path.clone());- let is_current = wt_path == current_root;- let candidate = Candidate {- check_idx: idx,- branch: if wt.detached { None } else { wt.branch.clone() },- label,- path: Some(wt.path.clone()),- kind: if is_current {- CandidateKind::Current- } else {- CandidateKind::Other- },- };- if dry_run {- let info = DryRunInfo {- reason_desc: reason.description().to_string(),- effective_target,- suffix: "",- };- dry_run_info.push((candidate, info));- } else if is_current {- deferred_current = Some(candidate);- } else if try_remove(- &candidate,- &repo,- &config,- foreground,- run_hooks,- worktrees,- &snapshot_arc,- )- .with_context(|| format!("removing worktree for {}", candidate.label))?- {- removed.push(candidate);- }- continue;- }-- // Branch-only candidates: prunable (stale worktree) and orphan branches- let (branch, suffix) = match &item.source {- CheckSource::Prunable { branch } => (branch, " (stale)"),- CheckSource::Orphan => (&item.integration_ref, " (branch only)"),- CheckSource::Linked { .. } => unreachable!(),- };-- // Age check for orphan branches via reflog creation timestamp- if matches!(&item.source, CheckSource::Orphan) && min_age_duration > Duration::ZERO {- let ref_name = format!("refs/heads/{branch}");- if let Ok(stdout) = repo.run_command(&["reflog", "show", "--format=%ct", &ref_name])- && let Some(created_epoch) = stdout- .trim()- .lines()- .last()- .and_then(|s| s.parse::<u64>().ok())- {- let age = Duration::from_secs(now_secs.saturating_sub(created_epoch));- if age < min_age_duration {- if !dry_run {- eprintln!(- "{}",- info_message(format!("Skipped {branch} (younger than {min_age})"))- );- }- skipped_young.push(branch.clone());- continue;- }- }- }-- let candidate = Candidate {- check_idx: idx,- label: branch.clone(),- branch: Some(branch.clone()),- path: None,- kind: CandidateKind::BranchOnly,- };- if dry_run {- let info = DryRunInfo {- reason_desc: reason.description().to_string(),- effective_target,- suffix,- };- dry_run_info.push((candidate, info));- } else if try_remove(- &candidate,- &repo,- &config,- foreground,- run_hooks,- worktrees,- &snapshot_arc,- )- .with_context(|| format!("removing worktree for {}", candidate.label))?- {- removed.push(candidate);- }- }-- if dry_run {- // Sort by original check order for deterministic output regardless of- // channel completion order.- dry_run_info.sort_by_key(|(c, _)| c.check_idx);-- if format == crate::cli::SwitchFormat::Json {- let items: Vec<serde_json::Value> = dry_run_info- .iter()- .map(|(c, info)| {- serde_json::json!({- "branch": c.branch,- "path": c.path,- "kind": c.kind.as_str(),- "reason": info.reason_desc,- "target": info.effective_target,- })- })- .collect();- println!("{}", serde_json::to_string_pretty(&items)?);- return Ok(());- }-- let mut dry_candidates = Vec::new();- for (candidate, info) in dry_run_info {- eprintln!(- "{}",- info_message(cformat!(- "<bold>{}</>{} — {} {}",- candidate.label,- info.suffix,- info.reason_desc,- info.effective_target- ))- );- dry_candidates.push(candidate);- }-- // Report skipped worktrees (after candidates, before summary).- // Sort for deterministic output regardless of channel completion order.- skipped_young.sort();- if !skipped_young.is_empty() {- let names = skipped_young.join(", ");- eprintln!(- "{}",- info_message(format!("Skipped {names} (younger than {min_age})"))- );- }-- if dry_candidates.is_empty() {- if skipped_young.is_empty() {- eprintln!("{}", info_message("No merged worktrees to remove"));- }- return Ok(());- }- eprintln!(- "{}",- hint_message(format!(- "{} would be removed (dry run)",- prune_summary(&dry_candidates)- ))- );- return Ok(());- }-- // Remove deferred current worktree last (cd-to-primary happens here)- if let Some(current) = deferred_current- && try_remove(- ¤t,- &repo,- &config,- foreground,- run_hooks,- worktrees,- &snapshot_arc,- )- .with_context(|| format!("removing worktree for {}", current.label))?- {- removed.push(current);- }-- if format == crate::cli::SwitchFormat::Json {- let items: Vec<serde_json::Value> = removed- .iter()- .map(|c| {- serde_json::json!({- "branch": c.branch,- "path": c.path,- "kind": c.kind.as_str(),- })- })- .collect();- println!("{}", serde_json::to_string_pretty(&items)?);- } else if removed.is_empty() {- if skipped_young.is_empty() {- eprintln!("{}", info_message("No merged worktrees to remove"));- }- } else {- eprintln!(- "{}",- success_message(format!("Pruned {}", prune_summary(&removed)))- );- }-- Ok(())-}--/// Move worktrees to their expected paths based on the `worktree-path` template.-///-/// See `src/commands/relocate.rs` for the implementation details and algorithm.-///-/// # Flags-///-/// | Flag | Purpose |-/// |------|---------|-/// | `--dry-run` | Show what would be moved without moving |-/// | `--commit` | Auto-commit dirty worktrees with LLM-generated messages before relocating |-/// | `--clobber` | Move non-worktree paths out of the way (`<path>.bak-<timestamp>`) |-/// | `[branches...]` | Specific branches to relocate (default: all mismatched) |-pub fn step_relocate(- branches: Vec<String>,- dry_run: bool,- commit: bool,- clobber: bool,- format: crate::cli::SwitchFormat,-) -> anyhow::Result<()> {- use super::relocate::{- GatherResult, RelocationExecutor, ValidationResult, gather_candidates, show_all_skipped,- show_dry_run_preview, show_no_relocations_needed, show_summary, validate_candidates,- };-- let json_mode = format == crate::cli::SwitchFormat::Json;-- let repo = Repository::current()?;- let config = UserConfig::load()?;- let default_branch = repo.default_branch().unwrap_or_default();-- // Validate default branch early - needed for main worktree relocation- if default_branch.is_empty() {- anyhow::bail!(- "Cannot determine default branch; set with: wt config state default-branch set main"- );- }- let repo_path = repo.repo_path()?.to_path_buf();-- // Phase 1: Gather candidates (worktrees not at expected paths)- let GatherResult {- candidates,- template_error_branches,- } = gather_candidates(&repo, &config, &branches)?;-- let template_skips: Vec<super::relocate::SkippedEntry> = template_error_branches- .iter()- .map(|b| super::relocate::SkippedEntry {- branch: b.clone(),- reason: "template_error",- })- .collect();-- if candidates.is_empty() {- if json_mode {- print_relocate_json(&[], &template_skips, dry_run)?;- } else {- show_no_relocations_needed(template_error_branches.len());- }- return Ok(());- }-- // Dry run: show preview and exit- if dry_run {- if json_mode {- let planned: Vec<_> = candidates- .iter()- .map(|c| RelocatedEntryView {- branch: c.branch().to_string(),- from: c.wt.path.clone(),- to: c.expected_path.clone(),- })- .collect();- print_relocate_json(&planned, &template_skips, true)?;- } else {- show_dry_run_preview(&candidates);- }- return Ok(());- }-- // Phase 2: Validate candidates (check locked/dirty, optionally auto-commit)- let ValidationResult {- validated,- skipped: validation_skipped,- } = validate_candidates(&repo, &config, candidates, commit, &repo_path)?;-- if validated.is_empty() {- if json_mode {- let mut all_skipped = template_skips;- all_skipped.extend(validation_skipped);- print_relocate_json(&[], &all_skipped, false)?;- } else {- show_all_skipped(validation_skipped.len());- }- return Ok(());- }-- // Phase 3 & 4: Create executor (classifies targets) and execute relocations- let mut executor = RelocationExecutor::new(&repo, validated, clobber)?;- let cwd = std::env::current_dir().ok();- executor.execute(&default_branch, cwd.as_deref())?;-- if json_mode {- let relocated_views: Vec<RelocatedEntryView> = executor- .relocated_entries- .iter()- .map(|e| RelocatedEntryView {- branch: e.branch.clone(),- from: e.from.clone(),- to: e.to.clone(),- })- .collect();- let mut all_skipped = template_skips;- all_skipped.extend(validation_skipped);- all_skipped.extend(executor.skipped_entries);- print_relocate_json(&relocated_views, &all_skipped, false)?;- } else {- let total_skipped = validation_skipped.len() + executor.skipped_count();- show_summary(executor.relocated_count(), total_skipped);- }-- Ok(())-}--/// Internal projection of a relocation event for JSON output.-struct RelocatedEntryView {- branch: String,- from: PathBuf,- to: PathBuf,-}--fn print_relocate_json(- entries: &[RelocatedEntryView],- skipped: &[super::relocate::SkippedEntry],- dry_run: bool,-) -> anyhow::Result<()> {- let payload = serde_json::json!({- "dry_run": dry_run,- "entries": entries.iter().map(|e| serde_json::json!({- "branch": e.branch,- "from": e.from,- "to": e.to,- })).collect::<Vec<_>>(),- "skipped": skipped.iter().map(|s| serde_json::json!({- "branch": s.branch,- "reason": s.reason,- })).collect::<Vec<_>>(),- });- println!("{}", serde_json::to_string_pretty(&payload)?);- Ok(())-}--#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn test_move_entry_file() {- let tmp = tempfile::tempdir().unwrap();- let src = tmp.path().join("source.txt");- let dest = tmp.path().join("subdir/dest.txt");-- fs::write(&src, "content").unwrap();- move_entry(&src, &dest, false).unwrap();-- assert!(!src.exists());- assert_eq!(fs::read_to_string(&dest).unwrap(), "content");- }-- #[test]- fn test_move_entry_directory() {- let tmp = tempfile::tempdir().unwrap();- let src = tmp.path().join("srcdir");- let dest = tmp.path().join("nested/destdir");-- fs::create_dir_all(src.join("inner")).unwrap();- fs::write(src.join("inner/file.txt"), "nested").unwrap();- fs::write(src.join("root.txt"), "root").unwrap();-- move_entry(&src, &dest, true).unwrap();-- assert!(!src.exists());- assert_eq!(- fs::read_to_string(dest.join("inner/file.txt")).unwrap(),- "nested"- );- assert_eq!(fs::read_to_string(dest.join("root.txt")).unwrap(), "root");- }-- #[test]- fn test_copy_and_remove_file() {- let tmp = tempfile::tempdir().unwrap();- let src = tmp.path().join("source.txt");- let dest = tmp.path().join("dest.txt");-- fs::write(&src, "content").unwrap();- copy_and_remove(&src, &dest, false).unwrap();-- assert!(!src.exists());- assert_eq!(fs::read_to_string(&dest).unwrap(), "content");- }-- #[test]- fn test_copy_and_remove_directory() {- let tmp = tempfile::tempdir().unwrap();- let src = tmp.path().join("srcdir");- let dest = tmp.path().join("destdir");-- fs::create_dir_all(src.join("sub")).unwrap();- fs::write(src.join("sub/file.txt"), "nested").unwrap();- fs::write(src.join("root.txt"), "root").unwrap();-- copy_and_remove(&src, &dest, true).unwrap();-- assert!(!src.exists());- assert_eq!(- fs::read_to_string(dest.join("sub/file.txt")).unwrap(),- "nested"- );- assert_eq!(fs::read_to_string(dest.join("root.txt")).unwrap(), "root");- }-}diff --git a/src/progress.rs b/src/progress.rsindex 71cce1dc7..627b932b4 100644--- a/src/progress.rs+++ b/src/progress.rs@@ -313,7 +313,7 @@ pub fn format_stats_paren(files: usize, bytes: u64) -> String {let word = if files == 1 { "file" } else { "files" };// Split the closing paren into a separate cformat so the optimizer doesn't// collapse the two color-print spans (matches the squash-progress pattern- // in commands/step_commands.rs).+ // in commands/step/squash.rs).let close = cformat!("<bright-black>)</>");cformat!(" <bright-black>({} {word} · {}</>{close}",diff --git a/tests/integration_tests/output_system_guard.rs b/tests/integration_tests/output_system_guard.rsindex ba9b1442f..5aae3f595 100644--- a/tests/integration_tests/output_system_guard.rs+++ b/tests/integration_tests/output_system_guard.rs@@ -42,8 +42,15 @@ const STDOUT_ALLOWED_PATHS: &[&str] = &["alias.rs",// Template evaluation output for scripting"eval.rs",- // LLM prompt output for wt step commit --show-prompt- "step_commands.rs",+ // LLM prompt output for wt step commit --show-prompt and squash --show-prompt+ "step/commit.rs",+ "step/squash.rs",+ // JSON output for wt step copy-ignored --format=json+ "step/copy_ignored.rs",+ // JSON output for wt step prune --format=json+ "step/prune.rs",+ // JSON output for wt step relocate --format=json+ "step/relocate.rs",// --no-cd flag: branch name output for scripting"picker/mod.rs",// JSON output for wt switch --format=jsondiff --git a/tests/integration_tests/step_copy_ignored.rs b/tests/integration_tests/step_copy_ignored.rsindex 3fc3906d4..1c6dd20f7 100644--- a/tests/integration_tests/step_copy_ignored.rs+++ b/tests/integration_tests/step_copy_ignored.rs@@ -1402,7 +1402,7 @@ fn test_copy_ignored_preserves_file_executable_permissions(mut repo: TestRepo) {fs::write(bin_dir.join("config.json"), r#"{"key": "value"}"#).unwrap();// Create a top-level ignored executable file (exercises the individual file copy- // path in step_commands.rs, separate from the recursive directory copy in copy.rs)+ // path in step/copy_ignored.rs, separate from the recursive directory copy in copy.rs)fs::write(repo.root_path().join("run-tests.sh"),"#!/bin/sh\necho running tests",@@ -1454,7 +1454,7 @@ fn test_copy_ignored_preserves_file_executable_permissions(mut repo: TestRepo) {);// Verify top-level executable file was copied with permissions preserved- // (exercises step_commands.rs individual file copy path)+ // (exercises step/copy_ignored.rs individual file copy path)let dest_script = feature_path.join("run-tests.sh");assert!(dest_script.exists(),