Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

Add `wt step relocate` command (#790)

Maximilian Roosc4b50bb6a8e4
diff --git a/.claude-plugin/skills/worktrunk/reference/step.md b/.claude-plugin/skills/worktrunk/reference/step.md
index 713c88e09..77cee4f40 100644
--- a/.claude-plugin/skills/worktrunk/reference/step.md
+++ b/.claude-plugin/skills/worktrunk/reference/step.md
@@ -44,6 +44,7 @@ Usage: <b><span class=c>wt step</span></b> <span class=c>[OPTIONS]</span> <span
<b><span class=c>rebase</span></b> Rebase onto target
<b><span class=c>copy-ignored</span></b> Copy gitignored files to another worktree
<b><span class=c>for-each</span></b> [experimental] Run command in each worktree
+ <b><span class=c>relocate</span></b> [experimental] Move worktrees to expected paths
<b><span class=g>Options:</span></b>
<b><span class=c>-h</span></b>, <b><span class=c>--help</span></b>
diff --git a/docs/content/step.md b/docs/content/step.md
index c413d2505..cc13eb6c8 100644
--- a/docs/content/step.md
+++ b/docs/content/step.md
@@ -58,6 +58,7 @@ Usage: <b><span class=c>wt step</span></b> <span class=c>[OPTIONS]</span> <span
<b><span class=c>rebase</span></b> Rebase onto target
<b><span class=c>copy-ignored</span></b> Copy gitignored files to another worktree
<b><span class=c>for-each</span></b> [experimental] Run command in each worktree
+ <b><span class=c>relocate</span></b> [experimental] Move worktrees to expected paths
<b><span class=g>Options:</span></b>
<b><span class=c>-h</span></b>, <b><span class=c>--help</span></b>
diff --git a/src/cli/step.rs b/src/cli/step.rs
index 7222d7c03..af2af513a 100644
--- a/src/cli/step.rs
+++ b/src/cli/step.rs
@@ -319,4 +319,77 @@ Note: This command is experimental and may change in future versions.
#[arg(required = true, last = true, num_args = 1..)]
args: Vec<String>,
},
+
+ /// \[experimental\] Move worktrees to expected paths
+ ///
+ /// Relocates worktrees whose path doesn't match the `worktree-path` template.
+ #[command(
+ after_long_help = r#"Moves worktrees to match the configured `worktree-path` template.
+
+## Examples
+
+Preview what would be moved:
+
+```console
+wt step relocate --dry-run
+```
+
+Move all mismatched worktrees:
+
+```console
+wt step relocate
+```
+
+Auto-commit and clobber blockers (never fails):
+
+```console
+wt step relocate --commit --clobber
+```
+
+Move specific worktrees:
+
+```console
+wt step relocate feature bugfix
+```
+
+## Swap handling
+
+When worktrees are at each other's expected locations (e.g., `alpha` at
+`repo.beta` and `beta` at `repo.alpha`), relocate automatically resolves
+this by using a temporary location.
+
+## Clobbering
+
+With `--clobber`, non-worktree paths at target locations are moved to
+`<path>.bak-<timestamp>` before relocating.
+
+## Skipped worktrees
+
+- **Dirty** (without `--commit`) — use `--commit` to auto-commit first
+- **Locked** — unlock with `git worktree unlock`
+- **Target blocked** (without `--clobber`) — use `--clobber` to backup blocker
+- **Detached HEAD** — no branch to compute expected path
+
+Note: This command is experimental and may change in future versions.
+"#
+ )]
+ Relocate {
+ /// Worktrees to relocate (defaults to all mismatched)
+ #[arg(add = crate::completion::worktree_only_completer())]
+ branches: Vec<String>,
+
+ /// Show what would be moved
+ #[arg(long)]
+ dry_run: bool,
+
+ /// Commit uncommitted changes before relocating
+ #[arg(long)]
+ commit: bool,
+
+ /// Backup non-worktree paths at target locations
+ ///
+ /// Moves blocking paths to `<path>.bak-<timestamp>`.
+ #[arg(long)]
+ clobber: bool,
+ },
}
diff --git a/src/commands/commit.rs b/src/commands/commit.rs
index 0d8646064..4c7028a9d 100644
--- a/src/commands/commit.rs
+++ b/src/commands/commit.rs
@@ -2,7 +2,6 @@ use anyhow::Context;
use color_print::cformat;
use worktrunk::HookType;
use worktrunk::config::CommitGenerationConfig;
-use worktrunk::git::Repository;
use worktrunk::styling::{
eprintln, format_with_gutter, hint_message, info_message, progress_message, success_message,
};
@@ -77,50 +76,58 @@ impl<'a> CommitGenerator<'a> {
}
}
+ /// Commit staged changes in the given worktree.
+ ///
+ /// When `show_progress` is true, displays a progress message with diff stats
+ /// before committing. Set to false for bulk operations where each worktree
+ /// is handled individually (e.g., `step relocate --commit`).
pub fn commit_staged_changes(
&self,
+ wt: &worktrunk::git::WorkingTree<'_>,
+ show_progress: bool,
show_no_squash_note: bool,
stage_mode: StageMode,
) -> anyhow::Result<()> {
- let repo = Repository::current()?;
- let wt = repo.current_worktree();
-
// Fail early if nothing is staged (avoids confusing LLM prompt with empty diff)
if !wt.has_staged_changes()? {
anyhow::bail!("Nothing to commit");
}
- let stats_parts = repo.diff_stats_summary(&["diff", "--staged", "--shortstat"]);
-
- let changes_type = match stage_mode {
- StageMode::Tracked => "tracked changes",
- _ => "changes",
- };
+ if show_progress {
+ let stats_parts = wt
+ .repo()
+ .diff_stats_summary(&["diff", "--staged", "--shortstat"]);
+
+ let changes_type = match stage_mode {
+ StageMode::Tracked => "tracked changes",
+ _ => "changes",
+ };
+
+ let action = if self.config.is_configured() {
+ format!("Generating commit message and committing {changes_type}...")
+ } else {
+ format!("Committing {changes_type} with default message...")
+ };
+
+ let mut parts = vec![];
+ if !stats_parts.is_empty() {
+ parts.extend(stats_parts);
+ }
+ if show_no_squash_note {
+ parts.push("no squashing needed".to_string());
+ }
- let action = if self.config.is_configured() {
- format!("Generating commit message and committing {changes_type}...")
- } else {
- format!("Committing {changes_type} with default message...")
- };
+ let full_progress_msg = if parts.is_empty() {
+ action
+ } else {
+ // Gray parenthetical with separate cformat for closing paren (avoids optimizer)
+ let parts_str = parts.join(", ");
+ let paren_close = cformat!("<bright-black>)</>");
+ cformat!("{action} <bright-black>({parts_str}</>{paren_close}")
+ };
- let mut parts = vec![];
- if !stats_parts.is_empty() {
- parts.extend(stats_parts);
+ eprintln!("{}", progress_message(full_progress_msg));
}
- if show_no_squash_note {
- parts.push("no squashing needed".to_string());
- }
-
- let full_progress_msg = if parts.is_empty() {
- action
- } else {
- // Gray parenthetical with separate cformat for closing paren (avoids optimizer)
- let parts_str = parts.join(", ");
- let paren_close = cformat!("<bright-black>)</>");
- cformat!("{action} <bright-black>({parts_str}</>{paren_close}")
- };
-
- eprintln!("{}", progress_message(full_progress_msg));
self.emit_hint_if_needed();
let commit_message = crate::llm::generate_commit_message(self.config)?;
@@ -128,10 +135,10 @@ impl<'a> CommitGenerator<'a> {
let formatted_message = self.format_message_for_display(&commit_message);
eprintln!("{}", format_with_gutter(&formatted_message, None));
- repo.run_command(&["commit", "-m", &commit_message])
+ wt.run_command(&["commit", "-m", &commit_message])
.context("Failed to commit")?;
- let commit_hash = repo
+ let commit_hash = wt
.run_command(&["rev-parse", "--short", "HEAD"])?
.trim()
.to_string();
@@ -214,8 +221,13 @@ impl CommitOptions<'_> {
}
let effective_config = self.ctx.commit_generation();
- CommitGenerator::new(&effective_config)
- .commit_staged_changes(self.show_no_squash_note, self.stage_mode)
+ let wt = self.ctx.repo.current_worktree();
+ CommitGenerator::new(&effective_config).commit_staged_changes(
+ &wt,
+ true, // show_progress
+ self.show_no_squash_note,
+ self.stage_mode,
+ )
}
}
diff --git a/src/commands/mod.rs b/src/commands/mod.rs
index a486333ff..190cdde43 100644
--- a/src/commands/mod.rs
+++ b/src/commands/mod.rs
@@ -14,6 +14,7 @@ pub(crate) mod list;
pub(crate) mod merge;
pub(crate) mod process;
pub(crate) mod project_config;
+mod relocate;
pub(crate) mod repository_ext;
#[cfg(unix)]
pub(crate) mod select;
@@ -38,7 +39,7 @@ pub(crate) use merge::{MergeOptions, execute_pre_remove_commands, handle_merge};
pub(crate) use select::handle_select;
pub(crate) use step_commands::{
RebaseResult, SquashResult, handle_rebase, handle_squash, step_commit, step_copy_ignored,
- step_show_squash_prompt,
+ step_relocate, step_show_squash_prompt,
};
pub(crate) use worktree::{
OperationMode, execute_switch, handle_remove, handle_remove_current,
diff --git a/src/commands/relocate.rs b/src/commands/relocate.rs
new file mode 100644
index 000000000..463ae3a2b
--- /dev/null
+++ b/src/commands/relocate.rs
@@ -0,0 +1,701 @@
+//! Worktree relocation logic for `wt step relocate`.
+//!
+//! This module implements the algorithm for moving worktrees to their expected
+//! paths based on the `worktree-path` template. It handles:
+//!
+//! - Simple relocations (target is empty)
+//! - Swap/cycle scenarios (worktrees occupy each other's targets)
+//! - Blocked targets (non-worktree paths, with optional `--clobber`)
+//! - Main worktree special handling (can't use `git worktree move`)
+//!
+//! The algorithm uses explicit types to represent each stage of the pipeline:
+//!
+//! ```text
+//! gather_candidates() → Vec<RelocationCandidate>
+//! ↓
+//! validate_candidates() → Vec<ValidatedCandidate>
+//! ↓
+//! RelocationExecutor::new() → executor with dependency graph
+//! ↓
+//! executor.execute() → performs moves in topological order
+//! ```
+
+use std::collections::{HashMap, HashSet};
+use std::path::{Path, PathBuf};
+
+use anyhow::Context;
+use color_print::cformat;
+use worktrunk::config::UserConfig;
+use worktrunk::git::{Repository, WorktreeInfo};
+use worktrunk::path::format_path_for_display;
+use worktrunk::shell_exec::Cmd;
+use worktrunk::styling::{
+ eprintln, format_with_gutter, hint_message, info_message, progress_message, success_message,
+ warning_message,
+};
+
+use super::commit::{CommitGenerator, StageMode};
+use super::worktree::{compute_worktree_path, paths_match};
+
+// ============================================================================
+// Types representing each stage of the pipeline
+// ============================================================================
+
+/// A worktree that needs relocation (current path != expected path).
+pub struct RelocationCandidate {
+ pub wt: WorktreeInfo,
+ pub expected_path: PathBuf,
+}
+
+impl RelocationCandidate {
+ /// The branch name (guaranteed to exist for relocation candidates).
+ pub fn branch(&self) -> &str {
+ self.wt.branch.as_deref().unwrap()
+ }
+}
+
+/// Result of gathering relocation candidates.
+pub struct GatherResult {
+ pub candidates: Vec<RelocationCandidate>,
+ pub template_errors: usize,
+}
+
+/// A candidate that passed pre-checks (not locked, not dirty or committed).
+pub struct ValidatedCandidate {
+ pub wt: WorktreeInfo,
+ pub expected_path: PathBuf,
+ pub is_main: bool,
+}
+
+impl ValidatedCandidate {
+ pub fn branch(&self) -> &str {
+ self.wt.branch.as_deref().unwrap()
+ }
+}
+
+/// Tracks a worktree temporarily moved to break a cycle.
+struct TempRelocation {
+ index: usize,
+ temp_path: PathBuf,
+ original_path: PathBuf,
+}
+
+/// Executes relocations in dependency order, handling cycles via temp moves.
+pub struct RelocationExecutor {
+ pending: Vec<ValidatedCandidate>,
+ /// Maps canonical current path → index in pending (for cycle detection)
+ current_locations: HashMap<PathBuf, usize>,
+ /// Indices blocked by external factors
+ blocked: HashSet<usize>,
+ /// Indices already moved (directly or to temp)
+ moved: HashSet<usize>,
+ /// Worktrees moved to temp location, awaiting final move
+ temp_relocated: Vec<TempRelocation>,
+ /// Temp directory for cycle breaking
+ temp_dir: PathBuf,
+ /// Counters for summary
+ pub skipped: usize,
+ pub relocated: usize,
+}
+
+// ============================================================================
+// Phase 1: Gather candidates
+// ============================================================================
+
+/// Find worktrees that are not at their expected paths.
+///
+/// Returns candidates for relocation plus a count of template errors encountered.
+pub fn gather_candidates(
+ repo: &Repository,
+ config: &UserConfig,
+ filter_branches: &[String],
+) -> anyhow::Result<GatherResult> {
+ // Get all worktrees, excluding prunable ones
+ let worktrees: Vec<_> = repo
+ .list_worktrees()?
+ .into_iter()
+ .filter(|wt| wt.prunable.is_none())
+ .collect();
+
+ // Filter to requested branches if any were specified
+ let worktrees: Vec<_> = if filter_branches.is_empty() {
+ worktrees
+ } else {
+ worktrees
+ .into_iter()
+ .filter(|wt| {
+ wt.branch
+ .as_ref()
+ .is_some_and(|b| filter_branches.iter().any(|arg| arg == b))
+ })
+ .collect()
+ };
+
+ // Find mismatched worktrees
+ let mut candidates = Vec::new();
+ let mut template_errors = 0;
+
+ for wt in worktrees {
+ let Some(branch) = wt.branch.as_deref() else {
+ continue; // Detached HEAD worktrees can't be relocated
+ };
+
+ match compute_worktree_path(repo, branch, config) {
+ Ok(expected) => {
+ // Check if paths differ (canonical comparison)
+ let actual_canonical = wt.path.canonicalize().unwrap_or_else(|_| wt.path.clone());
+ let expected_canonical =
+ expected.canonicalize().unwrap_or_else(|_| expected.clone());
+
+ if actual_canonical != expected_canonical {
+ candidates.push(RelocationCandidate {
+ wt,
+ expected_path: expected,
+ });
+ }
+ }
+ Err(e) => {
+ // Template expansion failed - warn user so they can fix config
+ let header = cformat!("Skipping <bold>{branch}</> due to template error:");
+ let detail = format_with_gutter(&e.to_string(), None);
+ eprintln!("{}\n{}", warning_message(header), detail);
+ template_errors += 1;
+ }
+ }
+ }
+
+ Ok(GatherResult {
+ candidates,
+ template_errors,
+ })
+}
+
+// ============================================================================
+// Phase 2: Validate candidates
+// ============================================================================
+
+/// Result of validating candidates.
+pub struct ValidationResult {
+ pub validated: Vec<ValidatedCandidate>,
+ pub skipped: usize,
+}
+
+/// Check each candidate for locked/dirty state and optionally auto-commit.
+///
+/// Returns validated candidates ready for relocation.
+pub fn validate_candidates(
+ repo: &Repository,
+ config: &UserConfig,
+ candidates: Vec<RelocationCandidate>,
+ auto_commit: bool,
+ repo_path: &Path,
+) -> anyhow::Result<ValidationResult> {
+ let mut validated = Vec::new();
+ let mut skipped = 0;
+
+ for candidate in candidates {
+ let branch = candidate.branch();
+
+ // Check locked - always skip (user must unlock manually)
+ if let Some(reason) = &candidate.wt.locked {
+ let reason_text = if reason.is_empty() {
+ String::new()
+ } else {
+ format!(": {reason}")
+ };
+ eprintln!(
+ "{}",
+ warning_message(cformat!("Skipping <bold>{branch}</> (locked{reason_text})"))
+ );
+ skipped += 1;
+ continue;
+ }
+
+ // Check dirty
+ let worktree = repo.worktree_at(&candidate.wt.path);
+ if worktree.is_dirty()? {
+ if auto_commit {
+ eprintln!(
+ "{}",
+ progress_message(cformat!("Committing changes in <bold>{branch}</>..."))
+ );
+ // Stage all changes
+ worktree
+ .run_command(&["add", "-A"])
+ .context("Failed to stage changes")?;
+ // Commit using shared pipeline
+ let project_id = repo.project_identifier().ok();
+ let commit_config = config.commit_generation(project_id.as_deref());
+ CommitGenerator::new(&commit_config).commit_staged_changes(
+ &worktree,
+ false, // show_progress - already showing "Committing changes in..."
+ false, // show_no_squash_note
+ StageMode::None, // already staged above
+ )?;
+ } else {
+ eprintln!(
+ "{}",
+ warning_message(cformat!("Skipping <bold>{branch}</> (uncommitted changes)"))
+ );
+ eprintln!(
+ "{}",
+ hint_message(cformat!(
+ "Use <bright-black>--commit</> to auto-commit changes before relocating"
+ ))
+ );
+ skipped += 1;
+ continue;
+ }
+ }
+
+ let is_main = paths_match(&candidate.wt.path, repo_path);
+ validated.push(ValidatedCandidate {
+ wt: candidate.wt,
+ expected_path: candidate.expected_path,
+ is_main,
+ });
+ }
+
+ Ok(ValidationResult { validated, skipped })
+}
+
+// ============================================================================
+// Phase 3 & 4: Execute relocations
+// ============================================================================
+
+impl RelocationExecutor {
+ /// Create executor and classify targets (handling blockers with optional clobber).
+ pub fn new(
+ repo: &Repository,
+ validated: Vec<ValidatedCandidate>,
+ clobber: bool,
+ ) -> anyhow::Result<Self> {
+ let temp_dir = repo.git_common_dir().join("wt-relocate-tmp");
+
+ // Build map of current locations for cycle detection
+ let mut current_locations: HashMap<PathBuf, usize> = HashMap::new();
+ for (i, candidate) in validated.iter().enumerate() {
+ let canonical = candidate
+ .wt
+ .path
+ .canonicalize()
+ .unwrap_or_else(|_| candidate.wt.path.clone());
+ current_locations.insert(canonical, i);
+ }
+
+ let mut blocked: HashSet<usize> = HashSet::new();
+ let mut skipped = 0;
+
+ // Classify targets and handle blockers
+ for (i, candidate) in validated.iter().enumerate() {
+ let expected_path = &candidate.expected_path;
+
+ if !expected_path.exists() {
+ continue; // Target is empty, no blocker
+ }
+
+ let canonical_target = expected_path
+ .canonicalize()
+ .unwrap_or_else(|_| expected_path.clone());
+
+ if current_locations.contains_key(&canonical_target) {
+ // Target is another worktree we're moving - handle via dependency graph
+ continue;
+ }
+
+ // Target exists but is NOT a worktree we're moving
+ let branch = candidate.branch();
+
+ // SAFETY: Never clobber an existing worktree - that would corrupt git metadata
+ if let Some((_, occupant_branch)) = repo.worktree_at_path(expected_path)? {
+ let occupant_name = occupant_branch.as_deref().unwrap_or("(detached)");
+ let msg = cformat!(
+ "Skipping <bold>{branch}</> (target is worktree for <bold>{occupant_name}</>)"
+ );
+ eprintln!("{}", warning_message(msg));
+ let hint = cformat!("Relocate or remove <bright-black>{occupant_name}</> first");
+ eprintln!("{}", hint_message(hint));
+ blocked.insert(i);
+ skipped += 1;
+ continue;
+ }
+
+ if clobber {
+ // Backup the blocker
+ let timestamp_secs = worktrunk::utils::get_now() as i64;
+ let datetime = chrono::DateTime::from_timestamp(timestamp_secs, 0)
+ .unwrap_or_else(chrono::Utc::now);
+ let suffix = datetime.format("%Y%m%d-%H%M%S");
+ let backup_path = expected_path.with_file_name(format!(
+ "{}.bak-{suffix}",
+ expected_path
+ .file_name()
+ .unwrap_or_default()
+ .to_string_lossy()
+ ));
+ let src = format_path_for_display(expected_path);
+ let dest = format_path_for_display(&backup_path);
+ eprintln!(
+ "{}",
+ progress_message(cformat!("Backing up {src} → {dest}"))
+ );
+ std::fs::rename(expected_path, &backup_path)
+ .with_context(|| format!("Failed to backup {}", expected_path.display()))?;
+ } else {
+ let blocked_path = format_path_for_display(expected_path);
+ let msg = cformat!("Skipping <bold>{branch}</> (target blocked: {blocked_path})");
+ eprintln!("{}", warning_message(msg));
+ eprintln!(
+ "{}",
+ hint_message(cformat!(
+ "Use <bright-black>--clobber</> to backup blocking paths"
+ ))
+ );
+ blocked.insert(i);
+ skipped += 1;
+ }
+ }
+
+ Ok(Self {
+ pending: validated,
+ current_locations,
+ blocked,
+ moved: HashSet::new(),
+ temp_relocated: Vec::new(),
+ temp_dir,
+ skipped,
+ relocated: 0,
+ })
+ }
+
+ /// Execute all relocations in dependency order.
+ pub fn execute(
+ &mut self,
+ repo_path: &Path,
+ default_branch: &str,
+ cwd: Option<&Path>,
+ ) -> anyhow::Result<()> {
+ // Process until all pending are moved or in temp
+ loop {
+ let mut made_progress = false;
+
+ // Find worktrees whose target is now empty
+ for i in 0..self.pending.len() {
+ if self.moved.contains(&i) || self.blocked.contains(&i) {
+ continue;
+ }
+
+ match self.is_target_empty(i) {
+ Some(true) => {
+ self.move_worktree(i, repo_path, default_branch, cwd)?;
+ made_progress = true;
+ }
+ Some(false) => {
+ // Target occupied by another pending worktree - wait for it to move
+ }
+ None => {
+ // Target unexpectedly blocked (TOCTOU race or same-target conflict)
+ let branch = self.pending[i].branch();
+ let blocked_path = format_path_for_display(&self.pending[i].expected_path);
+ let msg = cformat!(
+ "Skipping <bold>{branch}</> (target occupied: {blocked_path})"
+ );
+ eprintln!("{}", warning_message(msg));
+ self.blocked.insert(i);
+ self.skipped += 1;
+ }
+ }
+ }
+
+ if made_progress {
+ continue;
+ }
+
+ // No progress - break a cycle by moving one worktree to temp
+ if !self.break_cycle()? {
+ break; // All done
+ }
+ }
+
+ // Move temp-relocated worktrees to final destinations
+ self.finalize_temp_relocations()?;
+
+ // Clean up temp directory if empty
+ if self.temp_dir.exists() {
+ let _ = std::fs::remove_dir(&self.temp_dir);
+ }
+
+ Ok(())
+ }
+
+ /// Check if target path is empty (not occupied by a pending worktree).
+ ///
+ /// Returns:
+ /// - `Some(true)` if target doesn't exist or occupant has moved
+ /// - `Some(false)` if target is occupied by another pending worktree
+ /// - `None` if target is unexpectedly blocked (not in our tracking)
+ fn is_target_empty(&self, idx: usize) -> Option<bool> {
+ let expected = &self.pending[idx].expected_path;
+
+ if !expected.exists() {
+ return Some(true);
+ }
+
+ let canonical = expected.canonicalize().unwrap_or_else(|_| expected.clone());
+
+ // Check if it's a worktree we're tracking
+ self.current_locations
+ .get(&canonical)
+ .map(|occupant_idx| self.moved.contains(occupant_idx))
+ }
+
+ /// Move a single worktree to its expected path.
+ fn move_worktree(
+ &mut self,
+ idx: usize,
+ repo_path: &Path,
+ default_branch: &str,
+ cwd: Option<&Path>,
+ ) -> anyhow::Result<()> {
+ // Extract data we need before any mutable borrows
+ let branch = self.pending[idx].branch().to_string();
+ let is_main = self.pending[idx].is_main;
+ let src_path = self.pending[idx].wt.path.clone();
+ let dest_path = self.pending[idx].expected_path.clone();
+
+ let src_display = format_path_for_display(&src_path);
+ let dest_display = format_path_for_display(&dest_path);
+
+ if is_main {
+ self.move_main_worktree(idx, repo_path, default_branch)?;
+ } else {
+ Cmd::new("git")
+ .args(["worktree", "move"])
+ .arg(src_path.to_string_lossy())
+ .arg(dest_path.to_string_lossy())
+ .context(&branch)
+ .run()
+ .context("Failed to move worktree")?;
+ }
+
+ let msg = cformat!("Relocated <bold>{branch}</>: {src_display} → {dest_display}");
+ eprintln!("{}", success_message(msg));
+
+ // Update shell if user is inside this worktree
+ if let Some(cwd_path) = cwd
+ && cwd_path.starts_with(&src_path)
+ {
+ let relative = cwd_path.strip_prefix(&src_path).unwrap_or(Path::new(""));
+ crate::output::change_directory(dest_path.join(relative))?;
+ }
+
+ self.moved.insert(idx);
+ self.relocated += 1;
+ Ok(())
+ }
+
+ /// Main worktree can't use `git worktree move`; must create new + switch.
+ fn move_main_worktree(
+ &mut self,
+ idx: usize,
+ repo_path: &Path,
+ default_branch: &str,
+ ) -> anyhow::Result<()> {
+ let candidate = &self.pending[idx];
+ let branch = candidate.branch();
+
+ let msg = cformat!("Switching main worktree to <bold>{default_branch}</>...");
+ eprintln!("{}", progress_message(msg));
+
+ Cmd::new("git")
+ .args(["checkout", default_branch])
+ .current_dir(repo_path)
+ .context("main")
+ .run()
+ .context("Failed to checkout default branch")?;
+
+ // Try to create worktree; if it fails, rollback to original branch
+ let add_result = Cmd::new("git")
+ .args(["worktree", "add"])
+ .arg(candidate.expected_path.to_string_lossy())
+ .arg(branch)
+ .context(branch)
+ .run();
+
+ if let Err(e) = add_result {
+ // Rollback: checkout the original branch to restore user context
+ let rollback_msg = cformat!("Worktree creation failed, restoring <bold>{branch}</>...");
+ eprintln!("{}", warning_message(rollback_msg));
+
+ let _ = Cmd::new("git")
+ .args(["checkout", branch])
+ .current_dir(repo_path)
+ .context("main")
+ .run(); // Best-effort rollback
+
+ return Err(e).context("Failed to create worktree for main relocation");
+ }
+
+ Ok(())
+ }
+
+ /// Break a cycle by moving one worktree to a temp location.
+ ///
+ /// Returns `true` if a worktree was moved to temp, `false` if no cycles remain.
+ fn break_cycle(&mut self) -> anyhow::Result<bool> {
+ // Find a non-main worktree to temp-move (git worktree move can't move main)
+ let cycle_idx = (0..self.pending.len())
+ .filter(|&i| !self.moved.contains(&i) && !self.blocked.contains(&i))
+ .find(|&i| !self.pending[i].is_main);
+
+ // Fallback to any remaining (shouldn't happen in practice)
+ let cycle_idx = cycle_idx.or_else(|| {
+ (0..self.pending.len())
+ .find(|&i| !self.moved.contains(&i) && !self.blocked.contains(&i))
+ });
+
+ let Some(i) = cycle_idx else {
+ return Ok(false);
+ };
+
+ let candidate = &self.pending[i];
+ let branch = candidate.branch();
+
+ // Create temp directory if needed
+ std::fs::create_dir_all(&self.temp_dir)?;
+
+ // Sanitize branch name for temp path (feature/foo -> feature-foo)
+ let safe_branch = worktrunk::path::sanitize_for_filename(branch);
+ let temp_path = self.temp_dir.join(&safe_branch);
+
+ let msg = cformat!("Moving <bold>{branch}</> to temporary location...");
+ eprintln!("{}", progress_message(msg));
+
+ Cmd::new("git")
+ .args(["worktree", "move"])
+ .arg(candidate.wt.path.to_string_lossy())
+ .arg(temp_path.to_string_lossy())
+ .context(branch)
+ .run()
+ .context("Failed to move worktree to temp")?;
+
+ // Update current_locations to reflect the move
+ let old_canonical = candidate
+ .wt
+ .path
+ .canonicalize()
+ .unwrap_or_else(|_| candidate.wt.path.clone());
+ self.current_locations.remove(&old_canonical);
+
+ self.temp_relocated.push(TempRelocation {
+ index: i,
+ temp_path,
+ original_path: candidate.wt.path.clone(),
+ });
+ self.moved.insert(i);
+
+ Ok(true)
+ }
+
+ /// Move worktrees from temp locations to their final destinations.
+ fn finalize_temp_relocations(&mut self) -> anyhow::Result<()> {
+ for temp in std::mem::take(&mut self.temp_relocated) {
+ let candidate = &self.pending[temp.index];
+ let branch = candidate.branch();
+
+ let src_display = format_path_for_display(&temp.original_path);
+ let dest_display = format_path_for_display(&candidate.expected_path);
+
+ Cmd::new("git")
+ .args(["worktree", "move"])
+ .arg(temp.temp_path.to_string_lossy())
+ .arg(candidate.expected_path.to_string_lossy())
+ .context(branch)
+ .run()
+ .context("Failed to move worktree from temp to final location")?;
+
+ let msg = cformat!("Relocated <bold>{branch}</>: {src_display} → {dest_display}");
+ eprintln!("{}", success_message(msg));
+
+ self.relocated += 1;
+ }
+
+ Ok(())
+ }
+}
+
+// ============================================================================
+// Display helpers
+// ============================================================================
+
+/// Show dry-run preview of relocations.
+pub fn show_dry_run_preview(candidates: &[RelocationCandidate]) {
+ eprintln!(
+ "{}",
+ info_message(format!(
+ "{} worktree{} would be relocated:",
+ candidates.len(),
+ if candidates.len() == 1 { "" } else { "s" }
+ ))
+ );
+
+ let preview_lines: Vec<String> = candidates
+ .iter()
+ .map(|c| {
+ let branch = c.branch();
+ let src_display = format_path_for_display(&c.wt.path);
+ let dest_display = format_path_for_display(&c.expected_path);
+ cformat!("<bold>{branch}</>: {src_display} → {dest_display}")
+ })
+ .collect();
+ eprintln!("{}", format_with_gutter(&preview_lines.join("\n"), None));
+}
+
+/// Show summary of relocations performed.
+pub fn show_summary(relocated: usize, skipped: usize) {
+ if relocated > 0 || skipped > 0 {
+ eprintln!();
+ let plural = |n: usize| if n == 1 { "worktree" } else { "worktrees" };
+ if skipped == 0 {
+ let msg = format!("Relocated {relocated} {}", plural(relocated));
+ eprintln!("{}", success_message(msg));
+ } else {
+ let msg = format!(
+ "Relocated {relocated} {}, skipped {skipped} {}",
+ plural(relocated),
+ plural(skipped)
+ );
+ eprintln!("{}", info_message(msg));
+ }
+ }
+}
+
+/// Show message when no relocations are needed.
+pub fn show_no_relocations_needed(template_errors: usize) {
+ if template_errors == 0 {
+ eprintln!("{}", info_message("All worktrees are at expected paths"));
+ } else {
+ eprintln!(
+ "{}",
+ info_message(format!(
+ "No relocations performed; {} skipped due to template error{}",
+ template_errors,
+ if template_errors == 1 { "" } else { "s" }
+ ))
+ );
+ }
+}
+
+/// Show message when all candidates were skipped during validation.
+pub fn show_all_skipped(skipped: usize) {
+ if skipped > 0 {
+ eprintln!();
+ eprintln!(
+ "{}",
+ info_message(format!(
+ "Skipped {skipped} worktree{}",
+ if skipped == 1 { "" } else { "s" }
+ ))
+ );
+ }
+}
diff --git a/src/commands/step_commands.rs b/src/commands/step_commands.rs
index d8e67f445..bbad5b6f6 100644
--- a/src/commands/step_commands.rs
+++ b/src/commands/step_commands.rs
@@ -63,7 +63,7 @@ pub fn step_commit(
if !approved {
eprintln!(
"{}",
- worktrunk::styling::info_message("Commands declined, committing without hooks")
+ info_message("Commands declined, committing without hooks",)
);
true // Skip hooks
} else {
@@ -194,7 +194,7 @@ pub fn handle_squash(
if commit_count == 0 && has_staged {
// Just staged changes, no commits - commit them directly (no squashing needed)
- generator.commit_staged_changes(true, stage_mode)?;
+ generator.commit_staged_changes(&wt, true, true, stage_mode)?;
return Ok(SquashResult::Squashed);
}
@@ -733,6 +733,79 @@ fn copy_dir_recursive_fallback(src: &Path, dest: &Path) -> anyhow::Result<()> {
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,
+) -> 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 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_errors,
+ } = gather_candidates(&repo, &config, &branches)?;
+
+ if candidates.is_empty() {
+ show_no_relocations_needed(template_errors);
+ return Ok(());
+ }
+
+ // Dry run: show preview and exit
+ if dry_run {
+ show_dry_run_preview(&candidates);
+ return Ok(());
+ }
+
+ // Phase 2: Validate candidates (check locked/dirty, optionally auto-commit)
+ let ValidationResult { validated, skipped } =
+ validate_candidates(&repo, &config, candidates, commit, &repo_path)?;
+
+ if validated.is_empty() {
+ show_all_skipped(skipped);
+ 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(&repo_path, &default_branch, cwd.as_deref())?;
+
+ // Show summary
+ let total_skipped = skipped + executor.skipped;
+ show_summary(executor.relocated, total_skipped);
+
+ Ok(())
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/src/commands/worktree/mod.rs b/src/commands/worktree/mod.rs
index 1682bdeb0..bdd3848e9 100644
--- a/src/commands/worktree/mod.rs
+++ b/src/commands/worktree/mod.rs
@@ -88,8 +88,10 @@ mod types;
// Re-export public types and functions
pub use push::handle_push;
pub use remove::{handle_remove, handle_remove_current};
+pub(crate) use resolve::paths_match;
pub use resolve::{
- get_path_mismatch, is_worktree_at_expected_path, resolve_worktree_arg, worktree_display_name,
+ compute_worktree_path, get_path_mismatch, is_worktree_at_expected_path, resolve_worktree_arg,
+ worktree_display_name,
};
pub use switch::{execute_switch, plan_switch};
pub use types::{
diff --git a/src/commands/worktree/resolve.rs b/src/commands/worktree/resolve.rs
index 044d91ee2..788c52c99 100644
--- a/src/commands/worktree/resolve.rs
+++ b/src/commands/worktree/resolve.rs
@@ -180,7 +180,7 @@ fn canonicalize_with_parents(path: &Path) -> PathBuf {
/// Returns `true` if the paths resolve to the same location.
/// Handles the case where one path exists and the other doesn't by resolving
/// parent directory symlinks for non-existent paths.
-pub(super) fn paths_match(a: &std::path::Path, b: &std::path::Path) -> bool {
+pub(crate) fn paths_match(a: &std::path::Path, b: &std::path::Path) -> bool {
let a_canonical = canonicalize_with_parents(a);
let b_canonical = canonicalize_with_parents(b);
a_canonical == b_canonical
diff --git a/src/git/repository/working_tree.rs b/src/git/repository/working_tree.rs
index 1f7df4f30..113a4b927 100644
--- a/src/git/repository/working_tree.rs
+++ b/src/git/repository/working_tree.rs
@@ -52,6 +52,11 @@ pub struct WorkingTree<'a> {
}
impl<'a> WorkingTree<'a> {
+ /// Get a reference to the repository this worktree belongs to.
+ pub fn repo(&self) -> &Repository {
+ self.repo
+ }
+
/// Run a git command in this worktree and return stdout.
pub fn run_command(&self, args: &[&str]) -> anyhow::Result<String> {
let output = self.run_command_output(args)?;
diff --git a/src/main.rs b/src/main.rs
index 26a9cbfcb..45824bfaf 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -53,7 +53,7 @@ use commands::{
handle_remove_current, handle_show_theme, handle_squash, handle_state_clear,
handle_state_clear_all, handle_state_get, handle_state_set, handle_state_show,
handle_unconfigure_shell, plan_switch, resolve_worktree_arg, run_hook, step_commit,
- step_copy_ignored, step_for_each,
+ step_copy_ignored, step_for_each, step_relocate,
};
use output::{execute_user_command, handle_remove_output, handle_switch_output};
@@ -574,6 +574,12 @@ fn main() {
step_copy_ignored(from.as_deref(), to.as_deref(), dry_run)
}
StepCommand::ForEach { args } => step_for_each(args),
+ StepCommand::Relocate {
+ branches,
+ dry_run,
+ commit,
+ clobber,
+ } => step_relocate(branches, dry_run, commit, clobber),
},
Commands::Hook { action } => match action {
HookCommand::Show {
diff --git a/tests/integration_tests/completion.rs b/tests/integration_tests/completion.rs
index d79acd00f..58a8aa59b 100644
--- a/tests/integration_tests/completion.rs
+++ b/tests/integration_tests/completion.rs
@@ -592,10 +592,11 @@ fn test_complete_step_subcommands(repo: TestRepo) {
"Missing copy-ignored"
);
assert!(subcommands.contains(&"for-each"), "Missing for-each");
+ assert!(subcommands.contains(&"relocate"), "Missing relocate");
assert_eq!(
subcommands.len(),
- 6,
- "Should have exactly 6 step subcommands"
+ 7,
+ "Should have exactly 7 step subcommands"
);
}
diff --git a/tests/integration_tests/mod.rs b/tests/integration_tests/mod.rs
index bb7bcf0ca..b6c44bb1d 100644
--- a/tests/integration_tests/mod.rs
+++ b/tests/integration_tests/mod.rs
@@ -53,5 +53,6 @@ pub mod shell_wrapper;
pub mod spacing_edge_cases;
pub mod statusline;
pub mod step_copy_ignored;
+pub mod step_relocate;
pub mod switch;
pub mod user_hooks;
diff --git a/tests/integration_tests/step_relocate.rs b/tests/integration_tests/step_relocate.rs
new file mode 100644
index 000000000..e45b09a13
--- /dev/null
+++ b/tests/integration_tests/step_relocate.rs
@@ -0,0 +1,627 @@
+//! Integration tests for `wt step relocate`
+
+use crate::common::{TestRepo, make_snapshot_cmd, repo};
+use insta_cmd::assert_cmd_snapshot;
+use rstest::rstest;
+use std::fs;
+
+/// Get the parent directory of the repo (where worktrees are created)
+fn worktree_parent(repo: &TestRepo) -> std::path::PathBuf {
+ repo.root_path().parent().unwrap().to_path_buf()
+}
+
+/// Test with no mismatched worktrees
+#[rstest]
+fn test_relocate_no_mismatches(mut repo: TestRepo) {
+ // Create a worktree at the expected location
+ repo.add_worktree("feature");
+
+ // All worktrees should be at expected paths
+ assert_cmd_snapshot!(make_snapshot_cmd(&repo, "step", &["relocate"], None));
+}
+
+/// Test relocating a single mismatched worktree
+#[rstest]
+fn test_relocate_single_mismatch(repo: TestRepo) {
+ let parent = worktree_parent(&repo);
+
+ // Create a worktree manually at a non-standard location
+ let wrong_path = parent.join("wrong-location");
+ repo.run_git(&[
+ "worktree",
+ "add",
+ "-b",
+ "feature",
+ wrong_path.to_str().unwrap(),
+ ]);
+
+ // Relocate should move it to the expected path
+ assert_cmd_snapshot!(make_snapshot_cmd(&repo, "step", &["relocate"], None));
+
+ // Verify the worktree was moved to expected location
+ let expected_path = parent.join("repo.feature");
+ assert!(
+ expected_path.exists(),
+ "Worktree should be at expected path: {}",
+ expected_path.display()
+ );
+ assert!(
+ !wrong_path.exists(),
+ "Old worktree path should no longer exist: {}",
+ wrong_path.display()
+ );
+}
+
+/// Test dry run shows what would be moved
+#[rstest]
+fn test_relocate_dry_run(repo: TestRepo) {
+ let parent = worktree_parent(&repo);
+
+ // Create a worktree at a non-standard location
+ let wrong_path = parent.join("wrong-location");
+ repo.run_git(&[
+ "worktree",
+ "add",
+ "-b",
+ "feature",
+ wrong_path.to_str().unwrap(),
+ ]);
+
+ // Dry run should show what would be moved without actually moving
+ assert_cmd_snapshot!(make_snapshot_cmd(
+ &repo,
+ "step",
+ &["relocate", "--dry-run"],
+ None
+ ));
+
+ // Verify the worktree was NOT moved
+ assert!(
+ wrong_path.exists(),
+ "Worktree should still be at wrong path in dry run: {}",
+ wrong_path.display()
+ );
+}
+
+/// Test that locked worktrees are skipped
+#[rstest]
+fn test_relocate_locked_worktree(repo: TestRepo) {
+ let parent = worktree_parent(&repo);
+
+ // Create a worktree at a non-standard location and lock it
+ let wrong_path = parent.join("wrong-location");
+ repo.run_git(&[
+ "worktree",
+ "add",
+ "-b",
+ "feature",
+ wrong_path.to_str().unwrap(),
+ ]);
+ repo.run_git(&["worktree", "lock", wrong_path.to_str().unwrap()]);
+
+ // Relocate should skip locked worktree
+ assert_cmd_snapshot!(make_snapshot_cmd(&repo, "step", &["relocate"], None));
+
+ // Verify the worktree was NOT moved
+ assert!(
+ wrong_path.exists(),
+ "Locked worktree should not be moved: {}",
+ wrong_path.display()
+ );
+}
+
+/// Test mixed success and skip (covers "Relocated X, skipped Y" output)
+#[rstest]
+fn test_relocate_mixed_success_and_skip(repo: TestRepo) {
+ let parent = worktree_parent(&repo);
+
+ // Create one worktree that can be moved
+ let wrong_path1 = parent.join("wrong-location-1");
+ repo.run_git(&[
+ "worktree",
+ "add",
+ "-b",
+ "feature1",
+ wrong_path1.to_str().unwrap(),
+ ]);
+
+ // Create another worktree that is locked (will be skipped)
+ let wrong_path2 = parent.join("wrong-location-2");
+ repo.run_git(&[
+ "worktree",
+ "add",
+ "-b",
+ "feature2",
+ wrong_path2.to_str().unwrap(),
+ ]);
+ repo.run_git(&["worktree", "lock", wrong_path2.to_str().unwrap()]);
+
+ // Relocate should move feature1 and skip feature2
+ assert_cmd_snapshot!(make_snapshot_cmd(&repo, "step", &["relocate"], None));
+
+ // Verify feature1 was moved
+ let expected_path1 = parent.join("repo.feature1");
+ assert!(
+ expected_path1.exists(),
+ "feature1 should be at expected path: {}",
+ expected_path1.display()
+ );
+
+ // Verify feature2 was NOT moved (locked)
+ assert!(
+ wrong_path2.exists(),
+ "Locked feature2 should not be moved: {}",
+ wrong_path2.display()
+ );
+}
+
+/// Test that existing target path causes skip
+#[rstest]
+fn test_relocate_target_exists(repo: TestRepo) {
+ let parent = worktree_parent(&repo);
+
+ // Create a worktree at a non-standard location
+ let wrong_path = parent.join("wrong-location");
+ repo.run_git(&[
+ "worktree",
+ "add",
+ "-b",
+ "feature",
+ wrong_path.to_str().unwrap(),
+ ]);
+
+ // Create a directory at the expected location
+ let expected_path = parent.join("repo.feature");
+ fs::create_dir_all(&expected_path).unwrap();
+ fs::write(expected_path.join("existing-file.txt"), "existing").unwrap();
+
+ // Relocate should skip because target exists
+ assert_cmd_snapshot!(make_snapshot_cmd(&repo, "step", &["relocate"], None));
+
+ // Verify the worktree was NOT moved
+ assert!(
+ wrong_path.exists(),
+ "Worktree should not be moved when target exists: {}",
+ wrong_path.display()
+ );
+}
+
+/// Test that dirty worktrees are skipped without --commit
+#[rstest]
+fn test_relocate_dirty_without_commit(repo: TestRepo) {
+ let parent = worktree_parent(&repo);
+
+ // Create a worktree at a non-standard location
+ let wrong_path = parent.join("wrong-location");
+ repo.run_git(&[
+ "worktree",
+ "add",
+ "-b",
+ "feature",
+ wrong_path.to_str().unwrap(),
+ ]);
+
+ // Make uncommitted changes
+ fs::write(wrong_path.join("dirty.txt"), "uncommitted changes").unwrap();
+
+ // Relocate should skip dirty worktree
+ assert_cmd_snapshot!(make_snapshot_cmd(&repo, "step", &["relocate"], None));
+
+ // Verify the worktree was NOT moved
+ assert!(
+ wrong_path.exists(),
+ "Dirty worktree should not be moved: {}",
+ wrong_path.display()
+ );
+}
+
+/// Test that --commit auto-commits dirty worktrees before relocating
+#[rstest]
+fn test_relocate_dirty_with_commit(repo: TestRepo) {
+ let parent = worktree_parent(&repo);
+
+ // Create a worktree at a non-standard location
+ let wrong_path = parent.join("wrong-location");
+ repo.run_git(&[
+ "worktree",
+ "add",
+ "-b",
+ "feature",
+ wrong_path.to_str().unwrap(),
+ ]);
+
+ // Make uncommitted changes
+ fs::write(wrong_path.join("dirty.txt"), "uncommitted changes").unwrap();
+
+ // Configure mock LLM command via config file
+ let worktrunk_config = r#"
+[commit.generation]
+command = "cat >/dev/null && echo 'chore: auto-commit before relocate'"
+"#;
+ fs::write(repo.test_config_path(), worktrunk_config).unwrap();
+
+ // Relocate with --commit should commit then move
+ assert_cmd_snapshot!(make_snapshot_cmd(
+ &repo,
+ "step",
+ &["relocate", "--commit"],
+ None
+ ));
+
+ // Verify the worktree was moved to expected location
+ let expected_path = parent.join("repo.feature");
+ assert!(
+ expected_path.exists(),
+ "Worktree should be at expected path after commit: {}",
+ expected_path.display()
+ );
+ assert!(
+ !wrong_path.exists(),
+ "Old worktree path should no longer exist: {}",
+ wrong_path.display()
+ );
+}
+
+/// Test that --clobber backs up non-worktree paths at target locations
+#[rstest]
+fn test_relocate_clobber_backs_up(repo: TestRepo) {
+ let parent = worktree_parent(&repo);
+
+ // Create a worktree at a non-standard location
+ let wrong_path = parent.join("wrong-location");
+ repo.run_git(&[
+ "worktree",
+ "add",
+ "-b",
+ "feature",
+ wrong_path.to_str().unwrap(),
+ ]);
+
+ // Create a directory at the expected location (non-worktree blocker)
+ let expected_path = parent.join("repo.feature");
+ fs::create_dir_all(&expected_path).unwrap();
+ fs::write(expected_path.join("existing-file.txt"), "existing content").unwrap();
+
+ // Relocate with --clobber should backup and move
+ assert_cmd_snapshot!(make_snapshot_cmd(
+ &repo,
+ "step",
+ &["relocate", "--clobber"],
+ None
+ ));
+
+ // Verify the worktree was moved
+ assert!(
+ expected_path.exists(),
+ "Worktree should be at expected location: {}",
+ expected_path.display()
+ );
+ assert!(
+ !wrong_path.exists(),
+ "Original path should no longer exist: {}",
+ wrong_path.display()
+ );
+
+ // Verify backup exists (with timestamp suffix)
+ let backup_exists = fs::read_dir(&parent)
+ .unwrap()
+ .filter_map(|e| e.ok())
+ .any(|e| {
+ let name = e.file_name().to_string_lossy().to_string();
+ name.starts_with("repo.feature.bak-")
+ });
+ assert!(backup_exists, "Backup directory should exist");
+}
+
+/// Test that --clobber refuses to clobber an existing worktree
+#[rstest]
+fn test_relocate_clobber_refuses_worktree(repo: TestRepo) {
+ let parent = worktree_parent(&repo);
+
+ // Create worktree alpha at a non-standard location
+ let wrong_path = parent.join("wrong-location");
+ repo.run_git(&[
+ "worktree",
+ "add",
+ "-b",
+ "alpha",
+ wrong_path.to_str().unwrap(),
+ ]);
+
+ // Create another worktree beta at alpha's expected location
+ let expected_path = parent.join("repo.alpha");
+ repo.run_git(&[
+ "worktree",
+ "add",
+ "-b",
+ "beta",
+ expected_path.to_str().unwrap(),
+ ]);
+
+ // Relocate with --clobber should still skip (can't clobber a worktree)
+ assert_cmd_snapshot!(make_snapshot_cmd(
+ &repo,
+ "step",
+ &["relocate", "--clobber", "alpha"],
+ None
+ ));
+
+ // Verify alpha was NOT moved (beta still occupies the target)
+ assert!(
+ wrong_path.exists(),
+ "alpha should still be at wrong location: {}",
+ wrong_path.display()
+ );
+}
+
+/// Test relocating specific worktrees by branch name
+#[rstest]
+fn test_relocate_specific_branch(repo: TestRepo) {
+ let parent = worktree_parent(&repo);
+
+ // Create two worktrees at non-standard locations
+ let wrong_path1 = parent.join("wrong-location-1");
+ let wrong_path2 = parent.join("wrong-location-2");
+ repo.run_git(&[
+ "worktree",
+ "add",
+ "-b",
+ "feature1",
+ wrong_path1.to_str().unwrap(),
+ ]);
+ repo.run_git(&[
+ "worktree",
+ "add",
+ "-b",
+ "feature2",
+ wrong_path2.to_str().unwrap(),
+ ]);
+
+ // Relocate only feature1
+ assert_cmd_snapshot!(make_snapshot_cmd(
+ &repo,
+ "step",
+ &["relocate", "feature1"],
+ None
+ ));
+
+ // Verify only feature1 was moved
+ let expected_path1 = parent.join("repo.feature1");
+ assert!(
+ expected_path1.exists(),
+ "feature1 should be at expected path: {}",
+ expected_path1.display()
+ );
+ assert!(
+ wrong_path2.exists(),
+ "feature2 should still be at wrong path: {}",
+ wrong_path2.display()
+ );
+}
+
+/// Test relocating main worktree with non-default branch (create + switch)
+#[rstest]
+fn test_relocate_main_worktree(repo: TestRepo) {
+ let parent = worktree_parent(&repo);
+
+ // Switch main worktree to a feature branch
+ repo.run_git(&["checkout", "-b", "feature"]);
+
+ // Relocate should create worktree for feature and switch main to default branch
+ assert_cmd_snapshot!(make_snapshot_cmd(&repo, "step", &["relocate"], None));
+
+ // Verify new worktree was created
+ let expected_path = parent.join("repo.feature");
+ assert!(
+ expected_path.exists(),
+ "Feature worktree should be created at: {}",
+ expected_path.display()
+ );
+
+ // Verify main worktree is now on default branch
+ let output = repo
+ .git_command()
+ .args(["branch", "--show-current"])
+ .output()
+ .unwrap();
+ let current_branch = String::from_utf8_lossy(&output.stdout);
+ assert_eq!(
+ current_branch.trim(),
+ "main",
+ "Main worktree should be on default branch"
+ );
+}
+
+/// Test swap scenario: two worktrees at each other's expected locations
+///
+/// When alpha is at repo.beta and beta is at repo.alpha, relocate
+/// automatically handles the swap via a temporary location.
+#[rstest]
+fn test_relocate_swap(repo: TestRepo) {
+ let parent = worktree_parent(&repo);
+
+ // Create worktrees at each other's expected locations
+ // alpha at repo.beta (where beta should go)
+ // beta at repo.alpha (where alpha should go)
+ let path_for_beta = parent.join("repo.beta");
+ let path_for_alpha = parent.join("repo.alpha");
+
+ repo.run_git(&[
+ "worktree",
+ "add",
+ "-b",
+ "alpha",
+ path_for_beta.to_str().unwrap(), // alpha at beta's expected location
+ ]);
+ repo.run_git(&[
+ "worktree",
+ "add",
+ "-b",
+ "beta",
+ path_for_alpha.to_str().unwrap(), // beta at alpha's expected location
+ ]);
+
+ // Relocate resolves the swap via temp location
+ assert_cmd_snapshot!(make_snapshot_cmd(&repo, "step", &["relocate"], None));
+
+ // Verify both are now at their expected locations
+ assert!(path_for_alpha.exists(), "alpha should be at repo.alpha");
+ assert!(path_for_beta.exists(), "beta should be at repo.beta");
+}
+
+/// Test relocating multiple worktrees shows compact output
+#[rstest]
+fn test_relocate_multiple(repo: TestRepo) {
+ let parent = worktree_parent(&repo);
+
+ // Create 5 worktrees at non-standard locations
+ for i in 1..=5 {
+ let wrong_path = parent.join(format!("wrong-{i}"));
+ repo.run_git(&[
+ "worktree",
+ "add",
+ "-b",
+ &format!("feature-{i}"),
+ wrong_path.to_str().unwrap(),
+ ]);
+ }
+
+ // Relocate all
+ assert_cmd_snapshot!(make_snapshot_cmd(&repo, "step", &["relocate"], None));
+
+ // Verify all were moved
+ for i in 1..=5 {
+ let expected_path = parent.join(format!("repo.feature-{i}"));
+ assert!(
+ expected_path.exists(),
+ "feature-{i} should be at expected path: {}",
+ expected_path.display()
+ );
+ }
+}
+
+/// Test that two worktrees targeting the same path doesn't panic
+///
+/// Before the fix, this would panic with "existing target must be a tracked worktree"
+/// because after the first worktree moved, the second would find an occupied target
+/// that wasn't in the tracking map.
+#[rstest]
+fn test_relocate_same_target_no_panic(repo: TestRepo) {
+ let parent = worktree_parent(&repo);
+
+ // Create two worktrees at non-standard locations
+ let wrong_path1 = parent.join("wrong-location-1");
+ let wrong_path2 = parent.join("wrong-location-2");
+ repo.run_git(&[
+ "worktree",
+ "add",
+ "-b",
+ "alpha",
+ wrong_path1.to_str().unwrap(),
+ ]);
+ repo.run_git(&[
+ "worktree",
+ "add",
+ "-b",
+ "beta",
+ wrong_path2.to_str().unwrap(),
+ ]);
+
+ // Configure a template that maps BOTH branches to the same path
+ // This creates the "same target" scenario
+ let worktrunk_config = r#"
+worktree-path = "{{ repo }}.shared"
+"#;
+ fs::write(repo.test_config_path(), worktrunk_config).unwrap();
+
+ // Relocate only alpha and beta (exclude any other branches from prior tests)
+ // Previously this would panic
+ assert_cmd_snapshot!(make_snapshot_cmd(
+ &repo,
+ "step",
+ &["relocate", "alpha", "beta"],
+ None
+ ));
+
+ // Verify first worktree moved to shared location
+ // Note: {{ repo }} in template uses repo NAME, so path is inside repo root
+ let shared_path = repo.root_path().join("repo.shared");
+ assert!(
+ shared_path.exists(),
+ "First worktree should be at shared path: {}",
+ shared_path.display()
+ );
+
+ // Second worktree should still be at its original location (skipped)
+ // It was skipped because the target was occupied after first moved there
+ assert!(
+ wrong_path1.exists() || wrong_path2.exists(),
+ "One worktree should remain at original location (skipped)"
+ );
+}
+
+/// Test that template expansion errors are reported gracefully
+#[rstest]
+fn test_relocate_template_error(repo: TestRepo) {
+ let parent = worktree_parent(&repo);
+
+ // Create a worktree at a non-standard location
+ let wrong_path = parent.join("wrong-location");
+ repo.run_git(&[
+ "worktree",
+ "add",
+ "-b",
+ "feature",
+ wrong_path.to_str().unwrap(),
+ ]);
+
+ // Configure an invalid template with a non-existent variable
+ let worktrunk_config = r#"
+worktree-path = "{{ nonexistent_variable }}"
+"#;
+ fs::write(repo.test_config_path(), worktrunk_config).unwrap();
+
+ // Relocate should warn about template error and skip
+ // Filter to just "feature" to avoid noise from other worktrees
+ assert_cmd_snapshot!(make_snapshot_cmd(
+ &repo,
+ "step",
+ &["relocate", "feature"],
+ None
+ ));
+
+ // Verify the worktree was NOT moved (skipped due to template error)
+ assert!(
+ wrong_path.exists(),
+ "Worktree should not be moved when template fails: {}",
+ wrong_path.display()
+ );
+}
+
+/// Test that empty default branch is detected early with actionable error
+#[rstest]
+fn test_relocate_empty_default_branch(repo: TestRepo) {
+ let parent = worktree_parent(&repo);
+
+ // Create a worktree at a non-standard location
+ let wrong_path = parent.join("wrong-location");
+ repo.run_git(&[
+ "worktree",
+ "add",
+ "-b",
+ "feature",
+ wrong_path.to_str().unwrap(),
+ ]);
+
+ // Set worktrunk.default-branch to a non-existent branch.
+ // The detection logic validates that configured branches exist locally,
+ // and returns None if they don't. This triggers the empty default branch error.
+ repo.run_git(&[
+ "config",
+ "worktrunk.default-branch",
+ "nonexistent-branch-xyz",
+ ]);
+
+ // Relocate should fail early with helpful error
+ assert_cmd_snapshot!(make_snapshot_cmd(&repo, "step", &["relocate"], None));
+}
diff --git a/tests/snapshots/integration__integration_tests__help__help_step_long.snap b/tests/snapshots/integration__integration_tests__help__help_step_long.snap
index 81e0cfd71..976029563 100644
--- a/tests/snapshots/integration__integration_tests__help__help_step_long.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_step_long.snap
@@ -9,6 +9,8 @@ info:
CLICOLOR_FORCE: "1"
COLUMNS: "500"
GIT_EDITOR: ""
+ LANG: C
+ LC_ALL: C
RUST_LOG: warn
SHELL: ""
TERM: alacritty
@@ -35,6 +37,7 @@ Usage: wt step [OPTIONS] <COMMAND>
rebase Rebase onto target
copy-ignored Copy gitignored files to another worktree
for-each [experimental] Run command in each worktree
+ relocate [experimental] Move worktrees to expected paths
Options:
-h, --help
diff --git a/tests/snapshots/integration__integration_tests__help__help_step_short.snap b/tests/snapshots/integration__integration_tests__help__help_step_short.snap
index 295986224..51ac94798 100644
--- a/tests/snapshots/integration__integration_tests__help__help_step_short.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_step_short.snap
@@ -9,6 +9,8 @@ info:
CLICOLOR_FORCE: "1"
COLUMNS: "500"
GIT_EDITOR: ""
+ LANG: C
+ LC_ALL: C
RUST_LOG: warn
SHELL: ""
TERM: alacritty
@@ -33,6 +35,7 @@ Usage: wt step [OPTIONS] <COMMAND>
rebase Rebase onto target
copy-ignored Copy gitignored files to another worktree
for-each [experimental] Run command in each worktree
+ relocate [experimental] Move worktrees to expected paths
Options:
-h, --help Print help (see more with '--help')
diff --git a/tests/snapshots/integration__integration_tests__step_relocate__relocate_clobber_backs_up.snap b/tests/snapshots/integration__integration_tests__step_relocate__relocate_clobber_backs_up.snap
new file mode 100644
index 000000000..50725bf60
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__step_relocate__relocate_clobber_backs_up.snap
@@ -0,0 +1,42 @@
+---
+source: tests/integration_tests/step_relocate.rs
+info:
+ program: wt
+ args:
+ - step
+ - relocate
+ - "--clobber"
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
+ PATH: "[PATH]"
+ RUST_LOG: warn
+ SHELL: ""
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ WT_TEST_DELAYED_STREAM_MS: "-1"
+ WT_TEST_EPOCH: "1735776000"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+◎ Backing up _REPO_.feature → _REPO_.feature.bak-20250102-000000
+✓ Relocated feature: _PARENT_/wrong-location → _REPO_.feature
+
+✓ Relocated 1 worktree
diff --git a/tests/snapshots/integration__integration_tests__step_relocate__relocate_clobber_refuses_worktree.snap b/tests/snapshots/integration__integration_tests__step_relocate__relocate_clobber_refuses_worktree.snap
new file mode 100644
index 000000000..ea1c6847c
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__step_relocate__relocate_clobber_refuses_worktree.snap
@@ -0,0 +1,43 @@
+---
+source: tests/integration_tests/step_relocate.rs
+info:
+ program: wt
+ args:
+ - step
+ - relocate
+ - "--clobber"
+ - alpha
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
+ PATH: "[PATH]"
+ RUST_LOG: warn
+ SHELL: ""
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ WT_TEST_DELAYED_STREAM_MS: "-1"
+ WT_TEST_EPOCH: "1735776000"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+▲ Skipping alpha (target is worktree for beta)
+↳ Relocate or remove beta first
+
+○ Relocated 0 worktrees, skipped 1 worktree
diff --git a/tests/snapshots/integration__integration_tests__step_relocate__relocate_dirty_with_commit.snap b/tests/snapshots/integration__integration_tests__step_relocate__relocate_dirty_with_commit.snap
new file mode 100644
index 000000000..9f6580ca2
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__step_relocate__relocate_dirty_with_commit.snap
@@ -0,0 +1,44 @@
+---
+source: tests/integration_tests/step_relocate.rs
+info:
+ program: wt
+ args:
+ - step
+ - relocate
+ - "--commit"
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
+ PATH: "[PATH]"
+ RUST_LOG: warn
+ SHELL: ""
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ WT_TEST_DELAYED_STREAM_MS: "-1"
+ WT_TEST_EPOCH: "1735776000"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+◎ Committing changes in feature...
+  chore: auto-commit before relocate
+✓ Committed changes @ [HASH]
+✓ Relocated feature: _PARENT_/wrong-location → _REPO_.feature
+
+✓ Relocated 1 worktree
diff --git a/tests/snapshots/integration__integration_tests__step_relocate__relocate_dirty_without_commit.snap b/tests/snapshots/integration__integration_tests__step_relocate__relocate_dirty_without_commit.snap
new file mode 100644
index 000000000..eccbb42ea
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__step_relocate__relocate_dirty_without_commit.snap
@@ -0,0 +1,41 @@
+---
+source: tests/integration_tests/step_relocate.rs
+info:
+ program: wt
+ args:
+ - step
+ - relocate
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
+ PATH: "[PATH]"
+ RUST_LOG: warn
+ SHELL: ""
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ WT_TEST_DELAYED_STREAM_MS: "-1"
+ WT_TEST_EPOCH: "1735776000"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+▲ Skipping feature (uncommitted changes)
+↳ Use --commit to auto-commit changes before relocating
+
+○ Skipped 1 worktree
diff --git a/tests/snapshots/integration__integration_tests__step_relocate__relocate_dry_run.snap b/tests/snapshots/integration__integration_tests__step_relocate__relocate_dry_run.snap
new file mode 100644
index 000000000..90af205a6
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__step_relocate__relocate_dry_run.snap
@@ -0,0 +1,40 @@
+---
+source: tests/integration_tests/step_relocate.rs
+info:
+ program: wt
+ args:
+ - step
+ - relocate
+ - "--dry-run"
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
+ PATH: "[PATH]"
+ RUST_LOG: warn
+ SHELL: ""
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ WT_TEST_DELAYED_STREAM_MS: "-1"
+ WT_TEST_EPOCH: "1735776000"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+○ 1 worktree would be relocated:
+  feature: _PARENT_/wrong-location → _REPO_.feature
diff --git a/tests/snapshots/integration__integration_tests__step_relocate__relocate_empty_default_branch.snap b/tests/snapshots/integration__integration_tests__step_relocate__relocate_empty_default_branch.snap
new file mode 100644
index 000000000..cc205a13b
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__step_relocate__relocate_empty_default_branch.snap
@@ -0,0 +1,38 @@
+---
+source: tests/integration_tests/step_relocate.rs
+info:
+ program: wt
+ args:
+ - step
+ - relocate
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
+ PATH: "[PATH]"
+ RUST_LOG: warn
+ SHELL: ""
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ WT_TEST_DELAYED_STREAM_MS: "-1"
+ WT_TEST_EPOCH: "1735776000"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: false
+exit_code: 1
+----- stdout -----
+
+----- stderr -----
+✗ Cannot determine default branch; set with: wt config state default-branch set main
diff --git a/tests/snapshots/integration__integration_tests__step_relocate__relocate_locked_worktree.snap b/tests/snapshots/integration__integration_tests__step_relocate__relocate_locked_worktree.snap
new file mode 100644
index 000000000..eea456f25
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__step_relocate__relocate_locked_worktree.snap
@@ -0,0 +1,40 @@
+---
+source: tests/integration_tests/step_relocate.rs
+info:
+ program: wt
+ args:
+ - step
+ - relocate
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
+ PATH: "[PATH]"
+ RUST_LOG: warn
+ SHELL: ""
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ WT_TEST_DELAYED_STREAM_MS: "-1"
+ WT_TEST_EPOCH: "1735776000"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+▲ Skipping feature (locked)
+
+○ Skipped 1 worktree
diff --git a/tests/snapshots/integration__integration_tests__step_relocate__relocate_main_worktree.snap b/tests/snapshots/integration__integration_tests__step_relocate__relocate_main_worktree.snap
new file mode 100644
index 000000000..442b907ea
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__step_relocate__relocate_main_worktree.snap
@@ -0,0 +1,41 @@
+---
+source: tests/integration_tests/step_relocate.rs
+info:
+ program: wt
+ args:
+ - step
+ - relocate
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
+ PATH: "[PATH]"
+ RUST_LOG: warn
+ SHELL: ""
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ WT_TEST_DELAYED_STREAM_MS: "-1"
+ WT_TEST_EPOCH: "1735776000"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+◎ Switching main worktree to main...
+✓ Relocated feature: _REPO_ → _REPO_.feature
+
+✓ Relocated 1 worktree
diff --git a/tests/snapshots/integration__integration_tests__step_relocate__relocate_mixed_success_and_skip.snap b/tests/snapshots/integration__integration_tests__step_relocate__relocate_mixed_success_and_skip.snap
new file mode 100644
index 000000000..e8d69c1c0
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__step_relocate__relocate_mixed_success_and_skip.snap
@@ -0,0 +1,41 @@
+---
+source: tests/integration_tests/step_relocate.rs
+info:
+ program: wt
+ args:
+ - step
+ - relocate
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
+ PATH: "[PATH]"
+ RUST_LOG: warn
+ SHELL: ""
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ WT_TEST_DELAYED_STREAM_MS: "-1"
+ WT_TEST_EPOCH: "1735776000"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+▲ Skipping feature2 (locked)
+✓ Relocated feature1: _PARENT_/wrong-location-1 → _REPO_.feature1
+
+○ Relocated 1 worktree, skipped 1 worktree
diff --git a/tests/snapshots/integration__integration_tests__step_relocate__relocate_multiple.snap b/tests/snapshots/integration__integration_tests__step_relocate__relocate_multiple.snap
new file mode 100644
index 000000000..3d1cd68e7
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__step_relocate__relocate_multiple.snap
@@ -0,0 +1,44 @@
+---
+source: tests/integration_tests/step_relocate.rs
+info:
+ program: wt
+ args:
+ - step
+ - relocate
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
+ PATH: "[PATH]"
+ RUST_LOG: warn
+ SHELL: ""
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ WT_TEST_DELAYED_STREAM_MS: "-1"
+ WT_TEST_EPOCH: "1735776000"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+✓ Relocated feature-1: _PARENT_/wrong-1 → _REPO_.feature-1
+✓ Relocated feature-2: _PARENT_/wrong-2 → _REPO_.feature-2
+✓ Relocated feature-3: _PARENT_/wrong-3 → _REPO_.feature-3
+✓ Relocated feature-4: _PARENT_/wrong-4 → _REPO_.feature-4
+✓ Relocated feature-5: _PARENT_/wrong-5 → _REPO_.feature-5
+
+✓ Relocated 5 worktrees
diff --git a/tests/snapshots/integration__integration_tests__step_relocate__relocate_no_mismatches.snap b/tests/snapshots/integration__integration_tests__step_relocate__relocate_no_mismatches.snap
new file mode 100644
index 000000000..528408121
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__step_relocate__relocate_no_mismatches.snap
@@ -0,0 +1,38 @@
+---
+source: tests/integration_tests/step_relocate.rs
+info:
+ program: wt
+ args:
+ - step
+ - relocate
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
+ PATH: "[PATH]"
+ RUST_LOG: warn
+ SHELL: ""
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ WT_TEST_DELAYED_STREAM_MS: "-1"
+ WT_TEST_EPOCH: "1735776000"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+○ All worktrees are at expected paths
diff --git a/tests/snapshots/integration__integration_tests__step_relocate__relocate_same_target_no_panic.snap b/tests/snapshots/integration__integration_tests__step_relocate__relocate_same_target_no_panic.snap
new file mode 100644
index 000000000..6440fcb02
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__step_relocate__relocate_same_target_no_panic.snap
@@ -0,0 +1,43 @@
+---
+source: tests/integration_tests/step_relocate.rs
+info:
+ program: wt
+ args:
+ - step
+ - relocate
+ - alpha
+ - beta
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
+ PATH: "[PATH]"
+ RUST_LOG: warn
+ SHELL: ""
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ WT_TEST_DELAYED_STREAM_MS: "-1"
+ WT_TEST_EPOCH: "1735776000"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+✓ Relocated alpha: _PARENT_/wrong-location-1 → _REPO_/repo.shared
+▲ Skipping beta (target occupied: _REPO_/repo.shared)
+
+○ Relocated 1 worktree, skipped 1 worktree
diff --git a/tests/snapshots/integration__integration_tests__step_relocate__relocate_single_mismatch.snap b/tests/snapshots/integration__integration_tests__step_relocate__relocate_single_mismatch.snap
new file mode 100644
index 000000000..5a98de048
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__step_relocate__relocate_single_mismatch.snap
@@ -0,0 +1,40 @@
+---
+source: tests/integration_tests/step_relocate.rs
+info:
+ program: wt
+ args:
+ - step
+ - relocate
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
+ PATH: "[PATH]"
+ RUST_LOG: warn
+ SHELL: ""
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ WT_TEST_DELAYED_STREAM_MS: "-1"
+ WT_TEST_EPOCH: "1735776000"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+✓ Relocated feature: _PARENT_/wrong-location → _REPO_.feature
+
+✓ Relocated 1 worktree
diff --git a/tests/snapshots/integration__integration_tests__step_relocate__relocate_specific_branch.snap b/tests/snapshots/integration__integration_tests__step_relocate__relocate_specific_branch.snap
new file mode 100644
index 000000000..d981936de
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__step_relocate__relocate_specific_branch.snap
@@ -0,0 +1,41 @@
+---
+source: tests/integration_tests/step_relocate.rs
+info:
+ program: wt
+ args:
+ - step
+ - relocate
+ - feature1
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
+ PATH: "[PATH]"
+ RUST_LOG: warn
+ SHELL: ""
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ WT_TEST_DELAYED_STREAM_MS: "-1"
+ WT_TEST_EPOCH: "1735776000"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+✓ Relocated feature1: _PARENT_/wrong-location-1 → _REPO_.feature1
+
+✓ Relocated 1 worktree
diff --git a/tests/snapshots/integration__integration_tests__step_relocate__relocate_swap.snap b/tests/snapshots/integration__integration_tests__step_relocate__relocate_swap.snap
new file mode 100644
index 000000000..67f2d5fbf
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__step_relocate__relocate_swap.snap
@@ -0,0 +1,42 @@
+---
+source: tests/integration_tests/step_relocate.rs
+info:
+ program: wt
+ args:
+ - step
+ - relocate
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
+ PATH: "[PATH]"
+ RUST_LOG: warn
+ SHELL: ""
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ WT_TEST_DELAYED_STREAM_MS: "-1"
+ WT_TEST_EPOCH: "1735776000"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+◎ Moving beta to temporary location...
+✓ Relocated alpha: _REPO_.beta → _REPO_.alpha
+✓ Relocated beta: _REPO_.alpha → _REPO_.beta
+
+✓ Relocated 2 worktrees
diff --git a/tests/snapshots/integration__integration_tests__step_relocate__relocate_target_exists.snap b/tests/snapshots/integration__integration_tests__step_relocate__relocate_target_exists.snap
new file mode 100644
index 000000000..3b3c23b91
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__step_relocate__relocate_target_exists.snap
@@ -0,0 +1,41 @@
+---
+source: tests/integration_tests/step_relocate.rs
+info:
+ program: wt
+ args:
+ - step
+ - relocate
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
+ PATH: "[PATH]"
+ RUST_LOG: warn
+ SHELL: ""
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ WT_TEST_DELAYED_STREAM_MS: "-1"
+ WT_TEST_EPOCH: "1735776000"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+▲ Skipping feature (target blocked: _REPO_.feature)
+↳ Use --clobber to backup blocking paths
+
+○ Relocated 0 worktrees, skipped 1 worktree
diff --git a/tests/snapshots/integration__integration_tests__step_relocate__relocate_template_error.snap b/tests/snapshots/integration__integration_tests__step_relocate__relocate_template_error.snap
new file mode 100644
index 000000000..d376711bd
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__step_relocate__relocate_template_error.snap
@@ -0,0 +1,41 @@
+---
+source: tests/integration_tests/step_relocate.rs
+info:
+ program: wt
+ args:
+ - step
+ - relocate
+ - feature
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
+ PATH: "[PATH]"
+ RUST_LOG: warn
+ SHELL: ""
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ WT_TEST_DELAYED_STREAM_MS: "-1"
+ WT_TEST_EPOCH: "1735776000"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+▲ Skipping feature due to template error:
+  Failed to format worktree path: Template render error: undefined value (in worktree-path:1)
+○ No relocations performed; 1 skipped due to template error